I am looping through a range of cells to check if a value is 0. My logic is if cell value is zero, then cell value is the previous cells value. If that previous cell is also zero, then it is the next cell's value. But I said what if the last cell or first cell is zero? I need to check that too because if it is the first cell or last, then the loop fails. My question is, what should the code be to pass through the last row as an address. I know the last row, but I do not know how to write it as an address with a known column. The data starts at row 2 and then goes to row X.
For each Cell In rng
If Cell.Address="A2" Then
If Cell.Value=0 Then
Cell.Value=Cell.Offset(1,0).Value
End if
Elseif Cell.Address="AX" Then 'X is the last row
If Cell.Value=0 Then
Cell.Value=Cell.Offset(-1,0).Value
End If
Elseif Cell.Value=0 and Cell.Offset(1,0).Value=0 Then
Cell.Value=Cell.Offset(-1,0).Value
Elseif Cell.Value=0 Then
Cell.Value=Cell.Offset(1,0).Value
Else
Do Nothing
End If
Next
I've added three rows to define the variables and range.
Other than that I've only made changes to the
IF
statement and the firstELSEIF
statement.Edit: (after answer accepted).
To loop through each cell in each column you'll need a loop to look at each column and then another to look at each cell within the column.
In the code below I have defined
col
as a range.This is then used in the first loop (
For Each col in rng.Columns
).The second loop then looks at each cell within
col
(For Each Cell in col.Cells
).