是否可以在VBA方法中使用varible?
例如,我正在尝试将项目添加到列表中:列表框 1 .AddItem(item1)
Qns:我能用一个变量替换“1”:Listbox& “Varible” .AddItem(item1)
Sub ThisWorks()
Worksheets("Control Sheet").Tx_TgtRaw_FX_CA.AddItem ("Remark1")
End Sub
=======================
Sub test()
'Trying to use this as a varible instead
X = "Tx_TgtRaw_FX_CA"
Worksheets("Control Sheet").X.AddItem ("Remark1")
'Error 438: Object does not support this property or method
End Sub
=======================
Sub testarr()
Dim y(0 To 2)
Set y(0) = "Tx_TgtRaw_FX_CA"
Worksheets("Control Sheet").y(0).AddItem ("Remark1")
'Error 438: Object does not support this property or method
End Sub
答案 0 :(得分:1)
我不认为在VBA中使用INDIRECT
变量名的任何方式都是可能的。
一种解决方法是定义数组并引用它们的项目,例如:
Dim ListBoxes(10) as Variable
Set ListBoxes(1) = ListBox1
Set ListBoxes(2) = ListBox2
(instead of preparing the array manually you can
also add the items programmatically to the form)
...
ListBoxes(i).AddItem(item1)
答案 1 :(得分:0)
您需要在适当的容器中循环控件,以检查其名称是否等于您需要的控件名称。即。
For Each c in Controls
If LCase(c.Name) = LCase("NameOfDesiredControl") Then
... Work with it ...
End If
Next
这很容易转化为一种功能。
答案 2 :(得分:0)
我不确定您的目标是什么,但对您发布的代码进行以下修改可以让它发挥作用:
Option Explicit
Sub ThisWorks()
Worksheets("Control Sheet").Tx_TgtRaw_FX_CA.AddItem ("Remark1")
End Sub
'=======================
Sub test()
Dim X As Object
'Trying to use this as a varible instead
Set X = Worksheets("Control Sheet").Tx_TgtRaw_FX_CA
X.AddItem ("Remark1")
End Sub
'=======================
Sub testarr()
Dim y(0 To 2)
Set y(0) = Worksheets("Control Sheet").Tx_TgtRaw_FX_CA
y(0).AddItem ("Remarkx")
End Sub