且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用vba在运行时将多个标签和文本框添加到Excel用户窗体

更新时间:2023-12-06 11:49:10

该问题的答案具有误导性.该问题想在通过更改控件的ProgID添加控件时提供默认名称(bstrProgID是引用要创建的类的字符串).

Lou the answer to the question is misleading. The question wants to provide a default name when adding the control by changing its ProgID ( bstrProgID is a string that references the class that is to be created).

如果另一个控件没有相同的名称,则可以重命名新控件.

You can rename the new controls provided that another control does not have the same name.

您还可以将控件名称作为参数传递给Controls.Add方法.

You can also pass the controls name as an argument to the Controls.Add method.

您未显示的标签是您从未设置Label.Caption值.

Your labels are not showing is that you never set the Label.Caption value.

Private Sub CreateControl()
    Dim newLbl As MSForms.Label
    Dim newTxt As MSForms.Control
    Dim i As Integer, TopAmt
    Dim UserArray As Variant

    TopAmt = 50
    UserArray = Array("Cat", "Dog", "Horse", "Gorrilla")

    For i = LBound(UserArray) To UBound(UserArray)
        Set newLbl = MultipleOptionForm.Controls.Add("Forms.Label.1")
        With newLbl
            .Name = "Label" & i
            .Left = 50
            .Top = TopAmt
            .Visible = True
            .Caption = UserArray(i)
            Debug.Print .Name,
        End With

        Set newTxt = MultipleOptionForm.Controls.Add(bstrProgID:="Forms.Textbox.1", Name:="Textbox" & i)
        With newTxt
            .Left = 100
            .Top = TopAmt
            .Visible = True
            Debug.Print .Name
        End With
        TopAmt = TopAmt + newTxt.Height
    Next
End Sub


下一期:如何从这些动态创建的文本框中获取数据?

Dim newTxt As MSForms.Control
For i = LBound(UserArray) To UBound(UserArray)
    set newTxt  =  MultipleOptionForm.Controls("Textbox" & i)
    If UserArray(i) <> newTxt.Value then
        'Do something
    End if
Next