插入引用ActiveCell.Offset值(VBA)的SUM函数

时间:2017-11-30 22:48:10

标签: excel vba loops sum

我需要将sum函数输入到引用ActiveCell.Offset值的单元格中。有没有办法在VBA中执行此操作?这是迄今为止的代码:

 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

1 个答案:

答案 0 :(得分:0)

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

请注意,您要在.Offset(0, 2)中设置一个值,然后在同一个单元格中插入一个公式。您可能使用了错误的单元格引用。