Macro Errors in Excel
You will learn how to check and correct macro errors in Excel. First, let’s create some errors.
Add a command button to your worksheet and insert the code lines shown below:
x = 2 Range("A1").Valu = x
1. Press the command button.
Result:
2. Click OK.
The variable x is not defined. Because of Option Explicit (Used at the beginning of our code), we need to declare every variable before using it. When there is an error, Excel VBA marks the x in blue to help you identify it.
3. Press Reset in Visual Basic Editor to stop debugging immediately.
4. To fix the error, add the following line of code at the beginning of your script.
Dim x As Integer
You may have previously learned about a method known as debugging. This method helps you to execute and check your code line by line.
5. Inside the Visual Basic Editor, place the cursor in front of the word Private, then press F8 to begin running the code line by line.
The first line turns yellow.
6. Press F8 three more times.
The following error appears.
The Range object has a property called Value. Value isn’t spelled correctly here. Debugging helps you find errors in your code and also improves your understanding of how it works. Our debugging example program demonstrates how to go through your code one step at a time and observe how each line affects your worksheet.
1/7 Completed! Explore more about macro errors ➝
Next Chapter: String Manipulation