VBA:无法找到control.add循环创建的文本框的名称

时间:2017-05-16 06:08:48

标签: vba controls

我使用control.add循环创建了文本框,但我无法更改其值。我想要他们的名字tb1,tb2 ......

    Private Sub UserForm_Initialize()
    For i = 1 To 10
    Dim cCntrl As Control
        Set cCntrl = Me.Controls.Add("Forms.textbox.1", "tb" & i)
   Next
   tb4 = "b"
   End Sub

1 个答案:

答案 0 :(得分:0)

您无法通过名称访问控件,因为编译器不知道这些名称。相反,您可以将控件分配给数组。您可能不仅希望在初始化时访问控件,因此将其声明为全局。

Option Explicit

Dim ctrlArr(1 To 10) As Control, i As Long

Private Sub UserForm_Initialize()

    For i = 1 To 10
        Set ctrlArr(i) = Me.Controls.Add("Forms.textbox.1", "tb" & i)
        ctrlArr(i).Top = i * 20
    Next
    ctrlArr(4).value = "b"

End Sub