简体   繁体   中英

substract using activecell.offset

my lastrow is (315) - in the below code i need help in the last line (i am trying to do (sum of col H) - (sum of col J) by using activecell-offset in col k

''Totals''
Range("K" & LastRow).Offset(5, 0).Formula = "=activecell.offset(0,-3)-activecell.offset(0-1)"

我不知道你的最后一行是如何变成315你有320的数据,但你正在寻找这个:

Range("K" & LastRow).Offset(5, 0).Value = ActiveCell.offset(0,-3) - ActiveCell.offset(0-1)
Range("K" & LastRow).Offset(5, 0).Formula = "=" & ActiveCell.Offset(0, -3).Address & "-" & ActiveCell.Offset(0 - 1).Address

This would work, but is not pretty. An alternative would be a static VBA solution such as Damian's answer.

Furthermore, I would advise you to refer to the correct workbook and -sheet. If you were to omit this, the VBA code would always refer to the active workbook/-sheet, something you often don't want.

Eg

With Workbooks(REF).Sheets(REF)
     .Range("K" & LastRow).Offset(5, 0).Formula = "=" & ActiveCell.Offset(0, -3).Address & "-" & ActiveCell.Offset(0 - 1).Address
End With

Next to that, referring to the active cell is also asking for trouble. Perhaps you are better off with referring to better defined ranges, such as

With Workbooks(REF).Sheets(REF)
     .Range("K" & LastRow).Offset(5, 0).Formula = "=" & .Cells(LastRow + 4, "K").Address & "-" & .Cells(LastRow, "J").Offset(0 - 1).Address  'Ranges randomly chosen 
End With

EDIT

Formulas are dynamic. In other words, their results change dynamically with values/ranges they refer to. Unless you code a Worksheet_Change event, the calculation below will not update if you change the values for which the sum is calculated. However, you don't always need calculations to be dynamic, so pick what you need. I am assuming your columns have headers.

With Workbooks(REF).Sheets(REF)
    LastRow = .Cells(.Rows.Count, "K").End(xlUp).Row
    LROWJ = .Cells(.Rows.Count, "J").End(xlUp).Row
    LROWH = .Cells(.Rows.Count, "H").End(xlUp).Row
    .Range("K" & LastRow).Value = Application.Sum(.Range("H2:H" & LROWH)) - Application.Sum(.Range("J2:J" & LROWJ))
End With

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.

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