我在表单上有一组文本框,称为 sm1、sm2 等,我想将它们分配给单元格 A1、A2 等。有没有办法把它放在一个循环中,即:
For i = 1 to 100
Cells(i, 1).Value = ("sm" & c).Value
Next i
不确定 VBA,但表单上应该有“控件”集合,您可以通过控件名称访问它的元素,如上所示。
cells(i,1).Value = Controls("sm"&c).Value
另一种方法是使用ControlSource
每个文本框的属性将它们绑定到相关单元格
通过表单上的文本框,您可以使用 Controls 集合。
For Each oControl In Me.Controls
If Typename(oControl) = "TextBox" Then
iCellNumber = Val(Mid$(oControl.Name, 3)) 'Assumes all textboxes have two letter names
cells(iCellNumber ,1).Value = val(oControl.Text)
End If
Next oControl
如果控件在工作表上,您可以使用该工作表上的形状集合
For Each oControl In Me.Shapes
If InStr(oControl.Name, "TextBox") = 1 Then
iCellNumber = Val(Mid$(oControl.Name, 3))
cells(iCellNumber ,1).Value = val(oControl.Text)
End If
Next oControl