Scroll through column from top to bottom and repla

2020-05-03 00:50发布

I have to scroll through a column (actually two, but if I can get one going I can manage) from top to bottom and replace the 0's or blanks with cell value above it. This is what I have so far (it doesn't work):

Sub ReplaceZeros()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

lr = Cells(Rows.Count, "A").End(xlUp).Row                                          
For i = lr To 2 Step 7000                                                             
    If Cells(i, "A").Value = 0 Then Cells(i, "A").Replace_
    What: 0, Replacement:= "cell(i-1,"A").value,_
    SearchOrder:=xlByColumns, MatchCase:=True

Next i


Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

1条回答
闹够了就滚
2楼-- · 2020-05-03 01:44

So close:

Sub ReplaceZeros()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim lr As Long
Dim i As Long
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
    lr = .Cells(.Rows.Count, "A").End(xlUp).Row
    For i = 2 To lr
        If .Cells(i, "A").Value = 0 Then .Cells(i, "A").Value = .Cells(i - 1, "A").Value
    Next i
End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

Note: The loop you had started at the bottom and went up, this would be fine but if you had two '0' in a row the second would remain zero, plus the step 7000 made the loop skip 7000 rows at a time.

Then if all you want is the value above using Cells(i-1,"A").value will return the value of the cells directly above.

查看更多
登录 后发表回答