Sub Reflector()
Dim i As Integer
Dim endRow As Integer
endRow = Cells(Rows.Count, "B").End(xlUp).Row
Range("G2").Select
For i = 2 To 40
Range("G" & i).Select
If Range("H" & i).Value = "1" Or Range("H" & i).Value = "-1" Then
ActiveCell.Formula = "=ROW(A1)"
ActiveCell.AutoFill Destination:=Range(ActiveCell.Address & ":G" & endRow)
End If
Next i
End Sub
我想要的是宏检查H列中的值并保持它没有-1或1的次数,然后在G列中写入该值。如果它达到1或-1的值G栏,我希望重新开始计数。
过程是我将检查H列和自动填充到最后一行数据并“反弹”以检查下一个值,然后再次自动填充,如果它满足1或-1。
这是我得到的错误:
答案 0 :(得分:1)
Avoid using Select in and ActiveCell(除非绝对必要)。
试试这段代码:
Sub Reflector()
Dim ws as Worksheet
Set ws = WOrksheets("Sheet1") 'change as needed
Dim i As Integer
Dim endRow As Integer
endRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For i = 2 To 40
If ws.Range("H" & i).Value = "1" Or ws.Range("H" & i).Value = "-1" Then
With ws.Range("G" & i)
.Formula = "=ROW(A1)"
.AutoFill Destination:=ws.Range(ws.Range("G"&i),ws.Range("G" & endRow))
End With
End If
Next i
End Sub
<强>更新强>
对于@ ScottCraner来说,这段代码也可以工作,更容易阅读/维护。
Dim ws As Worksheet
Set ws = Worksheets("Sheet1") 'change as needed
Dim endRow As Long
endRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
With ws.Range("G2:G" & endRow)
.FormulaR1C1 = "=IF(OR(RC[1]=1,RC[1]=-1),1,R[-1]C+1)"
End With
经过测试的代码的屏幕截图: