保持对单元格值的每次更改的计数

时间:2019-01-30 12:43:21

标签: excel vba auto-increment

假设我在单元格A1中有一个值,并且每次A1的单元格值更改时,b1上的单元格都会计算该更改。

我有一个代码,它仅适用于A1(值)单元格和b1(零钱计数)单元格。我想将此功能应用于单元格E2:E709(值)单元格和F2:F709(变化计数)单元格。

Private Sub Worksheet_Change(ByVal Target As Range)
Static OldVal As Variant
If Target.Address(False, False) = "A1" Then
Application.EnableEvents = False
If Target.Value <> OldVal Then
    Target.Offset(, 1).Value = Target.Offset(, 1).Value + 1
    OldVal = Target.Value
End If
Application.EnableEvents = True
End If
End Sub

2 个答案:

答案 0 :(得分:0)

考虑:

Private Sub Worksheet_Change(ByVal Target As Range)
    Static OldVal(2 To 709) As Variant
    Dim E As Range, F As Range, r As Range, Intersekt As Range
    Dim rw As Long

    Set E = Range("E2:E709")
    Set F = Range("F2:F709")

    Set Intersekt = Intersect(E, Target)
    If Intersekt Is Nothing Then Exit Sub

    Application.EnableEvents = False
        For Each r In Intersekt
            rw = r.Row
            If r.Value <> OldVal(rw) Then
                r.Offset(0, 1).Value = r.Offset(0, 1).Value + 1
                OldVal(rw) = r.Value
            End If
        Next r
    Application.EnableEvents = True
End Sub

我们对OldVal使用数组,而不是单个项目
我们使用(可能)多单元格Intersekt Range`,以便一次更改多个单元格。

答案 1 :(得分:0)

请尝试以下代码:

function operationEvaluator({ left, op, right }) {
    const
        operators = {
            '+': (a, b) => a + b,
            '-': (a, b) => a - b,
            '*': (a, b) => a * b,
            '/': (a, b) => a / b
        },
        getOperand = o => typeof o === 'object'
            ? operationEvaluator(o)
            : o;

    return operators[op](getOperand(left), getOperand(right));
}

var op1 = { left: 5, op: '-', right: { left: 3, op: '*', right: { left: 8, op: '-', right: { left: 200, op: '/', right: 5 } } } },
    op2 = { left: { left: 10, op: '*', right: { left: 2, op: '+', right: 1, }, }, op: '+', right: { left: 5, op: '*', right: { left: 1, op: '-', right: { left: 1, op: '+', right: 2 } } } };

// prosses: 5 - (3 * (8 - (200 / 5)))
console.log(operationEvaluator(op1)); // 101
// prosses: ((10 * (2 + 1)) + (5 * (1 - (1 + 2)))
console.log(operationEvaluator(op2)); // 20