2016-08-05 591 views
1

我有一個函數,它檢查數組是否爲空。由於今天我得到一個運行時錯誤9.我不知道爲什麼。如何檢查VBA中的數組是否爲空?

下面是代碼:

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 

如何檢查,如果數組是空的?

+2

http://stackoverflow.com/questions/206324/how-to-check-for-empty-array-in-vba-macro –

+0

可能d重複的[如何檢查空數組在vba宏](http://stackoverflow.com/questions/206324/how-to-check-for-empty-array-in-vba-macro) – LWC

回答

0

好,我還沒有發現這樣的一個更好的解決辦法:

With rs 
    If Not .EOF Then 
     arrItems = .GetRows 
    Else 
     arrItems = Array() 
    End If 
    .Close 
End With 

ArrEmpty = IsArrayEmpty(arrItems) 
1

首先檢查與IsArray的(arrItems) 然後檢查UBOUND

+1

我已經檢查現在'isArray(parArray)',它返回給我'true',但ubound不起作用。 – yuro

+0

也許陣列是二維的 – Kelaref

1

。那些總是在芯片皮爾遜的網站功能工作對我來說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