SUM函数与来自另一个工作表的数据

时间:2015-10-19 18:45:07

标签: excel vba reference

我正在尝试在VBA中使用SUM函数来引用另一个工作表。该函数需要动态输入,因此我使用“Cells”。

只需添加两个单元格即可使用以下代码:

   Worksheets("Derived Data").Cells(2, 1).Formula = "=sheet1!" & (Cells(2, 2).Address & "+" & "sheet1!" & Cells(6, 2).Address)

当我尝试使用SUM或AVERAGE等函数或任何其他函数时,VBA将该函数解释为子宏而不是EXCEL函数

Worksheets("Derived Data").Cells(i, 1).Formula = "=sheet1!" & Sum(Cells(2, 2).Address & ":" & "sheet1!" & Cells(6, 2).Address)

我的推荐错了吗?

注意:已修​​复单元格和列以进行调试。

2 个答案:

答案 0 :(得分:1)

你几乎就在那里,你只是没有正确的语法来让VBA设置公式。试试这个:

Worksheets("Derived Data").Cells(i, 1).Formula = "=Sum(sheet1!" & Cells(2, 2).Address & ":sheet1!" & Cells(6, 2).Address & ")"

答案 1 :(得分:1)

接近试试这个:

Worksheets("Derived Data").Cells(i, 1).Formula = "=sum(sheet1!" & Range(Cells(2, 2), Cells(6, 2)).Address & ")"

由于公式要求范围,因此使用vba需要使用范围。

为了更容易编辑我的偏好,可以将其拆分,但上面的单行可以正常工作。

Dim rng as Range
with sheets("Sheets1")
    set rng = .Range(.Cells(2, 2), .Cells(6, 2))
end with
Worksheets("Derived Data").Cells(i, 1).Formula = "=sum(" & rng.Parent.Name & "!" & rng.Address & ")"
相关问题