问题
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
回答1:
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 first ELSEIF statement.
Sub Test()
Dim rng As Range
Dim Cell As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A20")
For Each Cell In rng
If Cell.Address = rng(1).Address Then
If Cell.Value = 0 Then
Cell.Value = Cell.Offset(1, 0).Value
End If
ElseIf Cell.Address = rng(rng.Cells.Count).Address Then
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
End Sub
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).
Sub Test()
Dim rng As Range
Dim Cell As Range
Dim col As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:Z20")
For Each col In rng.Columns
For Each Cell In col.Cells
If Cell.Address = rng(1).Address Then
If Cell.Value = 0 Then
Cell.Value = Cell.Offset(1, 0).Value
End If
ElseIf Cell.Address = rng(rng.Cells.Count).Address Then
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
Next col
End Sub
来源:https://stackoverflow.com/questions/47515141/cell-address-in-a-loop