How to find a difference between previous and current values in Excel Cell?

浪子不回头ぞ 提交于 2019-12-25 01:38:07

问题


A1 = time start using cntrl+shift+ which shows 4:00 AM

B1 = time end using cntrl+shift+ which shows 8:00 AM

C1 = time between using =MOD(B1-A1,1) which shows 4:00:00

D1 = time from cell C1 converted into minutes using =C1*1440 which shows 240 minutes

E1 = D1 new value - D1 old value (Example: if old value was 240, and new is 360, then 360-240 = 120.)

The bold is what I want, and I can only hope you guys can understand what I am trying to accomplish. I'll try to be clearer if need be as you wish. Thanks in advance!


回答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,



来源:https://stackoverflow.com/questions/27578950/how-to-find-a-difference-between-previous-and-current-values-in-excel-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!