如何找到在Excel单元格中以前和当前值之间的差异?(How to find a differenc

2019-10-28 10:49发布

A1 =时间开始使用CNTRL +移+表示上午4点

使用CNTRL +移+表示8:00 AM B1 =时间结束

C1 =使用之间的时间= MOD(B1-A1,1)示出四点00分00秒

D1 =来自小区C1时间转换成用分钟= C1 * 1440表示240分钟

E1 = D1新值- D1旧值(示例:如果旧值是240,并且新的是360,则360-240 = 120)

大胆的是我想要什么,我只希望你们能理解我试图完成。 我会试着更清楚,如果需要的话,如你所愿。 提前致谢!

Answer 1:

In order to find a difference between new and old values entered, for example, in "D1" (on cell change event) and display it cell "E1", the general solution is shown in following code snippet (see Listing 1):

Listing 1

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Column = 4 And Target.Row = 1 Then
        'new val
        newVal = Range("D1").Value
        Application.EnableEvents = False
        Application.Undo
        'old val
        oldVal = Range("D1").Value
        Range("D1").Value = newVal
        'diff between new and old val
        Range("E1").Value = newVal - oldVal
        Application.EnableEvents = True
    End If
End Sub

Pertinent to your particular case (assuming that time is entered by pressing combination CTRL+SHIFT+: (or just typed) in either cell "A1" or "B1", the modified code snippet is shown in Listing 2.

Listing 2

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Row = 1 And (Target.Column = 1 Or Target.Column = 2) Then
        'new val
        a1 = Range("A1").Value
        b1 = Range("B1").Value
        newVal = Range("D1").Value

        'disable events and undo
        Application.EnableEvents = False
        Application.Undo
        'old val
        oldVal = Range("D1").Value

        'diff between new and old val
        diff = newVal - oldVal

        Range("A1").Value = a1
        Range("B1").Value = b1
        Range("E1").Value = diff

        're-enable events
        Application.EnableEvents = True
    End If
End Sub

On a separate note, your Worksheet computation could be simplified if you use a formula for a difference in minute like: =MOD(B1-A1,1)*1440 entered in a single cell (e.g. "D1") instead of using the couple ("C1" and "D1"). Also, the entire computation could be performed solely in VBA module, updating "E1" value based on entries in "A1" and "B1" (no need for "C1" and "D1" in this scenario).

Hope this will help. Best regards,



文章来源: How to find a difference between previous and current values in Excel Cell?