excel Userforms.show与通过VBA.UserForms.Collection循环获取UserForms作为Object的比较

wbrvyc0a  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(78)

我想安全地选择用户表单,而不会意外地加载用户表单的新示例,同时我想避免太多的代码。到目前为止,我已经直接处理了用户表单,即。使用用户表单的标题,例如

Userform1.Show

字符串
但我经常需要或想要在VBA.project中按名称搜索和加载用户表单,因为这样可以简化一些功能。但是由于我使用了这两种变体,根据代码的执行方式,创建了第二个instant。我不想这样。我可以将任何直接调用(Userform1.Show)转换为Show_Userform(“Userform1”),但还有许多其他函数直接使用Userform1,我必须首先将它们全部转换为对象才能继续编写。
我真实的的问题是,当调用UserForm1.Show加载已经加载的示例Show_Userform(“UserForm1”)而不是创建一个新示例时,是否有一种安全的方法?我通读了Difference between declaring a userform as Object vs MSForms.Userform?,这很有帮助,但我的问题没有描述

Sub Test_Works()
Dim obj As Object
    
    UserForm1.Show (False)
    Show_Userform ("UserForm1")

End Sub

x

Sub Test_Creats_Second_Instance()
Dim obj As Object
    
    'Is there a way to avoid that second instance being created?
    Show_Userform ("UserForm1")
    UserForm1.Show (False)

End Sub
Sub Show_Userform(sName As String)

Dim obj As Object
    
    '~~> Set userform if still loaded
    For Each obj In VBA.UserForms
        If StrComp(obj.Name, sName, vbTextCompare) = 0 Then
            obj.Show (False)
            Exit Sub
        End If
    Next obj
    
    '~~> Get userform if not loaded yet
    On Error Resume Next
        Set obj = VBA.UserForms.Add(sName) 'triggers Initialize of the Userform
            obj.Show (False)
    On Error GoTo 0
    
End Sub

的字符串

pod7payv

pod7payv1#

根据Greg的建议,我找到了一个解决问题的好方法:

Sub Test_Solution()

Dim obj As Object

   'creates no second instance
   Set obj = Get_Userform("UserForm1")
   obj.Show (False)
   UserForm1.Show (False)

End Sub
Function Get_Userform(sName As String) As Object

Dim obj As Object

    '~~> Set userform if still loaded
    For Each obj In VBA.UserForms
        If StrComp(obj.Name, sName, vbTextCompare) = 0 Then
            Set Get_Userform = obj
            Exit Function
        End If
    Next obj

    '~~> Get userform if not loaded yet
    Select Case sName
        Case "UserForm1": Set Get_Userform = UserForm1
        Case "UserForm2": Set Get_Userform = UserForm2
        Case Else: Err.Raise vbObjectError, , "Error in Get_Userform: sName not defined"
    End Select

End Function

相关问题