Excel VBA-动态公式返回范围的零值

时间:2016-05-23 18:48:01

标签: excel vba excel-vba

我试图让vba为同一数据集中的两个范围创建一个公式,作为变量lastRow和lastRow2的输入。但是,当我尝试创建并计算公式时,不是获取最后一个单元格的值,而是获得零。以下违规代码:

Dim lastRow As Long
Dim lastRow2 As Long
    lastRow = Range("A" & Rows.Count).End(xlUp).Row
    lastRow2 = Range("M" & Rows.Count).End(xlUp).Row


...



    'Calculate ATRT 2014 at cell B4
    Range("B6").Formula = "=(SUM(J11:J" & lastRow & ")/ SUM(I11:I" & lastRow & "))"
    Range("E6").Formula = "=(SUM(U11:U" & lastRow2 & ")/ SUM(T11:T" & lastRow2 & "))"
    Range("H6").Formula = "=E6-B6"

运行它会得到两个公式:=(SUM(J11:J0)/ sum(I11:I0))和=(SUM(U11:U0)/ SUM(T11:T0))。为什么范围的结束为零???

1 个答案:

答案 0 :(得分:0)

如果你没有定义range()和row()对象所在的工作表,我很确定会发生什么,所以VBA猜测并且可能猜错了。尝试添加工作表对象,然后定义要在该工作表上使用的所有范围和行。

Dim lastRow As Long
Dim lastRow2 As Long
Dim ws As Worksheet

Set ws = ActiveSheet
lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
lastRow2 = ws.Range("M" & ws.Rows.Count).End(xlUp).Row


'...



'Calculate ATRT 2014 at cell B4
ws.Range("B6").Formula = "=(SUM(J11:J" & lastRow & ")/ SUM(I11:I" & lastRow & "))"
ws.Range("E6").Formula = "=(SUM(U11:U" & lastRow2 & ")/ SUM(T11:T" & lastRow2 & "))"
ws.Range("H6").Formula = "=E6-B6"