简体   繁体   中英

Add value from one cell to another then reset cell value. Excel

Hope someone can answer us.

We want to do the following:

When a value is entered in A1, this value is added to the value of B1.

We then want the value of A1 too reset to 0, but keep the value of B1

Is this possible in excel?

On the worksheet's VBA private module (right-click the report tab and hit "View Code"), enter the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    If Target.Address = Range("a1").Address Then
        Range("b1") = Range("b1") + Range("a1")
        Range("a1").ClearContents
    End If
    Application.EnableEvents = True
End Sub

Worksheet_Change is called whenever a change is made to the worksheet.

Application.EnableEvents=False prevents the code from running continuously (without it, the change to B1 would also call Worksheet_change).

This code assumes that the value in B1 is always numeric (or blank). If it may contain character text, then a check will need to be put in place to either reset its value or not do the increment.

Using simoco's suggestion:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A1 As Range
    Set A1 = Range("A1")
    If Intersect(Target, A1) Is Nothing Then
    Else
        Application.EnableEvents = False
        With A1
            .Offset(0, 1) = .Offset(0, 1) + .Value
            .ClearContents
        End With
        Application.EnableEvents = True
    End If
End Sub

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