Consulting

Results 1 to 7 of 7

Thread: Solved: Run macro after leaving a cell

  1. #1
    VBAX Regular
    Joined
    Aug 2008
    Posts
    12
    Location

    Unhappy Solved: Run macro after leaving a cell

    Problem: I want a macro to run when I leave a cell. The only thing I've found is EXIT and LostFocus, but it looks like those can only be used on forms. Do you have any suggestions.

  2. #2
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    Use the Worksheet_SelectionChange event. You will need to store a reference to the previous selection in a variable so that you can check it in the code, then update the variable to the current selection.
    Alternatively, if you wanted to run the code when that cell is changed, rather than simply left, you can use the Worksheet_Change event.
    Be as you wish to seem

  3. #3
    VBAX Regular
    Joined
    Aug 2008
    Posts
    12
    Location
    Thank you
    I am not that familiar with targets and such. Can you give me an example. I only want the macro to run when I leave cell "A2" not to specify target cell. I don't want it to run if I change something in another cell. My other option is to link the macro to a button or something.

  4. #4
    Knowledge Base Approver VBAX Guru GTO's Avatar
    Joined
    Sep 2008
    Posts
    3,368
    Location
    Not tested. You'd probably want to add checking what cell is active upon the sheet becoming active after the workbook opens.

    [VBA]Option Explicit

    Dim OldAddress As String
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If OldAddress = Range("A2").Address Then
    MyMacro
    End If
    OldAddress = ActiveCell.Address
    End Sub

    Private Sub MyMacro()
    MsgBox " I just left A2", 0, ""
    End Sub[/VBA]

  5. #5
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    [VBA]Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Static RunMe As Boolean

    If RunMe Then
    Rem do something
    Beep
    End If

    RunMe = (Target.Address = "$A$2")
    End Sub[/VBA]

  6. #6
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    Just to be absolutely sure: you would like the code to run if you select A2, then select A3 without changing A2?
    Be as you wish to seem

  7. #7
    VBAX Regular
    Joined
    Aug 2008
    Posts
    12
    Location
    Absolutly perfect!!
    Thank you

Posting Permissions

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