excel 如何在下面的单元格中应用VBA?

4dc9hkyq  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(135)
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:C2")) Is Nothing Then
        On Error Resume Next
        Application.EnableEvents = False
        If Application.WorksheetFunction.CountA(Range("A2:C2")) = 0 Then
            Range("D2").ClearContents
        Else
            Range("D2").Formula = "=SUM(A2:C2)"
        End If
        Application.EnableEvents = True
        On Error GoTo 0
    End If
End Sub

我希望这个VBA目前在一行工作的方式,以同样的方式,它也应该做下面的行。

rbpvctlc

rbpvctlc1#

Formula2R1C1使创建相对公式变得容易。我通常不自己写Formula2R1C1公式。相反,我将一个普通公式添加到ActiveCell,然后将Formula2R1C1打印到即时窗口。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:C3")) Is Nothing Then
        On Error Resume Next
        Application.EnableEvents = False
        If Application.WorksheetFunction.CountA(Range("A2:C2")) = 0 Then
            Target.EntireRow.Range("D1").ClearContents
        Else
            Target.EntireRow.Range("D1").Formula2R1C1 = "=SUM(RC[-3]:RC[-1])"
        End If
        Application.EnableEvents = True
        On Error GoTo 0
    End If
End Sub
kq0g1dla

kq0g1dla2#

这将处理跨行的多单元格更新:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, rw As Range, c As Range, rngSum As Range
    Set rng = Application.Intersect(Target, Me.Range("A2:C100")) 'for example
    If Not rng Is Nothing Then
        For Each rw In rng.Rows 'check each changed row...
            Set rngSum = rw.EntireRow.Range("A1:C1") 'range is *relative* to `rw`
            Set c = rw.EntireRow.Columns("D")
            If Application.CountA(rngSum) = 0 Then
                c.ClearContents
            Else
                c.Formula = "=SUM(" & rngSum.Address(False, False) & ")"
            End If
        Next rw
    End If
End Sub

相关问题