问题
In the last 30 minutes I am trying to execute a string in VBA as a command. The command is like this and it runs ok:
activesheet.chb_g_ba1.visible = true
What I am trying to do is to set "chb_g_ba1" as a variable, because there are "chb_g_ba2", "chb_g_ba3", etc as well.
What I have tried so far - things like:
dim l_counter as long: l_counter = 1
Evaluate (CStr("me.chb_g_ba" & l_counter & ".visible = true"))
Or even Eval
Eval (CStr("me.chb_g_ba" & l_counter & ".visible = true"))
Eval is a function in MS Access VBA, but obviously it is not present in Excel. Pretty much my question is extremely similar to this one:VBA how to run a string as a line of code, but it is for Excel, not for Access.
So, any ideas are welcomed! :)
回答1:
Credit to CPearson:
There is a way to do that but we have to add a new module dynamically with required code and delete while finished.
References: Microsoft Visual Basic for Applications Extensibility 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
来源:https://stackoverflow.com/questions/36595499/vba-execute-string-as-command-in-excel