Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a VBA sub using a string value [duplicate]

Tags:

excel

vba

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?

like image 326
jacek_wi Avatar asked Jun 10 '15 10:06

jacek_wi


People also ask

How do you reference a sub in VBA?

To call a Sub procedure from another procedure, type the name of the procedure and include values for any required arguments. The Call statement is not required, but if you use it, you must enclose any arguments in parentheses. Use a Sub procedure to organize other procedures so they are easier to understand and debug.

Can a VBA function call a sub?

Functions can call subs or anything else. I have numerous functions that call subs which call other functions, etc. There may be a practical limit to "things calling things", but I have never encountered it. You can Call a Sub, but you still cannot modify the worksheet if the Function is called from a cell.

How do you call another module in VBA?

VBA Example: Run Another Macro from a Macro Just type the word Call then space, then type the name of the macro to be called (run).

How do I extract a SubString in Excel VBA?

Step 1: In the same module declare a sub-function to start writing the code for sub-function. Step 2: Declare two Variables A as string and B as String array and take input string from the user and store it in Variable A. Step 3: Use the Split SubString function and store its value in Variable B.


1 Answers

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

like image 189
tea_pea Avatar answered Oct 10 '22 23:10

tea_pea