簡體   English   中英

將一列中所有單元格的值添加到另一列中的相應單元格,然后清除原始單元格

[英]Add value in all cells within a column to corresponding cell in another column and then clear original cells

我需要根據B列中輸入的數字創建一個Excel文檔,並在A列中更新總計。 每當添加新值時,行A中的每個相應單元格都應基於其等效的B單元格值進行更新,然后,一旦添加到A中,就清除輸入到B中的值。

我已經完成了單行工作,但是沒有知識或了解如何最好地使整列中的每個單元對都有效。 我真的不想復制並粘貼此10,000次並更新單元格以引用正確的對。 單個單元格的代碼:

Private bIgnoreEvent As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
    If bIgnoreEvent Then Exit Sub
    bIgnoreEvent = True
    Cells(1, 2) = Cells(1, 2) + Cells(1, 1)
    Cells(1, 1) = ""
    bIgnoreEvent = False
End Sub

我希望可以通過循環功能或某種范圍的方法來實現。

這應該工作:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, c As Range

    'any updates in ColB?
    Set rng = Application.Intersect(Target, Me.Columns(2))

    If Not rng Is Nothing Then
        Application.EnableEvents = False '<< prevent re-triggering of event
        'Process each updated cell
        For Each c In rng
            If IsNumeric(c.Value) Then
                With c.Offset(0, -1)
                    .Value = .Value + c.Value
                End With
                c.ClearContents
            End If
        Next c
        Application.EnableEvents = True  '<< re-enable event
    End If

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM