Loop Through Cells


July 07, 2002 - by

Richard writes:

If I may be so bold to ask, I should be grateful if you could enlighten me as to the answer to this perplexing conundrum on syntatical integrity videlict:

When referencing a cell for external use in VisualBasic for example via "Range("F3").Select" suppose that I wish instead of the column 1 to substitute a variable from a loop to the following end:

For Scarab=3 To 15
	Range("FScarab").Select
	ActiveCell.Value = Scarab * Scarab - 3
Next Scarab

for instance.



Clearly, one can not just use FScarab where before one would have had F3 but perhaps there is a method via which the desired result can be achieved. That is, is there a way to refer to the cell in column F and row Scarab for the variable Scarab and if so could you divulge this information.

There are several ways to do this. Probably the most intuitive is this method which involves concatenating the column letter "F" with the numeric row number inside of the Range() reference.

For Scarab=3 To 15
	Range("F" & Scarab).Select
	ActiveCell.Value = Scarab * Scarab - 3
Next Scarab

The next method uses the CELLS(row, column) function instead of the Range reference. In this case, row and column need to be numeric. Your row number variable already is numeric, so you simply have to convert the "F" to a 6 in your head. You will also note that it is not necessary to select the cell, you can simply assign a value to it.

For Scarab=3 To 15
	Cells(Scarab, 6).Value = Scarab * Scarab - 3
Next Scarab

Finally, it is possible to simply loop through each cell in the range:

For Each cell in Range("F3:F15")
	Cell.Value = Cell.Row * Cell.Row - 3
Next Cell