我有一个函数,该函数检查数组是否为空。从今天开始,我遇到运行时错误9。我不知道为什么。

这是代码:

When db table contains data, pass it to the variable => arrItems
arrItems as Variant
ArrEmpty as Boolean

With rs
  If Not .EOF Then
      arrItems = .GetRows
      .Close
  End If
End With

ArrEmpty = IsArrayEmpty(arrItems)

Private Function IsArrayEmpty(parArray As Variant) As Boolean
    IsArrayEmpty = IIf(UBound(parArray) > 0, False, True) //Here is invoked the runtime error 9
End Function


如何检查数组是否为空?

最佳答案

Chip Pearson网站上有一个对我一直有效的功能link

Public Function IsArrayEmpty(Arr As Variant) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsArrayEmpty
' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.
'
' The VBA IsArray function indicates whether a variable is an array, but it does not
' distinguish between allocated and unallocated arrays. It will return TRUE for both
' allocated and unallocated arrays. This function tests whether the array has actually
' been allocated.
'
' This function is really the reverse of IsArrayAllocated.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim LB As Long
Dim UB As Long

Err.Clear
On Error Resume Next
If IsArray(Arr) = False Then
    ' we weren't passed an array, return True
    IsArrayEmpty = True
End If

' Attempt to get the UBound of the array. If the array is
' unallocated, an error will occur.
UB = UBound(Arr, 1)
If (Err.Number <> 0) Then
    IsArrayEmpty = True
Else
    ''''''''''''''''''''''''''''''''''''''''''
    ' On rare occassion, under circumstances I
    ' cannot reliably replictate, Err.Number
    ' will be 0 for an unallocated, empty array.
    ' On these occassions, LBound is 0 and
    ' UBoung is -1.
    ' To accomodate the weird behavior, test to
    ' see if LB > UB. If so, the array is not
    ' allocated.
    ''''''''''''''''''''''''''''''''''''''''''
    Err.Clear
    LB = LBound(Arr)
    If LB > UB Then
        IsArrayEmpty = True
    Else
        IsArrayEmpty = False
    End If
End If

End Function

关于arrays - 如何检查VBA中的数组是否为空?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38784430/

10-11 05:48