简体   繁体   English

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

[英]Excel VBA- Dynamic formula returning zero value for range

I am trying to have vba create a formula for two ranges within the same data set, as input into variables lastRow and lastRow2. 我试图让vba在同一数据集中为两个范围创建一个公式,作为变量lastRow和lastRow2的输入。 However, when I try to create and calculate the formula, instead of getting the value of the last cell I get a zero. 但是,当我尝试创建和计算公式时,没有得到最后一个单元格的值,而是得到了零。 Offending code below: 令人反感的代码如下:

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"

Running this gets two formulas: =(SUM(J11:J0)/ sum(I11:I0)) and =(SUM(U11:U0)/ SUM(T11:T0)). 运行此命令可获得两个公式:=(SUM(J11:J0)/ sum(I11:I0))和=(SUM(U11:U0)/ SUM(T11:T0))。 Why is the end of the range a zero??? 为什么范围的结尾为零???

I'm pretty sure what is happening if you are not defining which worksheet the range() and row() objects are on so VBA is guessing and probably guessing incorrectly. 我很确定,如果您没有定义range()和row()对象位于哪个工作表上,那么VBA会猜测并且可能会猜测不正确。 Try adding a worksheet object and then defining all the ranges and rows to use be on that worksheet. 尝试添加工作表对象,然后定义要在该工作表上使用的所有范围和行。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM