I am trying to have vba create a formula for two ranges within the same data set, as input into variables lastRow and 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)). 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. 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.