Call a Sub with a String Call a Sub with a String vba vba

Call a Sub with a String


Try this

Replace Call pro with Application.Run pro

Example

Private Sub test_Click()    Dim i As String    Dim pro As String    i = 1    pro = "sale_call" + i    '~~> This will run sale_call1    Application.Run pro    i = 2    pro = "sale_call" + i    '~~> This will run sale_call2    Application.Run proEnd SubSub sale_call1()    MsgBox "Hello"End SubSub sale_call2()    MsgBox "goodbye"End Sub

FOLLOWUP

If your code is not in a module but in a Userform or Sheet Code area then Application.Run will not work till the time sale_call1 or sale_call2 is not placed in a module. If you do not wish to move them to a module then you will have to use CallByName. Check Excel's inbuilt help on this function. Here is an example which assumes that the code is in Userform1

Private Sub CommandButton1_Click()    Dim i As String    Dim pro As String    i = 1    pro = "sale_call" + i    '~~> This will run sale_call1    CallByName UserForm1, pro, VbMethod    i = 2    pro = "sale_call" + i    '~~> This will run sale_call2    CallByName UserForm1, pro, VbMethodEnd SubSub sale_call1()    MsgBox "Hello"End SubSub sale_call2()    MsgBox "goodbye"End Sub


Just add as prefix the workbook name where the macro is hosted.Like when doing a formula in a cell:

Application.Run "WorkbookNameAsString.app_ext!MacroName"


VBA uses '&' for concatenation;

Incorrect:

pro = "sale_call" + i

Corrected:

pro = "sale_call" & i

I hope it helps.