是否需要在调用函数中重复名称?

Is it necessary to repeat name in Calling Function?

示例:

“qlBlackConstantVol”"blackConstantVol":

blackVolId = Application.Run("qlBlackConstantVol", _

"blackConstantVol", 35932, "Target", 0.2, "Actual/365 (Fixed)")

如果是这样,为什么他们在每个函数中都重复这个名称,除了这个:

blackScholesId = Application.Run( _

"qlGeneralizedBlackScholesProcess", "blackScholes", _

blackVolId, 36, "Actual/365 (Fixed)", 35932, 0.06, 0)

不,通过 Application.Run 调用时不需要重复函数或子名称,这不是您所看到的。 qlBlackConstantVolblackConstantVol 不同名(注意 ql)。在上下文中,"blackConstantVol" 只是一个传递给 qlBlackConstantVol 的字符串参数。该字符串与函数名称相似这一事实无关紧要,并且不反映对 Application.Run.

使用的任何限制

有必要像您目前所做的那样传递参数,但我认为您误解了代码,因为您没有传递两次名称,您只传递了一次名称。

blackVolId = Application.Run("qlBlackConstantVol", _
    "blackConstantVol", 35932, "Target", 0.2, "Actual/365 (Fixed)")

但是,Application.Run 没有任何内容需要传递名称两次(如果仔细观察,您会发现实际上您不是在做,您传递的是名称, 以及其他一些任意但相似的 String):

在上面的上下文中,"qlBlackConstantVol" 是 运行 的过程,而 "blackConstantVol" 只是一个字符串参数,它是函数 qlBlackConstantVol 的输入。

没有看到函数体,就不可能说出 "blackConstantVol" 是干什么用的,是否是 "arbitrary" 所以没有更多细节,我会说你不应该改变它,除非你知道什么你在做什么,为什么。

Is it Correct that the name of the function is irrelevant, and doesn't reflect any constraint on the use of Application.Run ?

名称本身对后续的 args 列表施加了约束,因此虽然名称本身不是约束(即,您可以传递任何函数名称,只要它是 valid/accessible 函数),它确实施加了约束( args 列表必须对该函数有效)。令人困惑?

让我们解压缩 Application.Run:

Application.Run 具有以下签名:

expression . Run( Macro , Arg1 , Arg2 , Arg3 , Arg4 , Arg5 , Arg6 , Arg7 , Arg8 , Arg9 , Arg10 , Arg11 , Arg12 , Arg13 , Arg14 , Arg15 , Arg16 , Arg17 , Arg18 , Arg19 , Arg20 , Arg21 , Arg22 , Arg23 , Arg24 , Arg25 , Arg26 , Arg27 , Arg28 , Arg29 , Arg30 )

第一个参数 Macro 是可选的 (!),表示:

The macro to run. This can be either a string with the macro name, a Range object indicating where the function is, or a register ID for a registered DLL (XLL) function. If a string is used, the string will be evaluated in the context of the active sheet.

剩余参数各代表:

An argument that should be passed to the function.

Application.Run 是如何工作的?

假设您有 2 个带有所需参数的子例程,例如:

Sub foo(i As Long, b As Boolean, s As String)
Static counter As Long
counter = counter + i
    If b Then MsgBox ("Count: " & counter & ". " & s)
End Sub

Sub bar(i As Long)
    MsgBox i
End Sub

为了从 Application.Run 调用 foo 这个,你需要这样传递它:

Application.Run("foo", _some_long_integer_value, _a_boolean_value, _a_string_value)

如果您传递了错误的参数类型或数量会怎样?

如果你没有传递足够的参数,你会得到一个错误:

Application.Run("foo", 90210)

如果传递太多参数(bar 只接受一个参数),你会得到一个错误:

Application.Run("bar", 6, True, "hello")

如果你传递错误类型的参数,你会得到一个错误:

Application.Run("bar", "Blue")

如果您向它传递无法评估的不可能的参数(例如无效的 Range 规范),您将收到 1004 错误:

Application.Run("foo", True, Range("A1:A-10"))

使用此方法时可能会遇到更多错误,上面的内容很容易说明,但我并不认为它们是详尽无遗的列表。

当然,您可以通过这种方式调用大多数 function/sub(有一些注意事项:它必须在范围内,args 列表取决于要成为 Run 的函数,等等),所以从这个意义上说,只要后续参数与函数签名匹配,你为 Macro 传递的内容并不严格。