我有两列A和B,数字作为值。
=A1 + B1
=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
答案 0 :(得分:3)
只需将您的Until条件替换为以下字符串:
Loop Until IsEmpty(ActiveCell.Offset(1, -2))
这将检查正确的单元格是否为空。其余代码应保持不变。
答案 1 :(得分:3)
看看Do Until
and Do While
and 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
输出:
答案 2 :(得分:2)
我不是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
答案 3 :(得分:1)
我以为我会推荐一个略有不同的行动方案,只是为了给你一些想法:):
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