PDA

View Full Version : Excel VBA Code help



Melvin9900
03-12-2021, 07:29 PM
In my Excel when someone change a value in the cell it calls the VBA code to add a audit log into the database. Logic is added inside Private Sub Worksheet_Change()

Failure Scenario - If some one double clicks a cell and doesn't change any value. But Sub Worksheet_Change() still gets execute and audit is added.
I thought Worksheet_Change() is called only if we change anything in the cell.

I can update the query to compare the database value with the cell value before update but I want to see are there any other better way in the excel to call Private Sub Worksheet_Change()
only if cell value is actually changed not just for double click.

Please help.

SamT
03-12-2021, 09:03 PM
Option Explicit

Dim DClckd As Boolean

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
DClckd = True
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
DClckd = False
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Address
End Sub

p45cal
03-13-2021, 04:34 AM
That won't be the only failure scenario; if someone edits the cell using any method to get into that editing mode and doesn't change the data and presses Enter (or moves off the cell with the arrow keys) it will still trigger the change event.
You will have to do as you say and compare old value with new value.
There is Application.undo but I wouldn't try to use it, especially in cases where the user has changed more than one cell at once, for example by pasting multiple cells, or by editing multiple cells at once by entering data into multiple cells using Ctrl+Enter.
There is user training too: if the user goes into editing a cell and decides they don't, after all, want to change it, get them to Esc from the cell, not press Enter.