excelvbaevents

How to Create the event before cell change with cancel in Excel. For the active cell


vba -excel

Is there a better solution for this event that I described?

Dim bitExit As Boolean

Private Sub Worksheet_Change(ByVal Target As Range)
    If bitExit Then
        Application.Undo
        bitExit = False
        Exit Sub
    End If
    Dim Cancel As Boolean
    Cancel = BeforeCellChange(Target)
    If Cancel Then
        bitExit = True
        Target = ""
    End If
End Sub

Private Function BeforeCellChange(ByVal Target As Range) As Boolean
    BeforeCellChange = True
End Function

Solution

  • how about this:

    methods:

    Offset for restoring active cell's position

    EnableEvents for resetting target cell's value

    Dim bitExit As Boolean
    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim c As Range
        Set c = ActiveCell
        If bitExit Then
            'ActiveCell.Offset(-1).Select
            c.Offset(Target.Row - c.Row, Target.Column - c.Column).Select
            bitExit = False
            Exit Sub
        End If
        Dim Cancel As Boolean
        Cancel = BeforeCellChange(Target)
        If Cancel Then
            bitExit = True
            Application.EnableEvents = False
            Target = ""
            c.Offset(Target.Row - c.Row, Target.Column - c.Column).Select
            Application.EnableEvents = True
        End If
    End Sub
    Private Function BeforeCellChange(ByVal Target As Range) As Boolean
        rem set your rule
        If Target.Value <> "w" Then BeforeCellChange = True
    End Function