For Each...

gingerafro

Active Member
Joined
Mar 23, 2005
Messages
448
Hi.
I'm trying to put some bones on my 'layman's VBA'. I would like to know how to use a For Each statement with cells, and if the fit the criteria, do something with them. What I do isn't actually important, its the method I'm interested in. My badly written VBA would be:

sub selectcells()

dim c as Cells (I know the 'Cells' bit doesn't exist)

with worksheets("Sheet1")
For Each c in .Range("A1:A10")
IF c.value = 5 then
c.select
End IF
Next
End With

End Sub
 

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!
Dim c As Range and it should work, probably even without a declaration.

I usually just use:

For each cell in Range("A1:A10")

....

Next

It works well but that may be because I use the word cell itself. Just try
 
Upvote 0
It's always best to define the variable for what it is though and no, it's not because you used the word cell, an undefined variable will default to type Variant

Code:
Sub selectcells()
Dim c As Range
Worksheets("Sheet1").Activate
For Each c In Range("A1:A10")
    If c = 5 Then c.Select
Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,218,499
Messages
6,142,829
Members
450,449
Latest member
Dave Carr QM

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top