将工作表名称添加到工作表更改日志

时间:2018-12-17 17:34:41

标签: excel vba spreadsheet

下午好,

我在网上找到了此代码以创建更改日志,并且我想将其应用于多个工作表。如何使其更改更改单元格的工作表的名称?

Private Sub Worksheet_Change(ByVal Target As Range)
Dim strAddress As String
Dim val
Dim dtmTime As Date
Dim Rw As Long

If Intersect(Target, Range("A:Z")) Is Nothing Then Exit Sub
   'change range to suit
dtmTime = Now()
With Target
      val = .Value
       strAddress = .Address
End With

Rw = Sheets("Log").Range("A" & Rows.Count).End(xlUp).Row + 1
With Sheets("Log")
    .Cells(Rw, 1) = strAddress
    .Cells(Rw, 2) = Environ("UserName")
    .Cells(Rw, 3) = dtmTime
    .Cells(Rw, 4) = val

End With
End Sub

1 个答案:

答案 0 :(得分:2)

停止使用多个Worksheet_Change事件子,并在ThisWorkbook私有代码表中切换到单个Workbook_Sheetchange。

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    Select Case LCase(Sh.Name)
        Case "sheet1", "sheet2", "sheet3"
            If Not Intersect(Target, Sh.Range("A:Z")) Is Nothing Then
                On Error GoTo exit_out
                Application.EnableEvents = False
                Dim rw As Long, t As Range
                For Each t In Intersect(Target, Sh.Range("A:Z"))
                    With Worksheets("Log")
                    rw = Worksheets("Log").Range("A" & Rows.Count).End(xlUp).Row + 1
                        .Cells(rw, "A") = t.Address(0, 0)
                        .Cells(rw, "B") = Environ("UserName")
                        .Cells(rw, "C") = Now
                        .Cells(rw, "D") = t.Value
                        .Cells(rw, "E") = Sh.Name
                    End With
                Next t
            End If
        Case "log"
            'do nothing
    End Select

exit_out:
    Application.EnableEvents = True

End Sub