显示基于变量字符串输入的表单

时间:2015-12-15 22:33:59

标签: excel-vba vba excel

是否可以根据字符串变量显示类似Form_1.show的表单,例如工作表或类似控件

Private Sub Demo()
    Dim i As Long
    For i = 1 To 10
        me.Controls("Label_" & i) = Rnd()
    Next i

    'Or select a worksheet based on an input

    With Me.ListBox1
        For i = 1 to 5
            .additem Cstr("Sheet" & i)
        Next i
    End With

    ThisWorkBook.Worksheets(me.ListBox1).Activate
End Sub

基本上我要做的是根据表单中列表框的选择显示Form1到10,而不是编写很多If语句是否可以更改显示的表单根据选择?

以下是目前的情况。

Private Sub Worksheet_Activate()
    Dim Table1 as ListObject
    Set Table1 = Thisworkbook.Worksheets("Sheet1").Listobjects("Forms_List")
    Dim Rows As Long
    Rows = Table1.ListRows.Count
    Dim i As Long

    With Me.ListBox1
        For i = 1 To Rows
            .AddItem Table1.DataBodyRange(i, 1)
        Next i
    End With
End Sub

Private Sub ListBox1_dblclick(ByVal Cancel As MSForms.ReturnBoolean) 
    'This is what I want to avoid, mainly because it isn't flexible
    If Me.ListBox1 = "Form1" Then Form1.Show
    If Me.ListBox1 = "Form2" Then Form2.Show
    If Me.ListBox1 = "Form3" Then Form3.Show
    If Me.ListBox1 = "Form4" Then Form4.Show
    If Me.ListBox1 = "Form5" Then Form5.Show
    If Me.ListBox1 = "Form6" Then Form6.Show
    If Me.ListBox1 = "Form7" Then Form7.Show
    If Me.ListBox1 = "Form8" Then Form8.Show
    If Me.ListBox1 = "Form9" Then Form9.Show
    If Me.ListBox1 = "Form10" Then Form10.Show
End Sub

1 个答案:

答案 0 :(得分:2)

尝试使用:

VBA.UserForms.Add(Me.ListBox1).Show

来源: How to Display a UserForm Whose Name Is in a Variable