Home » excel » excel – Call a VBA sub using a string value

excel – Call a VBA sub using a string value

Posted by: admin March 9, 2020 Leave a comment

Questions:

This is my test code

Sub dotask()

    Dim qusub As String
    qusub = Worksheets("Task List").Range("C2").Value

    MsgBox qusub
    Application.Run qusub

End Sub

Sub msg1()

    MsgBox "sub msg1"

End Sub

Sub msg2()

    MsgBox "sub msg2"

End Sub

Sub msg3()

    MsgBox "sub msg3"

End Sub

Sub msg4()

    MsgBox "sub msg4"

End Sub

All of this is contained in a single standard module. I’ve read Trying to call a Sub with a String – VBA and wrote my code according to what I found there (i.e. using Application.Run). Cell C2 of Task List worksheet contains “msg3” at the moment. When I execute sub “dotask” I first get a message box saying “msg3” as I want but then I get the following error message:

Run-time error ‘1004’:

Cannot run the macro ‘msg3’. The macro may not be available in this workbook or all macros may be disabled.

I’m working on Excel 2010 and the file is .xlsm – what should I do to get my code to execute as I want it?

How to&Answers:

just ran it over here. msg1 seems to be a reserved word… change it to something else and it works fine =)

Answer:

Using GetRef, you give the reference to the sub.
See my question here for example

EDIT: following the suggestions in the comments, here part of the solution to this question.

sub one(para)
  WScript.Echo para & " from one"
end sub

sub two(para)
  WScript.Echo para & " from two"
end sub

sub main(subname, para)
  Dim f : Set f = GetRef(subname)
  f para
end sub

main "one", "test" '=>test from one