r/vba • u/First-Feature-3556 • 17h ago
Discussion Why does `For Each ... In myArray` require a Variant as the iterator variable?
5
Upvotes
Dim myarray(5) As Integer
Dim myint As Integer
For Each myint In myarray ' <-- compile error here
...
Next
I mean, the obvious answer is: Because the spec (Section 5.4.2.4) say so.
So, the question is: Why does the spec require this? When iterating over a collection of objects, I can use Object or the concrete type as the iterator variable. It would seem natural to use a variable of type Integer to iterate over an array of integers.
Completely unrelated fun fact: I've been using VBA for more than 30 years now, and only now (while reading the spec) I discovered that the following code is legal. Not that I would ever do this...
Dim row, col
For row = 0 To 5
For col = 0 To 5
Debug.Print row, col
Next col, row