VBA- 检查是否加载了特定的用户表单

VBA- Check if a particular userform is Loaded or not

我想在 运行 代码时检查是否加载了用户表单。我尝试了几种方法,没有人在工作。我记得我以前做过,但我不记得我的解决方法。任何的想法?

我在这里和其他地方找到了一些解决方案,但它们也没有用!

问题是……

  1. vba.userforms 只接受索引号,不接受字符串索引,
  2. 在遍历用户表单时,某些属性(如名称)无法访问以进行检查!

这是我的尝试:

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

这里有两个简单的选项。首先,您可以将 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

我已经让这两个都不区分大小写了。

如果您确实需要测试可见性,我认为 IsFormVisible 的代码只是遗漏了一行代码。

HINT 问题正如 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 将 return 为真,尽管表单不可见。

    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

“我想在 运行 代码时检查是否加载了用户表单。”是问题。

在VBA中Excel如果你检查表单是否可见

If Form2.Visible Then
    'code here
End If

然后表单将在后台加载! 如果加载过程需要很长时间,那就不好了! 所以 最佳解决方案是

Function IsTheFormLoaded(frmName As String)
    'Works for VBA Excel office Xp 2002
    'Returns true if found or false if not found
    Dim Frm 'As UserForm dont declare as UserForm you wont get the frm.Name proptery below
    Dim Found As Boolean
    Found = False
    For Each Frm In VBA.UserForms
      If frmName = Frm.Name Then
         Found = True
         Exit For
      End If
    Next
     IsTheFormLoaded = Found
End Function