用字符串调用子 [英] Call a Sub with a String

查看:84
本文介绍了用字符串调用子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据i的值调用其他子项.

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

例如,如果i = 1调用sale_call1,而i = 2调用sale_call2.

For example, if i = 1 call sale_call1 and if i = 2 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

推荐答案

尝试一下

Application.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

关注

如果您的代码不在模块中,而是在用户窗体或工作表代码区域中,则在未将sale_call1sale_call2放置在模块中之前,Application.Run将不起作用.如果您不希望将它们移至模块,则必须使用CallByName.检查Excel在此功能上的内置帮助.这是一个假定代码在Userform1

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

这篇关于用字符串调用子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆