How to assign an event to multiple objects with excel vba?

前端 未结 2 378
广开言路
广开言路 2020-12-11 19:02

I have ten drop down menus on a worksheet each of which should respond the same to the GotFocus() event.

I have written the following code but I get a ru

2条回答
  •  粉色の甜心
    2020-12-11 19:23

    The below works for me. There were a couple of problem with your code, and comboboxes don't have a GotFocus event, so you'll have to use a different one. The collection needs to be a global in the module, noty part of the class. I couldn't get this to work using the generic "OLEobject" approach (same error you got).

    ' ### in the class
    Public WithEvents inputObj As MSForms.ComboBox
    
    Private Sub inputObj_Change()
        MsgBox "Change!"
    End Sub
    
    ' ### in a module
    Dim tbCollection As Collection
    
    Public Sub InitializePDRInput()
        Dim myObj As OLEObject
        Dim obj As clsPDRInput
    
        Set tbCollection = New Collection
    
        For Each myObj In Worksheets("Sheet1").OLEObjects
            If TypeName(myObj.Object) = "ComboBox" Then
                Set obj = New clsPDRInput
                Set obj.inputObj = myObj.Object
                tbCollection.Add obj
            End If
        Next myObj
    
    End Sub
    

提交回复
热议问题