按名称打开用户表单

问题描述 投票:0回答:1

我想使用它的名称打开用户表单,而不必为每个用户表单硬编码 Select Case 语句。

我试过了

VBA.UserForms(Integer).Show and
VBA.UserForms(String).Show

首先抛出错误“超出范围”。 第二个抛出错误“类型不匹配”

然后我尝试了 for every 循环:

Sub Open_UserForm(ByVal UserFormName As String)
Dim Usf As UserForm
For Each Usf in VBA.UserForms
    If Usf.Name = UserFormName Then
        Usf.Show
    End If
Next Usf
End Sub

我也尝试过使用 Usf 作为对象。 在这两种情况下,它在第一次迭代时都跳过了 For Each。

然后我用 VBProject 和 VBComponent 尝试了一下:

Workbooks(WorkbookName).VBProject.VBComponents(UserFormName).Show

我也用无模式尝试了所有这些方法。

excel vba
1个回答
0
投票

按名称显示用户表单

  • 基于 T.M. 在您的评论中建议的 Chip Pearson 的文章。
Sub ShowUserForm( _
        UserFormName As String, _
        Optional ShowMessages As Variant = False)
    
    Dim obj As Object
    
    For Each obj In VBA.UserForms
        If StrComp(obj.Name, UserFormName, vbTextCompare) = 0 Then
            If ShowMessages Then MsgBox "Was already loaded.", vbInformation
            obj.Show
            Exit Sub
        End If
    Next obj
    
    On Error Resume Next
        Set obj = VBA.UserForms.Add(UserFormName)
    On Error GoTo 0

    If obj Is Nothing Then
        MsgBox "User form """ & UserFormName & """ not found!", vbExclamation
        Exit Sub
    End If
    
    If ShowMessages Then MsgBox "Was NOT loaded.", vbInformation
    obj.Show
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.