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



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

目前我有一个函数可以做到这一点,但是我无法保存文本框的值。我尝试以几种方式引用文本框,但它们似乎都不起作用(尽管之前在单独的代码中使用相同的方法,尽管有问题的文本框不是以编程方式添加的(

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

最新更新