简体   繁体   中英

Inserting a SUM function that references ActiveCell.Offset values (VBA)

I need to enter the sum function into a cell which references ActiveCell.Offset values. Is there a way to do this in VBA? Here is the code thus far:

 For Each cell In Rec
    If cell.Value = "Y" And cell.Offset(0, 1).Value = "Y" Then
            cell.Activate
            Selection.Clear
            ActiveCell.Offset(0, 1).Clear
            ActiveCell.Offset(0, 2).Value = ActiveCell.Offset(0, 2).Value - (ActiveCell.Offset(0, 3).Value + ActiveCell.Offset(0, 6).Value)
            ActiveCell.Offset(0, 6).Clear
            ActiveCell.Offset(0, 7).Clear
            ActiveCell.Offset(0, 3).Clear
            ActiveCell.Offset(0, 2).Formula = "=SUM(ActiveCell.Offset(0,4):ActiveCell.Offset(0,5))"
            Range("A" & ActiveCell.Row & ":S" & ActiveCell.Row).Copy
            pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
            Range("A" & ActiveCell.Row & ":S" & ActiveCell.Row).Delete
End If
Next
For Each cell In Rec
   With cell
       If .Value = "Y" And .Offset(0, 1).Value = "Y" Then
               .Clear
               .Offset(0, 1).Clear
               .Offset(0, 2).Value = .Offset(0, 2).Value - (.Offset(0, 3).Value + .Offset(0, 6).Value)
               .Offset(0, 6).Clear
               .Offset(0, 7).Clear
               .Offset(0, 3).Clear
               .Offset(0, 2).Formula = "=SUM(" & .Offset(0, 4).Resize(, 2).Address(1, 1) & ")"
               ActiveSheet.Range("A" & .row & ":S" & A.row).Copy
               pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
               ActiveSheet.Range("A" & ActiveCell.row & ":S" & ActiveCell.row).Delete
        End If
    End With
Next

One note you are setting a value in .Offset(0, 2) then a few lines later inserting a formula in that same cell. You may be using the wrong cell reference.

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