![](/img/trans.png)
[英]Read text from in Excel ActiveX TextBox with python's xlwings
[英]How to read a text from dynamic added TextBox?
我有一个关于如何从动态添加的 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”。 我写了一个 function 来在每个新的文本框中找到一个文本:
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
我使用这个 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
命令的第二个参数完成的。 在您的代码中,您为代码和注释提供相同名称的控件,因此FindName
-函数只能找到其中一个。 看看下面的代码 - 它创建名称像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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.