[英]Is it possible to pass a function or sub as an argument in Excel VBA?
I want to pass a function/sub name as an argument so that I can call it within another function/sub in Excel VBA. 我想将函数/子名称作为参数传递,以便可以在Excel VBA中的另一个函数/子中调用它。 Is this possible?
这可能吗? If so, what is the type I set it as?
如果是这样,我将其设置为哪种类型? I tried setting as Variant but that didn't work.
我尝试将其设置为“变体”,但没有用。 I'm not sure what else to try.
我不确定还有什么尝试。
Here is a basic outline of the code I'm working on. 这是我正在处理的代码的基本概述。 Including my failed attempt at using Variant.
包括我使用Variant的失败尝试。
As you can see I'm trying to have waitingBBG check a different range each time and then call a different sub each time. 如您所见,我正在尝试让BBG每次检查一个不同的范围,然后每次调用一个不同的子程序。 That's why I want to be able to specify which sub to call after waitingBBG is done.
这就是为什么我希望能够指定在等待BBG完成后要调用哪个子程序。
Update: I updated the code with Application.Run instead of Call 更新:我使用Application.Run而不是Call更新了代码
Sub part_1
Dim calculation_rng as String
calculation_rng = "A1"
Call waitingBBG(calculation_rng, "part_2")
End Sub
Sub waitingBBG(calculation_rng As String, call_id As Variant)
If Application.WorksheetFunction.CountIfs(Range(calculation_rng), "#N/A Requesting Data...") > 0 Then
'Check every 1 second
Application.OnTime Now + TimeValue("00:00:01"), "waitingBBG"
Else
'Call rest of code
Application.Run "'my_addin.xlam'!" & call_id
End If
End Sub
Sub part_2
Dim calculation_rng as String
calculation_rng = "B1"
Call waitingBBG(calculation_rng, "part_3")
End Sub
Sub part_3
Msgbox("Success")
End Sub
@MathieuGuindon provided the correct solution. @MathieuGuindon提供了正确的解决方案。 Thank you!
谢谢!
Basically, I needed to pass the function name as a string and use Application.Run
instead of Call
基本上,我需要将函数名称作为字符串传递,并使用
Application.Run
代替Call
Also, 也,
Application.OnTime Now + TimeValue("00:00:01"), "waitingBBG"
needed to be changed to 需要更改为
Application.OnTime Now + TimeValue("00:00:01"), "'waitingBBG """ & calculation_rng & """,""" & call_id & "'"
to reflect the changes. 反映变化。
Sub sub1()
Dim a As String
a = "hii"
sub2 (a)
End Sub
Sub sub2(val As String)
If val = "hi" Then
MsgBox (val)
Else
MsgBox ("sub2 else")
sub3 (val)
End If
End Sub
Sub sub3(val1 As String)
MsgBox (val1)
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.