根据名称将文本框值分配给相应的单元格

我在窗体上有一组文本框,称为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