代码之家  ›  专栏  ›  技术社区  ›  Mahhdy

VBA-检查是否加载了特定的用户窗体

  •  1
  • Mahhdy  · 技术社区  · 6 年前

    我想检查在运行代码时是否加载了userform。我试了好几种方法,没人管用。我记得我以前做过,但我想不起来我的解决方法。你知道吗?

    我在这里和其他地方找到了一些解决方案,它们也不起作用!

    1. userforms只接受索引号,而不是字符串索引,

    以下是我的尝试:

    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
    
    2 回复  |  直到 4 年前
        1
  •  5
  •   Rory    6 年前

    这里有两个简单的选择。首先,你可以申报 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
    

        2
  •  1
  •   Storax    6 年前

    IsFormVisible 如果您真的需要测试可见性,只会遗漏一行代码。

    这个问题正如Rory正确地指出的,关于是否加载了userform。对于这个问题,他的回答是绝对正确的。

    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
    

        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