Excel VBA - 在Excel

时间:2015-08-17 20:05:17

标签: excel vba excel-vba

我想在工作表1中更改单元格值时添加详细日志,其中包含对“审核”工作表的更改。但是,如果在空白单元格中输入值,则不应记录任何更改。我正在处理以下代码,但无法删除空白单元格更改日志。

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

1 个答案:

答案 0 :(得分:1)

您可以选择事件来跟踪更改。 在sheet1后面尝试这样的事情

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