excel - 如何从动态添加的文本框中读取文本?
问题描述
我有一个关于如何从动态添加的 TextBox 中读取文本的问题。在我的用户窗体中,我有一个文本框,在这个文本框中我放了一些我想要添加的新文本框。从这个文本框我添加了两个新的动态文本框。
Set Ctrl = .Add("Forms.TextBox.1", Window.Name + CStr(i)) 'TextBox for code
With Ctrl
.Width = 32
.Height = 16
.Top = TopPos
.Left = 6
.Value = Chr(64 + i) + CStr(10 + i)
.MaxLength = 4
.ZOrder (0)
End With
Set Ctrl = .Add("Forms.TextBox.1", Window.Name + CStr(i)) 'TextBox for comment
With Ctrl
.Width = 240
.Height = 16
.Top = TopPos
.Left = 44
.MaxLength = 50
.ZOrder (0)
End With
TextBoxes 的第一列自动填充一个字母和一个数字,第二列为我的评论是空的。使用“完成”按钮,我想将两个 TextBoxes 中的文本导出到两个单元格 - TextBoxes 第一列中的文本到单元格“A”,TextBoxes 第二列中的文本到新文件中的单元格“B”。我编写了一个函数来在每个新的 TextBox 中查找文本:
Function FindName(Iter As Integer, Name As String) As String
Dim Text As String
Dim Ctrl As Control
For Each Ctrl In UserForm1.Controls
If Ctrl.Name = Name Then
Text = Ctrl.Text
End If
Next Ctrl
FindName = Text
End Function
我使用此函数用 TextBoxes 中的文本填充新 Excel,但问题是,文本仅从第二列导出到新文件:
NewFile.Worksheets(1).Cells(StartValue + i, 1) = FindName(i, "TextBox1" + CStr(i))
NewFile.Worksheets(1).Cells(StartValue + i, 2) = FindName(i, "TextBox1" + CStr(i))
是否有任何解决方案如何区分文本与第一列文本框和第二列文本框以将文本从第一个文本框导出到一个单元格并从第二个文本框导出到另一个单元格?
感谢您的帮助。
解决方案
当您按名称检索控件时,您需要为它们提供唯一的名称。这是通过.Add
-command 的第二个参数完成的。在您的代码中,您为代码和注释提供相同名称的控件,因此FindName
-function 只能找到其中一个。看看下面的代码——它会创建名称为tbCode_1
和的文本框tbComment_1
——如果你不喜欢它,可以根据你的个人喜好更改它。
Set Ctrl = .Add("Forms.TextBox.1", "tbCode_" & CStr(i)) 'TextBox for code
(...)
Set Ctrl = .Add("Forms.TextBox.1", "tbComment_" & CStr(i)) 'TextBox for comment
你的FindName
-function 可能看起来像
Function FindName(Iter As Integer, colName As String) As String
Dim ctrlName as String
ctrlName = "tb" & colName & "_" & CStr(i)
On Error Resume Next
FindName = Me.Controls(ctrlName).Text
On Error Goto 0
End Function
你用它来称呼它
NewFile.Worksheets(1).Cells(StartValue + i, 1) = FindName(i, "Code")
NewFile.Worksheets(1).Cells(StartValue + i, 2) = FindName(i, "Comment")
推荐阅读
- javascript - 从 ajax/jquery 中的 post 请求中获取响应数据
- c++ - Bluez GATT 服务器(外围)安全特性读取
- ios - MKMarkerAnnotationView 在 iPhone X 上不显示
- function - 如何使用任意类型作为函数参数?
- java - 给定集合名称(ArrayList、LinkedList 等)和集合中的项目,如何创建任何集合?
- flutter - 颤振-Futurebuilder 在位置许可后不断返回 null
- javascript - 如何修复递归 hcf 函数?
- javascript - 检测 txt 中的 URL
- observable - RxJava 2 Flowable 是热的还是冷的?
- xamarin.forms - 有没有办法在内容页面中有一个标签页