缺少UDF中的ParamArray

时间:2018-06-03 06:51:02

标签: excel-vba user-defined-functions paramarray vba excel

我正在尝试确定何时在没有提供ParamArray参数的工作表上使用ParamArray的用户定义函数(UDF)。

我尝试过IsEmpty,IsArray,IsError,比较什么都没有,比较零长度字符串等等。

我知道paramarray总是byVal并且变量数组总是从零开始,但是如果它不存在,它是怎么一个数组的呢?

  • 将数组的第一个元素与Nothing或Not Nothing进行比较会引发错误
  • IsEmpty报告错误
  • IsArray奇怪地报告了真实
  • 两个测试和测试(0)
  • 的IsError报告为False

testParams UDF:

Public Function testParams(ByRef ndx As Long, ParamArray tests())
    Select Case ndx
        Case 1
            testParams = CBool(tests(LBound(tests)) Is Nothing)
        Case 2
            testParams = IsEmpty(tests)
        Case 3
            testParams = IsArray(tests)
        Case 4
            testParams = IsError(tests)
        Case 5
            testParams = CBool(tests(LBound(tests)) = vbNullString)
    End Select
End Function

在下面的示例中,我只是返回到工作表,尝试访问ParamArray返回的内容。

enter image description here

如何确定用户是否未在需要它们的真实UDF中提供ParamArray参数?我更喜欢简单的布尔检查和测试,以测试是否有什么东西。

2 个答案:

答案 0 :(得分:3)

TL; DR - 如果IsMissing(测试)则使用然后......

NTL&安培; WR:

即使ParamArray不能与任何声明的Optional参数(包括ParamArray本身)一起使用,如果省略它也不会引发错误。可以很容易地说,ParamArray 始终是可选的,尽管它不能被标记为。

  

发件人: Parameter Arrays (Visual Basic)
参数数组是自动可选的。它的默认值是参数数组元素类型的空一维数组。

用户未提供的ParamArray将是一个实例化的变量数组,但既没有填充也没有正尺寸。

定义时LBound为0(零),UBound为-1(减1)。这与声明但未标注尺寸的任何其他变体数组相同。

由于它是always a variant type parameter,因此它也会使用IsMissing正确报告其存在与否。

Public Function testParams(ByRef ndx As Long, ParamArray tests())
    Select Case ndx
        Case 1
            testParams = CBool(tests(LBound(tests)) Is Nothing)
        Case 2
            testParams = IsEmpty(tests)
        Case 3
            testParams = IsArray(tests)
        Case 4
            testParams = IsError(tests)
        Case 5
            testParams = CBool(tests(LBound(tests)) = vbNullString)
        Case 6
            testParams = CBool(UBound(tests) = -1)
        Case 7
            testParams = IsMissing(tests)
    End Select
End Function

测试IsMissing或UBound值为-1将确定用户是否提供了paramarray。

enter image description here

答案 1 :(得分:1)

阵列分配的一个很好的解释是http://www.cpearson.com/Excel/IsArrayAllocated.aspx

Excert:

  

下面的函数IsArrayAllocated将准确返回True或False,指示是否已分配数组。此函数适用于任意维度的静态和动态数组,并且可以正确地用于具有有效(非错误)LBound值的未分配数组

功能

Function IsArrayAllocated(Arr() As Variant) As Boolean
    On Error Resume Next
    IsArrayAllocated = IsArray(Arr) And _
        Not IsError(LBound(Arr, 1)) And _
        LBound(Arr, 1) <= UBound(Arr, 1)
End Function

将其与带有参数数组的Function一起使用

Function MyFunc(ParamArray pa()) As Variant
    Dim v()
    v = pa
    If IsArrayAllocated(v) Then
        'Do stuff with the parameters
    Else
        'There are no parameters...
    End If
End Function
相关问题