Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether value is iterable vba

Tags:

excel

vba

In many languages it is possible to check whether an object is iterable, how do I do this for VBA?

I can try:

Function isIterable(obj As Variant) As Boolean
    On Error Resume Next
    Dim iterator As Variant
    For Each iterator In obj
        Exit For
    Next
    isIterable = Err.Number = 0
End Function

But I wonder if there's a builtin or a better approach?

like image 651
Greedo Avatar asked Dec 01 '17 16:12

Greedo


2 Answers

Is there a built-in function: No.

Is there a better approach?:

I would have done it like this:

Function isIterable(obj As Variant) As Boolean

    On Error GoTo isIterable_Error

    Dim iterator As Variant

    For Each iterator In obj
        isIterable = True
        Exit Function
    Next

isIterable_Error:

End Function

Because putting twice = on the same line is a bit too much.

like image 54
Vityata Avatar answered Nov 15 '22 06:11

Vityata


I don't think it's any better than Vityata's function, but just as an alternative:

Function isIterable(obj As Object) As Boolean

    On Error Resume Next

    isIterable = TypeName(CallByName(obj, "_NewEnum", VbGet)) = "Unknown"
    If Not isIterable Then isIterable = TypeName(CallByName(obj, "_NewEnum", VbMethod)) = "Unknown"

End Function
like image 30
Rory Avatar answered Nov 15 '22 08:11

Rory