【问题标题】:Is there a way to determine which optional arguments were given in a VBA function call?有没有办法确定在 VBA 函数调用中给出了哪些可选参数?
【发布时间】:2011-10-03 16:49:30
【问题描述】:

假设我有一个带有可选参数的 VBA 函数。有没有办法从该函数中判断调用代码是否提供了可选参数?

Public Function SomeFunction(optional argument as Integer = 0) As Integer

End Function

即有没有办法区分以下调用?

x = SomeFunction()
x = SomeFunction(0)

【问题讨论】:

    标签: function vba introspection optional-parameters


    【解决方案1】:

    据我所知,这是不可能的。如果未传递任何参数,则该参数被初始化为其默认值(在本例中为 0)。

    解决此问题的一种方法是将变量类型更改为Variant 并使用IsMissing 函数检查是否传递了参数。示例:

    Public Function SomeFunction(Optional argument As Variant) As Integer
        If IsMissing(argument) Then
            argument = 0
        Else
            // Code if argument not = 0....
        End If
    End Function
    

    IsMissing 函数仅适用于 Variant 数据类型,因为任何其他数据类型将始终具有默认初始化值。

    【讨论】:

      【解决方案2】:

      不,没有。

      同样的问题在其他语言中也存在,比如C#,在“C# In Depth”第 13.1.1 章中有清楚的表述(我在 15 分钟前读过这部分,这很正常,我记得这个!)

      我建议你不要在函数声明中设置默认值。在函数中,如果参数为 null,则将其设置为 0,并且您知道它没有在函数调用中提供。

      编辑:就像@Remnant 在他的回答中所说,为了能够做到这一点,参数类型需要是一个变体。

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 2020-10-06
        • 2012-08-06
        • 2012-04-17
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多