Search code examples
vbaloops

0 length Iterable compatible with For Each loop in VBA


For me it looks truely unbelievable that in the VBA for Excel there is a For Each loop but I simply cannot create any kind of data that the loop iterates through 0 times (so the core of the loop is never executed).

Function GetChildren() As Variant()
  Dim children()
  GetChildren = children
End Function

For Each something In GetChildren()
  ' Do something
Next something

Is there anything that is

  • compatible with the For Each structure
  • there is no need to check (for errors, emptiness etc.) The client side should be simple
  • in exchange in the GetChildren I can put anything to fulfill

So I guess I'm looking for a data structure to return that I can loop through 0 times.

Thanks in advance


Solution

  • With the use of the Collection object there is 0 iteration.

    Function GetChildren() As Object
    
      Set childrens = New Collection
      Set GetChildren = childrens
      
    End Function
    
    Sub caller()
    
    For Each something In GetChildren
      Debug.Print TypeName(something)
    Next something
    
    End Sub