Excel VBA Userform - Execute Sub when something changes

前端 未结 7 483
攒了一身酷
攒了一身酷 2020-12-01 15:09

I have a userform containing lots of text boxes. When ever the values of these text boxes changes, I need to recalculate my end result values based on the textbox values by

7条回答
  •  醉梦人生
    2020-12-01 15:53

    Two Class Module Method

    I've created a very easy way to add event listeners to a userform. Additionally, it adds events such as MouseOver and MouseOut. (Cool for doing hover effects)

    The two class modules that need to be imported in order to work can be found on my Github page VBA Userform Event Listeners


    How to use the code in a Userform

    It's easy to get started, once you add my class modules, simple add the sample code below to a Userform.

    Private WithEvents Emitter As EventListnerEmitter
        
    Private Sub UserForm_Activate()
       Set Emitter = New EventListnerEmitter
       Emitter.AddEventListnerAll Me
    End Sub
    

    That's it! Now you can start listening for different events.


    The Main Event Listener

    There is the main event EmittedEvent. This passes in the control that the event on, and the event name. So all events go through this event handler.

    Private Sub Emitter_EmittedEvent(Control As Object, ByVal EventName As String, EventValue As Variant)
        
        If TypeName(Control) = "Textbox" And EventName = "Change" Then
            'DO WHATEVER
        End If
      
    End Sub
    

    Individual Event Listeners

    You can also just listen for the specific events. o in this case the change event.

    Private Sub Emitter_Change(Control As Object)
    
        If TypeName(Control) = "Textbox" Then
              'DO WHATEVER
        End If
        
    End Sub
    

    Please feel free to check out my Github page and make a pull request as not all the events are being captured yet.

提交回复
热议问题