Sum函数在VBA中
我在vba中求和单元格有问题。 我需要使用单元格(a,b):
Range("A1").function="=SUM(Range(Cells(2,1),Cells(3,2)))"
但它不起作用。
函数不是来自范围的属性/方法。
如果你想总结价值然后使用以下内容:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
编辑:
如果你想要的公式,然后使用如下:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")" 'The two false after Adress is to define the address as relative (A2:B3). 'If you omit the parenthesis clause or write True instead, you can set the address 'as absolute ($A$2:$B$3).
如果你总是要使用相同的范围地址,那么你可以使用Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
将函数值放入单元格中
Application.Sum往往不能很好地工作在我的经验(或者至lessVBA开发环境不喜欢它出于任何原因)。
最适合我的函数是Excel.WorksheetFunction.Sum()
例:
Dim Report As Worksheet 'Set up your new worksheet variable. Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable. Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
将函数直接放入单元格中
你正在寻找的另一种方法我认为是将函数直接放入单元格中。 这可以通过将函数stringinput单元格值来完成。 下面是一个例子,提供了与上面相同的结果,除了单元格的值是函数而不是函数的结果:
Dim Report As Worksheet 'Set up your new worksheet variable. Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable. Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
将无法工作,因为工作表函数(实际上在工作表上使用时)不理解Range
或Cell
尝试
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"
Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))
哪里
Range("A10")
是答案单元格
Range("A1", "A9")
是要计算的范围