Excelmacros:双循环添加两个单元toegther
背景:我正在尝试改进我用于清单的Excel电子表格。 我需要添加两个单元格,并将结果放回到第一个(原始单元格)。 这里是Excel工作表的截图
我创build了一个双循环遍历所有单元格并将它们添加在一起。 我遇到的地方是如何实际将两个单元格加在一起。
这是我的代码… 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
您不需要使用AR2作为“控股单元”。 只需保留价值。 如果您需要使用工作表的本机SUM函数 (单元格值可能是文本)的安全开销,那么可以使用WorksheetFunction对象或Excel应用程序对象来方便使用它。
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
顺便说一句,原来的公式是缺less一个右括号,你需要Range.Address属性 ,而不是Range对象 。
Range("AR2").Formula = "=SUM(" & Cells(r,i).Address & "," & Cells(r,p).Address & ")"