【问题标题】:Pass Sub as a parameter将 Sub 作为参数传递
【发布时间】:2020-10-30 01:17:28
【问题描述】:

我有一个子

Sub MySub1

MsgBox "I am ok!"

End Sub

然后我有一个带参数的所谓“方法子”

Sub MySub2 (Parameter1, Parameter2, MethodName)

MsgBox Parameter1
MsgBox Parameter2

MethodName

End Sub

然后我想在我的主人中运行整个链条。我尝试了以下方法:

Sub MasterSub

Dim Parameter1 As String
Dim Parameter2 As String
Dim MethodName As String

Parameter1 = "Ou"
Parameter2 = "Yes"
MethodName = MySub1

MySub2 Parameter1, Parameter2, MethodName

Dim 

这给出了预期值或函数的错误。如何使这项工作?

【问题讨论】:

  • 有什么理由想让它成为一个参数吗?您可以通过将字符串作为子例程(方法)的名称传递给它来完成类似的操作,然后使用Select CaseIf 根据字符串的值运行某个子例程...
  • @BigBen Application.Run "MethodName" 有效。我还没有尝试过第二个建议,但我也会检查一下
  • Sub 不返回值。 Function 确实如此。这就是为什么当您说MethodName = MySub1 时,它不会为MethodName 分配任何值。我怀疑这就是你收到错误的原因。如果您将其转换为函数,请忘记为函数分配返回值(即在MySub1 sub 结束之前,有类似:MySub1 = "This is a test"

标签: excel vba


【解决方案1】:

您需要创建Module(如下图所示):

然后粘贴这段代码:

    Private Sub MySub1()
        MsgBox "I am ok!"
    End Sub

    Private Sub MySub2(Parameter1, Parameter2, MethodName)
        MsgBox Parameter1
        MsgBox Parameter2

        Application.Run MethodName
    End Sub

    Sub MasterSub()
        Dim Parameter1 As String
        Dim Parameter2 As String
        Dim MethodName As String

        Parameter1 = "Ou"
        Parameter2 = "Yes"
        MethodName = "MySub1"

        MySub2 Parameter1, Parameter2, MethodName
    End Sub

然后点击Run Sub/User Form按钮(或点击F5键)运行你的宏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2020-09-18
    • 2015-05-24
    • 2012-11-10
    • 2014-02-25
    相关资源
    最近更新 更多