Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Error 9 when there is an Empty Array

I am writing a script that will loop through an Excel spreadsheet and find if there are duplicates of selected cells. If there are duplicates then the function will return an array of which rows are duplicates and create a comment to tell me the rows.

I have been able to handle error 0 but now I am getting error 9 when I check if there are elements in the array using the UBound function.

How do I validate if the array of integers is empty?

Function IsArrayEmpty(anArray As Variant) As Boolean
    Dim i As Integer

    On Error Resume Next
        i = UBound(anArray, 1)
    Select Case (Err.Number)
        Case 0
            IsArrayEmpty = True
        Case 9
            IsArrayEmpty = True
        Case Else
            IsArrayEmpty = False
    End Select
End Function
like image 303
Talguy Avatar asked Nov 04 '10 13:11

Talguy


People also ask

What is the UBound of an empty array VBA?

If the array is empty, the Ubound function triggers an error; in turn, that will cause the script to come to a screeching halt. That is, it will come to a screeching halt unless we've implemented On Error Resume Next.

What does empty array mean in Excel?

Empty array errors occur when an array formula returns an empty set. For example, =FILTER(C3:D5,D3:D5<100) will return an error because there are no values less than 100 in our data set. To resolve the error, either change the criterion, or add the if_empty argument to the FILTER function.

How do I ReDim an array in VBA?

Examples to use VBA Redim StatementStep 1: Create a macro name first. Step 2: Declare an array name as a string. Step 3: Now, use “Redim” and assign the array size. Step 4: The array name “MyArray” can hold up to 3 values here.


2 Answers

Try this to check an empty array:

Dim arr() As String

If (Not arr) = -1 Then
   Debug.Print "empty"
Else
   Debug.Print "UBound is " & UBound(X)
End If  

HTH!

like image 194
Dr. belisarius Avatar answered Sep 24 '22 00:09

Dr. belisarius


Your function is failing because if there is no error raised by UBound() (i.e. the array is dimensioned) then Err.Number is 0 and:

Case 0
  IsArrayEmpty = True

is executed returning an incorrect result.

The simplest way is to just trap the error:

Function IsArrayEmpty(anArray As Variant) As Boolean
On Error GoTo IS_EMPTY
If (UBound(anArray) >= 0) Then Exit Function
IS_EMPTY:
    IsArrayEmpty = True
End Function
like image 41
Alex K. Avatar answered Sep 24 '22 00:09

Alex K.