是否可以在VBA方法中使用变量?
例如,我试图将项目添加到列表中: Listbox1.AddItem (item1)
Qns:我能用varible: Listbox & "Varible".AddItem (item1)替换"1“吗?
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
发布于 2015-09-07 00:32:33
我认为在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)
发布于 2015-09-07 00:43:16
您需要在适当的容器中循环控件,以检查其名称是否等于所需的控件名称。也就是说。
For Each c in Controls
If LCase(c.Name) = LCase("NameOfDesiredControl") Then
... Work with it ...
End If
Next
这可以很容易地转换成一个函数。
发布于 2015-09-07 03:30:42
我不清楚您的目标是什么,但是对您发布的代码的以下修改使其能够工作:
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
https://stackoverflow.com/questions/32434006
复制相似问题