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

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple

jungix

Board Regular
Joined
Jul 24, 2006
Messages
58
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
 

Scott Huish

MrExcel MVP
Joined
Mar 17, 2004
Messages
19,958
Office Version
  1. 365
  2. 2010
Platform
  1. Windows
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
 

gingerafro

Active Member
Joined
Mar 23, 2005
Messages
448
Oh I get it, a Cell is still a range even though it is only one cell.

Thank you both very much.
 

Watch MrExcel Video

Forum statistics

Threads
1,130,309
Messages
5,641,448
Members
417,209
Latest member
Agbarker

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
Top