Search code examples
excelvbavariablescommandeval

How to run a string as a command in VBA


I have this simple VBA code below, and I don't know why is not working.

Sub Run()
    test = "MsgBox" & """" & "Job Done!" & """"
    Application.Run test     
End Sub

What I want to do is to put the VBA Command into a variable as text and run it as a command. In this case, I want to run like MsgBox "Job Done!" and print just:

Job Done!


Solution

  • You may be tempted by adding your own string "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