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!
You may be tempted by adding your own string "Executer":
Short answer is, you cannot do that (You should not do that) but ... read the following to find out why and see a work around!
As you know you are writing your code in a compiler. What you want to do is running human-legible line of text as a command which is not possible. While you run the program all of it is compiled to machine language. When you pass that line of text to it, it cannot recognize it as a command and you will end up getting an error. What you can do is passing arguments to it:
You can also run an executable which can be written as a text file within a
macro
and then runs within the sameSub
(extension needs to be taken care of).If you cannot change the variable (i.e.
test
) then you need to take another approach towards it. I would suggest something like extracting the argument which can be passed to the function and use that. Something like below;I believe there was a same question on SO but I couldn't find it. I will included it as a reference if found it.
P.S. These two posts may help to find an answer:
Access VBA - Evaluate function with string arguments
Excel VBA - How to run a string as a line of code
ANOTHER SOLUTION
This needs to trust the VB project. Quoting from ExcelForum and referencing to Programmatic Access To Visual Basic Project Is Not Trusted - Excel
Place your Macro-Enabled Workbook in a folder which you can designate as macro friendly.
Then open the workbook.
Click on the Office Button -> Excel Options -> Trust Center -> Trust Center Setting -> Trusted Locations.
Then you add your folder (where you have your Excel Macro-Enabled Workbook) as a trusted location.
Also you need to do this:
File -> Options -> Trust Center -> Trust Center Setting -> Macro Setting -> Check the box beside "Trust access to the VBA project object model"
Close and re-open your workbook.
Those who use your macro should go through the same steps.
Then you can use this which I got from VBA - Execute string as command in Excel (This is not tested)
@A.S.H answer does the thing that last solution intends to implement. I am including it here for the sake of completeness. You can refer to the original answer and up-vote it.