我在 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 所建议的那样使用:
Range("A1").Formula ="=Sum(A2:B3)"
根据我的经验,Application.Sum 通常不能很好地工作(或者至少 VBA 开发人员环境不喜欢它,无论出于何种原因)。
最适合我的功能是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.
我认为您正在寻找的另一种方法是将函数直接放入单元格中。这可以通过将函数字符串输入到单元格值中来完成。这是一个提供与上面相同结果的示例,除了单元格值是函数而不是函数的结果:
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")
是要计算的范围