excelvbabyval

How do I execute instructions only if the cell value change?


I have a ByVal code to clear the contents of a specific range inside a table, it works. But I need to add a condition for the instructions execute if the RANGE VALUE (content) change, not if I only place the cursor on it.

Also, someone knows how to reference a table column in VBA? Now I'm using an estimated range "C1:C999" but I'll like to use his name "A_[OPERATION]".

This is the code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

   If Not Application.Intersect(Range("C1:C999"), Range(Target.Address)) Is Nothing Then
    
       Range(Selection, Selection.End(xlToRight)).ClearContents

   End If

End Sub

Solution

  • A Worksheet Change

    The code

    Option Explicit
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        
        Const ProcName As String = "Worksheet_Change"
        On Error GoTo clearError
        
        Const tName As String = "A_"
        Const hName As String = "OPERATION"
        
        Dim rng As Range
        Set rng = Range(tName & "[" & hName & "]")
        Set rng = Intersect(rng, Target)
        If rng Is Nothing Then GoTo ProcExit
        
        Application.EnableEvents = False
        
        With ListObjects(tName).HeaderRowRange
            Dim LastColumn As Long
            LastColumn = .Columns(.Columns.Count).Column
        End With
        Dim cel As Range
        For Each rng In rng.Areas
            For Each cel In rng.Cells
                With cel.Offset(, 1)
                    .Resize(, LastColumn - .Column + 1).ClearContents
                End With
            Next cel
        Next rng
    
    CleanExit:
        Application.EnableEvents = True
        GoTo ProcExit
    
    clearError:
        Debug.Print "'" & ProcName & "': " & vbLf _
                  & "    " & "Run-time error '" & Err.Number & "':" & vbLf _
                  & "        " & Err.Description
        On Error GoTo 0
        GoTo CleanExit
    
    ProcExit:
    
    End Sub