停止excel do-loop直到

我有两个列A和B与数字作为值。

  • 在C1我想=A1 + B1
  • 在C2我想=A2 + B2

等等。 我已经写了下面的VBA代码 – 当它工作的时候,在范围的最后一行结束之后加上“0”。

假设我的最后一行是A10。 当我运行代码时,它在C11中添加了“0”。 我如何防止这种情况?

 Sub macro() Dim R As Long R = 1 Do Cells(R, "C").Select R = R + 1 ActiveCell.Formula = "=sum(" & ActiveCell.Offset(0, -2) & "," & ActiveCell.Offset(0, -1) & ")" Loop Until IsEmpty(ActiveCell.Offset(0, -2)) End Sub 

只要将您的直到条件replace为以下string:

Loop Until IsEmpty(ActiveCell.Offset(1, -2))

这将检查正确的单元格是空的。 其余的代码应该保持不变。

看看Do Until Do While While

如果你真的想迭代单元格,你可以继续。 但在这里使用Arrays的方法,这将通过一切手段降低任何性能下降,你会得到循环通过单元格…

 Option Explicit Sub AddToRigh() Dim i As Integer Dim vArr As Variant Dim LastRow As Long '--assume you are working on Sheet 1 LastRow = Sheets(1).Cells(Rows.Count, Range("A1").Column).End(xlUp).Row ReDim vArr(1 To LastRow) For i = LBound(vArr) To UBound(vArr) vArr(i) = "=Sum(RC[-2]:RC[-1])" Next i '--output this entire array with formulas into column C Sheets(1).Range("C1").Resize(UBound(vArr)) = Application.Transpose(vArr) End Sub 

输出:

在这里输入图像说明

我绝不是vba的专家,但你可以这样做:

 Sub macro() Dim R As Long R = 1 Do While Not IsEmpty(ActiveCell.Offset(0, -2)) Cells(R, "C").Select R = R + 1 ActiveCell.Formula = "=sum(" & ActiveCell.Offset(0, -2) & "," & ActiveCell.Offset(0, -1) & ")" Loop End Sub 

我以为我会推荐一个稍微不同的行动方式,只是为了给你想法:):

 Sub macro() Dim found As Range Set found = Range("A:A").Find("*", after:=Range("A1"), searchdirection:=xlPrevious) If Not found Is Nothing Then Range(Range("A1"), found).Offset(0, 2).FormulaR1C1 = "=RC[-2]+RC[-1]" End If End Sub