Consulting

Results 1 to 3 of 3

Thread: Excel VBA Code help

  1. #1

    Excel VBA Code help

    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.

  2. #2
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    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
    Last edited by SamT; 03-12-2021 at 09:13 PM.
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  3. #3
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,874
    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.
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •