Is 'For Each' and 'For i = 1 to n' work in different ways?

prabha_friend

Board Regular
Joined
Jun 28, 2011
Messages
95
Data:
C1: 3
B2: 2
D2: 2
A3: 1
E3: 1
B4: 2
D4: 2
c3: 3

Code:
Sub mac()
'MsgBox Selection.Cells.Count
For Each cell In Selection.Cells
    MsgBox cell.Address
Next cell
End Sub

Code:
Sub mac1()
'MsgBox Selection.Cells.Count
For i = 1 To Selection.Cells.Count
    MsgBox Selection.Cells(i).Address
Next i
End Sub
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
It depends on the use.

If you are going to the same thing to each cell (e.g. add 1 to it) then For Each is a good choice.
If what you are going to do varies with which cell (e.g. add 1 to the first, 2 to the second,...) the For I = ... is good.

If you are trying to keep two arrays (or ranges) in sync, then For I might be better.

Which to use depends on what you are going to do.
 
Upvote 0
Code:
Sub mac()
'MsgBox Selection.Cells.Count
For Each cell In Selection.Cells
    MsgBox cell.Address
Next cell
End Sub
Gives me the proper result:
C1
B2
D2
A3
E3
B4
D4
c3

but...

Code:
Sub mac1()
'MsgBox Selection.Cells.Count
For i = 1 To Selection.Cells.Count
    MsgBox Selection.Cells(i).Address
Next i
End Sub
gives...

C1
C2
C3
C4
C5
C6
C7
C8

why?

so 'for each' and 'for i = 1 to n' is entirely different when comes to selection? I want to store them in a 2D array as per row,col...
 
Upvote 0
The Cells property properly needs two arguments, and the result is not limited to the range it is a member of.
For what you are looking for, the Item property would work best.

Code:
MsgBox Selection.Item(I).Address
 
Upvote 0

Forum statistics

Threads
1,216,100
Messages
6,128,834
Members
449,471
Latest member
lachbee

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