从以编程方式添加的 vba 文本框中保存数据

Saving data from a programmatically added vba text box

我正在尝试创建一个函数,该函数根据用户所需的文本框数量以编程方式将文本框添加到空白用户窗体。

目前我有一个函数可以执行此操作,但是我无法保存文本框的值。我已尝试通过多种方式引用文本框,但是其中 none 似乎有效(尽管之前在单独的代码中使用相同的方法,尽管所讨论的文本框不是以编程方式添加的)

Function addtxtbox(number_of_textboxes As Integer)

Dim option_names As New UserForm2
Dim names As String
Dim test As String   
Dim textbox  As Object
Dim submit As Object

For i = 1 To number_of_textboxes
    Set textbox = option_names.Controls.Add("Forms.textbox.1")
    With textbox
        .Left = 30
        .Width = 200
        .Top = 20 * i
        .Left = 20
    End With

    MsgBox (textbox.Name)'used to find the name of the textboxes

Next

option_names.Show

names = "TextBox1" 'correct name of the 1st textbox according to the msgbox above.
MsgBox (names) 'msgbox is always blank
test = option_names.names 'Compile error: Method or data members not found
'test = textbox.TextBox1.Value 'run time error 418 object does not support this property or method
MsgBox (test) 

End Function

用可预测的顺序命名文本框更容易:

For i = 1 To number_of_textboxes

    Set textbox = option_names.Controls.Add("Forms.textbox.1")
    With textbox
        .Left = 30
        .Width = 200
        .Top = 20 * i
        .Left = 20
        .Name = "dynamic_" & i  '<<<<<<< name the textbox
    End With

    MsgBox (textbox.Name)'used to find the name of the textboxes

Next

现在您可以使用类似的东西:

For i = 1 To number_of_textboxes

    MsgBox "Textbox# " & i & " has value '" & _
            Me.Controls("dynamic_" & i).Text & "'"

Next