for each c

Cascade

New Member
Joined
Aug 1, 2010
Messages
9
I've noticed you can use the letter 'c' to refer to every single cell within a looping range:

Sub ApplyColor()
Const Limit As Integer = 25
For Each c In Range("MyRange")
If c.Value > Limit Then
c.Interior.ColorIndex = 27
End If
Next c
End Sub



so i just like to clarify what;
"For Each c" ... actually means in VBA

haven't been able to find it anywhere.

can you use the letter c for non looping procedures?
like

for each c in range("a1:a10")
c.value = 1


thanks alot
chrs.
 

Excel Facts

Whats the difference between CONCAT and CONCATENATE?
The newer CONCAT function can reference a range of cells. =CONCATENATE(A1,A2,A3,A4,A5) becomes =CONCAT(A1:A5)
c is just a variable. It could be any valid variable name. In that example, c should be dimmed as Range. It's a For Each Loop. This is in the help file.
 
Upvote 0
Don't be so literal. You can decide what your variables are going to be. I'm not a huge fan of using single-letter variables, but it does make some smart-looking code.

I also like to intentionally declare my variables at the top of my macros, indicating the variable name I want to use and what type it is.

If I have a large range of cells and want to process them one cell at a time, those are range variables.

Code:
Sub Test()
Dim cel as Range
Dim Limit as Long

Limit = Range("C2").Value

For Each cel in Range("MyRange")
    If cel.Value > Limit Then cel.Interior.ColorIndex = 27
Next cel

End Sub


I know this is just an example code, but I would be remiss if I didn't point out that you don't need VBA to color cells that pass a certain known value, you can do that directly on the worksheet in the MyRange cells using Conditional Formatting.
 
Upvote 0

Forum statistics

Threads
1,215,521
Messages
6,125,307
Members
449,218
Latest member
Excel Master

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