我想在运行代码时检查是否加载了用户窗体。我尝试了几种方法,但是没有人在工作。我记得我以前做过,但是我不记得我的解决方法。任何想法?
我在这里和其他地方找到了一些解决方案,它们也无法正常工作!
问题是……
这是我的尝试:
Public Function IsFormVisible(FrmName As String) As Boolean
On Error GoTo errorH
IsFormVisible = False
Set Frm = UserForms(FrmName)
If Not Frm Is Nothing Then IsFormVisible = True
End Function
errorH:
IsFormVisible = False
End Function
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As UserForm
On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If Frm.Name = FrmName Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
答案 0 :(得分:3)
这是两个简单的选项。首先,您可以将frm
声明为Object
:
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As Object
On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If LCase$(Frm.Name) = LCase$(FrmName) Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
或者第二,您可以使用TypeName
代替.Name
:
Public Function IsFormVisible(FrmName As String) As Boolean
Dim Frm As UserForm
'On Error GoTo errorH
IsFormVisible = False
For Each Frm In VBA.UserForms
If lcase$(TypeName(Frm)) = lcase$(FrmName) Then
IsFormVisible = True
Exit Function
End If
Next
errorH:
IsFormVisible = False
End Function
我使这两种情况都不区分大小写。
答案 1 :(得分:1)
如果您确实需要测试可见性,我认为IsFormVisible
的代码只会漏掉一行代码。
提示,正如Rory正确指出的那样,有关是否加载用户表单的问题是正确的。对于这个问题,他的回答是绝对正确的。
Public Function IsFormVisibleA(FrmName As String) As Boolean
Dim Frm As Object
On Error GoTo errorH
IsFormVisibleA = False
For Each Frm In VBA.UserForms
If LCase$(Frm.Name) = LCase$(FrmName) Then
If Frm.Visible Then
IsFormVisibleA = True
Exit Function
End If
End If
Next
errorH:
IsFormVisibleA = False
End Function
您可以像这样测试它。如果只加载表单而不显示该表单,则尽管该表单不可见,但IsFormVisible函数将返回true。
Sub Testfrm()
Dim Frm As frmMy
Set Frm = New frmMy
' Frm.Show vbModeless
Debug.Print Frm.Name
Debug.Print IsFormVisibleA("frmMy"), IsFormVisible("frmMy")
End Sub