在过去30分钟内,我尝试在VBA中执行一个字符串作为命令。命令是这样的,它运行正常:
activesheet.chb_g_ba1.visible = true
我要做的是将“chb_g_ba1”设置为变量,因为还有“chb_g_ba2”,“chb_g_ba3”等。
到目前为止我尝试了什么 - 比如:
dim l_counter as long: l_counter = 1
Evaluate (CStr("me.chb_g_ba" & l_counter & ".visible = true"))
甚至是Eval
Eval (CStr("me.chb_g_ba" & l_counter & ".visible = true"))
Eval是MS Access VBA中的一项功能,但显然它不存在于Excel中。几乎我的问题与这个问题非常类似:VBA how to run a string as a line of code,但它适用于Excel,而不适用于Access。
所以,欢迎任何想法! :)
答案 0 :(得分:1)
归功于CPearson:
有一种方法可以做到这一点,但我们必须动态添加一个新模块和所需的代码,并在完成时删除。
参考:Microsoft Visual Basic for Applications可扩展性5.3
Sub test()
Set VBComp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)
VBComp.Name = "NewModule"
Set VBCodeMod = ThisWorkbook.VBProject.VBComponents("NewModule").CodeModule
Dim l_counter As Long
l_counter = 1
With VBCodeMod
LineNum = .CountOfLines + 1
.InsertLines LineNum, _
"Sub MyNewProcedure()" & Chr(13) & "UserForm1.chb_g_ba" & l_counter & ".Visible = True" & Chr(13) & "End Sub"
End With
'run the new module
Application.Run "MyNewProcedure"
UserForm1.Show
'Delete the created module
ThisWorkbook.VBProject.VBComponents.Remove VBComp
End Sub