Home » excel » excel – Append Procedure to Event upon User Action

excel – Append Procedure to Event upon User Action

Posted by: admin April 23, 2020 Leave a comment


Say, I have a procedure which changes the random colour of a cell based on selection change. I know that I can code in a procedure for the worksheet SelectionChange event.

I guess Im asking, as in javascript where we can use addEventListeners, can we do something similar in Excel VBA.

enter image description here

What I am wondering is can this be done dynamically? I.e. when a user chooses an option, then I bind a procedure to the event SelectionChange of the worksheet.

Note, I know that I could declare a global boolean & use that to ascertain user action & use it in my SelectionChange event procedure.

Im just curious whether in Excel VBA, we can dynamically append procedures to events?

How to&Answers:

You can’t dynamically assign event handlers. Excel will always call the built-in event handlers (SelectionChange, Calculate, etc) and there’s no way to substitute your own. You can create your own Worksheet variable using the WithEvents keyword, however, and choose when to start receiving the events. For example, start with this structure in one of your worksheets:

Dim WithEvents MySheet As Worksheet

Private Sub MySheet_SelectionChange(ByVal Target As Range)

    Debug.Print "Receiving events"

End Sub

As long as MySheet isn’t bound to an active sheet, you’re not going to receive any events. When you’re ready to begin, call a custom subroutine to do the assignment:

Public Sub DoIt()

    Set MySheet = Sheet1

End Sub