Search code examples
vbaloopsreferencecellcounter

VBA in Excel - use loop counter to reference cells


I have cells that are either "True" or "False". I have names for these cells so that it's easier for me to reference in my codes. For Example, instead of saying cell "A1" I say cell "Apples". The cell names are:
Apples
Oranges
Onions
Potatoes
Bananas

In a separate worksheet I have under column A:
Apples
Oranges
Bananas
This range of cells is named "Fruit". So this list is meant to be a list of the cell names I want to check.

I want to use a for loop to check if each cell referenced under in the range "Fruit" is true. This is my code:

For Each item In [Fruit]
    If Worksheets("Inventory").Range(item).Value = True Then
        --Do stuff--
    End If
Next item

I keep getting an error when trying to reference the cell. How can I do this? Is it possible for me to use the counter to reference the cell?


Solution

  • close...

    For Each item In [Fruit]
        If Worksheets("Inventory").Range(item.Value) = True Then
            '--Do stuff--
        End If
    Next item