Search code examples
excelvbacopyrangetrace

How to make track-changes column/range specific


I have a table with a number of columns and rows in it and I would like to track the changes made in a specific column. I found the code (see bottom of message) online, and it works perfectly. However, it tracks “all changes”. Is there a way to make it range specific. For example I only want to track the changes made in the column with the red numbers. Please see the example:

enter image description here

The code I found online is the following:

Option Explicit

Dim vOldVal 'Must be at top of module

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim bBold As Boolean
    If Target.Cells.Count > 1 Then Exit Sub
    If ActiveSheet.Name = "Pricing" Then Exit Sub
    'On Error Resume Next
    With Application
         .ScreenUpdating = False
         .EnableEvents = False
    End With
    If IsEmpty(vOldVal) Then vOldVal = "Empty Cell"
    bBold = Target.HasFormula
        With Sheets("Data")
            '.Unprotect Password:="Secret"
                If .Range("A96") = vbNullString Then
                    .Range("A96:H96") = Array("Cell Changed", "Old Value", _
                        "New Value", "Old Formula", "New Formula", "Time of Change")
                End If
            With .Cells(.Rows.Count, 1).End(xlUp)(2, 1)
                  .Value = ActiveSheet.Name & " : " & Target.Address
                  .Offset(0, 1) = vOldVal
            With .Offset(0, 2)
              If bBold = True Then
                .ClearComments
                .AddComment.Text Text:= _
                     "OzGrid.com:" & Chr(10) & "" & Chr(10) & _
                        "Bold values are the results of formulas"
              End If
                .Value = Target
                .Font.Bold = bBold

            End With
                .Offset(0, 3) = Time
                .Offset(0, 4) = Date
                .Offset(0, 5) = Application.UserName
            End With
            .Cells.Columns.AutoFit
            '.Protect Password:="Secret"
        End With
    vOldVal = vbNullString
    With Application
         .ScreenUpdating = True
         .EnableEvents = True
    End With
    On Error GoTo 0
End Sub


Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
        vOldVal = Target
End Sub


Private Sub test()
    Application.EnableEvents = True
End Sub

Please keep in mind that I'm very new to VBA coding.


Solution

  • You can do it by adding a single line to your existing code:

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
        Dim bBold As Boolean
        If Target.Cells.Count > 1 Then Exit Sub
        If ActiveSheet.Name = "Pricing" Then Exit Sub
        If Target.Column <> 4 Then Exit Sub
    

    This will just check to see if it is the 4th column of your sheet that has been changed and will ignore changes elsewhere.