Table of Contents

RDC11032: For Each variable read after the loop ran out

Severity: Warning  ·  Family: RDC (Rubberduck Core analyzers)  ·  Raised by: ForEachControlEmptiedAnalyzer

The control variable of a For Each loop is read after the loop, where the only way to get there is through the end of the loop.

When a For Each loop runs out of elements, VBA empties its control variable: a Variant is Empty, and an object variable is Nothing. The same goes for a loop over a collection or an array that has no element at all. A loop left by Exit For, GoTo or an error keeps the element it was at. MS-VBAL §5.4.2.4 says the variable holds the last element. Microsoft Office VBA empties it, and so does RD-VBA.

For example, with src a Collection of objects:

Dim item As Object
For Each item In src
    Debug.Print item.Name
Next
Debug.Print item.Name   ' item is Nothing here: run-time error 91

The warning is raised only where every way to the read goes through the end of the loop, with nothing assigned to the variable in between. A read that an Exit For can also reach is not reported: the usual search, which leaves the loop when it finds the element and then tests the variable, works as written. Only a local variable declared with Dim is followed. A Static variable, a parameter and a variable of the module are not, nor is a procedure that uses On Error Resume Next.

How it is raised

Situation Example What to do
The last element is used after the loop. For Each c In cells ... Next, then Debug.Print c.Address Keep the element in a variable of its own inside the loop: Set last = c.
The variable is tested after a loop that has no Exit For. If item Is Nothing Then, always True Test what the loop found, with a variable it sets when it finds it.
A Variant is read after a loop over an array. For Each v In Array(1, 2) ... Next, then Debug.Print v Same: assign the value to another variable inside the loop.

See also


ACCUEIL • HOME | ℹ️ BIENVENUE • WELCOME | 🧩 BÂTISSONS • BUILD | RD-VBAL | SDK | 🌐 rubberduckvba.ca