ExcelNewbie
ExcelNewbie

Reputation: 11

Excel VBA - Log changes when old value of a cell is changed manually in Excel

I want to add detailed log with changes to the sheet "Audit" when a cell value is changed in Sheet 1. However no changes should be logged when value is entered in a blank cell. I am working on the below code , but unable to remove blank cell change logs.

Option Explicit


Const LiveWS As String = "Sheet1"
Const AuditWS As String = "Audit"

Private Sub Workbook_Open()

  Dim iRow As Integer
  Dim iCol As Integer
  Dim iLastRow As Long

  For iRow = 9 To 20
    For iCol = 4 To 22
      If Sheets(AuditWS).Cells(iRow, iCol).Value <> Sheets(LiveWS).Cells(iRow, iCol).Value Then
        iLastRow = Sheets(AuditWS).Cells(Rows.Count, 1).End(xlUp).Row
        Sheets(AuditWS).Cells(iLastRow + 1, 1) = "Cell(" & CStr(iRow) & "," & CStr(iCol) & ") " _
          & "changed from '" & Sheets(AuditWS).Cells(iRow, iCol).Value & "' " _
          & "to '" & Sheets(LiveWS).Cells(iRow, iCol).Value & "'"
        Sheets(AuditWS).Cells(iRow, iCol) = Sheets(LiveWS).Cells(iRow, iCol).Value
      End If
    Next iCol
  Next iRow

  iLastRow = Sheets(AuditWS).Cells(Rows.Count, 1).End(xlUp).Row
  Sheets(AuditWS).Cells(iLastRow + 1, 1) = "Workbook opened by " & Environ("USERNAME") _
     & " on " & Format(Now(), "dd/mm/yyyy") & " at " & Format(Now(), "hh:nn:ss")

  ActiveWorkbook.Save

End Sub

Upvotes: 1

Views: 5738

Answers (1)

cyboashu
cyboashu

Reputation: 10433

You sheet events to track changes. behind your sheet1 try something like this

Option Explicit

Public bLog     As Boolean

Private Sub Worksheet_Change(ByVal Target As Range)
    If bLog Then
        ''''' YOUR Logging code here or a call to logging routine
    End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   bLog = Not IsEmpty(Target.Value2)
End Sub

Upvotes: 1

Related Questions