检查值是否可迭代vba

时间:2017-12-01 16:05:08

标签: vba excel-vba excel

在许多语言中,可以检查对象是否可迭代,如何为VBA执行此操作?

我可以尝试:

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

但我想知道是否有内置或更好的方法?

2 个答案:

答案 0 :(得分:4)

是否有内置功能

有更好的方法吗?

我会这样做的:

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

因为在同一行上放置两次=有点太多了。

答案 1 :(得分:2)

我认为它不比Vityata的功能更好,但作为替代方案:

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