VBA如何用变量表示控件名?

VBA如何用变量表示控件名?

一个语句:labelx.caption=......

其中想用x代表数字,实现对不同空间属性的更改。

请问怎样做

如果该控件位于UserForm窗体中,那么我们可以用Controls集合来表示指定的控件,
例如,UserForm1中有三个控件,Label1,Label2,TextBox1
那么,我们可以这样表示:
a = 1 : b = 2
UserForm1.Controls("Label" & a).Caption 表示Label1.Caption
UserForm1.Controls("Label" & b).Caption 表示Label2.Caption
UserForm1.Controls("TextBox" & a).Text 表示TextBox1.Text

如果你的控件位于工作表中,那么我们可以使用OleObjects集合来表示指定的控件,
例如,Sheet1工作表中有三个控件,Label1,Label2,CommandButton1
a = 1 : b = 2
那么我们可以这样表示,注意Object不可省略:
Sheet1.OleObjects("Label" & a).Object.Caption 表示Label1.Caption
Sheet1.OleObjects("Label" & b).Object.Caption 表示Label2.Caption
Sheet1.OleObjects("CommandButton" & a).Object.Caption 表示CommandButton1.Caption
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-10
Private Sub UserForm_Initialize()
Dim i As Byte
Sheet1.Range("C9").Select
For i = 1 To 4
Set 单选按钮集合(i).OButtonBillType = Controls("OptionButton" & i)
Next
Me.Left = Range("工具箱位置")(3)
Me.Top = Range("工具箱位置")(4)
End Sub

重点就是Controls("OptionButton" & i)
名字必须使用相同的前缀追问

是Excel里面插入的控件

追答

sheet1.Controls("OptionButton" & i)

第2个回答  2013-06-10
如果是userform里的控件 可用 me.controls("label"& x).caption="xxx" 来实现
me 可用userform1 代替
如果是activeX控件我就没辙了,
相似回答