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
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.
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With