Trying to call a Sub with a String - VBA

妖精的绣舞 提交于 2019-11-26 04:56:05

问题


I have the following code.

I cannot for the life of me figure it out.

I want to call a different sub depending on the value of i.

For example, if i = 1 it should call sale_call1 and if i = 2 it should call sale_call2.

Private Sub test_Click()
    Dim i As String
    Dim pro As String

    i = Me.tb1.Value
    pro = \"sale_call\" + i

    If i = \"1\" Then
        Call pro
    Else
        Call pro
    End If
End Sub

Sub sale_call1()
    MsgBox \"Hello\"
End Sub

Sub sale_call2()
    MsgBox \"goodbye\"
End Sub

回答1:


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 pro
End Sub

Sub sale_call1()
    MsgBox "Hello"
End Sub

Sub 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, VbMethod
End Sub

Sub sale_call1()
    MsgBox "Hello"
End Sub

Sub sale_call2()
    MsgBox "goodbye"
End Sub



回答2:


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"



回答3:


VBA uses '&' for concatenation;

Incorrect:

pro = "sale_call" + i

Corrected:

pro = "sale_call" & i

I hope it helps.



来源:https://stackoverflow.com/questions/15969796/trying-to-call-a-sub-with-a-string-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!