Macro Errors in Excel

 

This chapter teaches you how to fix macro errors in Excel. First, let's create some errors.

Place a command button on your worksheet and add the following code lines:

x = 2
Range("A1").Valu = x

1. Click the command button on the sheet.

Result:

Compile Error in Excel VBA

2. Click OK.

The variable x is not defined. Because we are using the Option Explicit statement at the start of our code, we have to declare all our variables. Excel VBA has colored the x blue to indicate the error.

3. In the Visual Basic Editor, click Reset to stop the debugger.

Click Reset

4. Correct the error by adding the following code line at the start of the code.

Dim x As Integer

You may have heard of the technique called debugging before. With this technique you can step through your code.

5. In the Visual Basic Editor, place your cursor before Private and press F8.

The first line turns yellow.

First Line Turns Yellow

6. Press F8 three more times.

Press F8 Three More Times

The following error appears.

Run-time Error

The Range object has a property called Value. Value isn't spelled correctly here. Debugging is a great way to not only find errors, but also understand code better. Our Debugging example program shows you how to single step through your code and see the effect of each code line on your worksheet.