如何检查对象是否为用户窗体?

时间:2019-05-13 22:03:08

标签: vba userform

我正在研究可以侦听UserForm中发生的所有事件(包括UserForm本身)的代码。

main方法采用 MSForms.Control MSForms.UserForm作为其主要参数。为了适应这两个选项,参数作为对象传递(见下文)。

Public Sub AddEventListner(ByRef ControlOrForm As Object)
  'Do next steps for adding listeners...
End Sub

如何检查用户表单是否是传入的对象?

我想出的解决方案是在VBA.UserForms中循环每个用户窗体,并检查其名称是否与传入的对象相匹配。但是,我想看看是否有一个更可靠的解决方案,而不是依赖于名称匹配?

'CHECK TO SEE IF OBJ IS A USERFORM
Private Function IsUserform(ByRef Obj As Object) As Boolean

    Dim Form As Object
    For Each Form In VBA.UserForms

      'IF NAME MATCHES THEN IT MUST BE A USERFORM
      On Error GoTo NotUserform
      If Form.Name = Obj.Name Then
        IsUserform = True
        Exit Function
      End If

    Next

NotUserform:

End Function

1 个答案:

答案 0 :(得分:2)

尚未测试,但也许是这样的:

Private Function IsUserform(ByRef Obj As Object) As Boolean

      If TypeOf Obj Is MSForms.UserForm Then
        IsUserform = True
      Else 
        IsUserform = False
      End If

End Function

它至少避免循环。