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
addEventListeners, can we do something similar in Excel VBA.
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?
You can’t dynamically assign event handlers. Excel will always call the built-in event handlers (
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