Excel宏:双循环添加两个单元格

时间:2016-02-23 02:37:33

标签: excel loops macros

背景:我正在尝试改进我用于库存的Excel电子表格。我需要将两个单元格一起添加并将结果放回第一个(原始单元格)。 Here is a screenshot of the excel sheet...

我创建了一个双循环来遍历所有单元格并将它们添加到一起。我遇到的地方是如何将两个单元格实际加在一起。

这是我的代码......     Private Sub CommandButton1_Click()

Dim i As Integer, p As Integer, r As Integer, v As Integer
' i is for the column in Inventory
' p is for the column in Pending
' r is for the current row
' v is the holding variable for the Sum of both cells


    For r = 2 to 30
For i = 2 To 18
Range("AR2").Formula = "=SUM(Cells(r,i),Cells(r,p)" 'This is not proper syntax I think
    v = Range("AR2").Value 'Assigning the value fo he forumla to the variable

    Cells(r, i).ClearContents
    Cells(r, p).ClearContents

    Cells(r, i).Value = v 'need to add an if/then statment to clear cell is value is zero

    Range("AR2").ClearContents 'Do I really need this here cant I add this after the loop?
Next i
Next r
End Sub`

有人可以帮我解决这个问题吗?我在代码中提出了我的意见/问题以提供帮助。谢谢你提前!!!

Alex S

1 个答案:

答案 0 :(得分:1)

您不需要将AR2用作“保持单元”。只需保留价值。如果您需要使用工作表的原生SUM function的安全开销(单元格值可能是文本),请使用WorksheetFunction objectExcel Application object以方便其使用。

For r = 2 to 30
    For i = 2 To 18
        v = Application.Sum(Cells(r,i), Cells(r,p))

        Cells(r, i).ClearContents
        Cells(r, p).ClearContents

        if cbool(v) then 'v is not zero
            Cells(r, i).Value = v
        end if

    Next i
Next r

顺便说一句,原始公式缺少结束括号,您需要Range.Address property,而不是Range object

Range("AR2").Formula = "=SUM(" & Cells(r,i).Address & "," & Cells(r,p).Address & ")"