Events in Excel VBA

Events in Excel VBA are user actions that automatically trigger specific code to run in response.

Workbook Open Event

Code inside the Workbook Open Event will start running automatically when you open the Excel file.

1. Open the Visual Basic Editor.

2. Open the Project Explorer, then double-click on “ThisWorkbook” to view its code.

3. Choose Workbook from the left menu, and then select Open from the right menu.

Events in Excel VBA

4. Copy and paste the following code into the Workbook Open event of the workbook:

MsgBox “Good Morning”

5. Now save your file, then close it and re-open it again.

Result:

Worksheet Change Event

If you write code in the Worksheet Change Event, it will be triggered whenever you make a change to any cell on the worksheet.

1. Open the Visual Basic Editor.

2. In the Project Explorer window, double-click “Sheet1” or any other sheet you want to work with.

3. Choose Worksheet from the left drop-down list. From the dropdown on the right side, choose Change.

Open the Visual Basic Editor and put this code in the Worksheet Change event:

4. The Worksheet Change Event runs automatically whenever something is modified on Sheet1. We want the VBA code to run only when there is a change in cell B2. To do this, insert the following lines of code into your script or program file:

If Target.Address = "$B$2" Then

End If

5. Want to show a message box in Excel VBA only when the input number is higher than 78. To do this, insert the following line of code between If and End If.

If Target.Value > 78  Then MsgBox "Goal Completed"

6. Go to Sheet1, select cell B2, and type a number greater than 78. In our case, we use 81 as shown in the attached picture.

Result:

1/6 Completed! Learn much more about events ➝
Next Chapter: Array