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?
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.
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
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