2016-02-23 16 views
0

背景:我试图改进我用于清单的excel电子表格。我需要将两个单元格加在一起,并将结果放回第一个单元格(原始单元格)。 Here is a screenshot of the excel sheet...Excel宏:双循环添加两个单元toegther

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

这里是我的代码... 私人小组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

+0

您是不是想要增加列AR中的行? – Jeeped

+0

我不认为这是必要的,因为我只是将它用作公式的附加单元,将原始的两个单元格添加在一起。我想不出一个更好的方法来使它工作。 :( –

+0

您可以使用'Cells(r,i).Value = WorksheetFunction.Sum(Cells(r,i).Value,Cells(r,p).Value)'将公式分配给AR2 – SincereApathy

回答

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 & ")" 
+0

非常感谢!这正是我所需要的!我将更深入到工作表函数对象和Excel应用程序对象中 –