Table of Contents

RDC11035: Collection set to Nothing inside its own For Each loop

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

A Set statement inside a For Each loop sets the variable the loop walks to Nothing.

While the loop runs, RD-VBA leaves the variable as it is. The loop holds the object it walks, and its own iteration does not destroy it: the loop reaches every member, and the variable still refers to the collection after the loop. MS-VBA lets go of a Collection there. The collection is destroyed, with the members the loop has not reached yet, and the loop ends. MS-VBAL §5.4.2.4 leaves the enumeration of a collection implementation-defined.

Dim items As Collection, item As Variant
Set items = MakeItems()
For Each item In items
    Set items = Nothing      ' RD-VBA: items is left as it is
    Debug.Print item.Name
Next
Debug.Print items Is Nothing ' False in RD-VBA

The warning is raised for a Set to Nothing of the variable named after In, anywhere in the body of the loop, including a block inside it.

How it is raised

Situation Example What to do
The collection is set to Nothing to end the loop. Set items = Nothing inside For Each item In items Leave the loop with Exit For, then set the variable to Nothing.
The collection is set to Nothing to free it early. If done Then Set items = Nothing inside the loop Set it to Nothing after Next.

See also


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