如何在VBA中将字符串作为命令运行

ECo*_*ode 7 variables excel vba command eval

我在下面有这个简单的VBA代码,我不知道为什么不工作.

Sub Run()
    test = "MsgBox" & """" & "Job Done!" & """"
    Application.Run test     
End Sub
Run Code Online (Sandbox Code Playgroud)

我想要做的是将VBA命令作为文本放入变量并将其作为命令运行.在这种情况下,我想运行MsgBox "Job Done!"和打印只是:

任务完成!

A.S*_*S.H 7

您可能会喜欢添加自己的字符串“ Executer”:

Sub StringExecute(s As String)
    Dim vbComp As Object
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & s & vbCrLf & "End Sub"
    Application.Run vbComp.name & ".foo"
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub
Run Code Online (Sandbox Code Playgroud)