在VBA Sum函数在VBA Sum函数(Sum function in VBA)

2019-05-12 05:00发布

我有一个在VBA总结细胞的一个问题。 我需要使用电池(A,B):

Range("A1").function="=SUM(Range(Cells(2,1),Cells(3,2)))"

但它不工作。

Answer 1:

功能不是从范围内的属性/方法。

如果要总结的值,然后使用以下命令:

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).

如果你是百达将使用相同的范围地址,然后你可以使用如罗里sugested:

Range("A1").Formula ="=Sum(A2:B3)"


Answer 2:

将函数进入细胞

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.


Answer 3:

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

不会工作,因为工作表函数(当实际的工作表上使用)不明白RangeCell

尝试

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"


Answer 4:

Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))

哪里

Range("A10")就是答案细胞

Range("A1", "A9")是计算的范围



文章来源: Sum function in VBA