14

我想根据i.

例如,如果i = 1调用sale_call1和如果i = 2调用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
4

3 回答 3

25

尝试这个

替换Call proApplication.Run pro

例子

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

跟进

如果您的代码不在模块中,而是在用户表单或工作表代码区域中,那么Application.Run直到那时才会起作用,sale_call1或者sale_call2没有放在模块中。如果您不想将它们移动到模块中,则必须使用CallByName. 查看 Excel 对此功能的内置帮助。这是一个假设代码在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
于 2013-04-12T11:12:34.523 回答
2

只需将托管宏的工作簿名称添加为前缀即可。就像在单元格中做公式一样:

Application.Run "WorkbookNameAsString.app_ext!MacroName"
于 2013-09-26T15:23:22.190 回答
-1

VBA 使用 '&' 进行连接;

不正确:

pro = "sale_call" + i

更正:

pro = "sale_call" & i

我希望它有所帮助。

于 2019-09-16T10:41:27.953 回答