且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将值从一个单元格添加到另一个单元格,然后重置单元格值.电子表格

更新时间:2023-02-04 21:04:48

在工作表的VBA专用模块上(右键单击报告"选项卡,然后单击查看代码"),输入以下代码:

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 .

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

Application.EnableEvents = False 阻止代码连续运行(如果没有运行,对B1的更改也将称为Worksheet_change).

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

此代码假定B1中的值始终是数字(或空白).如果其中可能包含字符文本,则需要进行检查以重置其值或不执行增量操作.

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.