I have a code to log usage in an excel sheet, but I get one bug, and one issue

后端 未结 2 997
小鲜肉
小鲜肉 2021-01-26 19:02

This is a universal log system, that a few people here and myself have created. I\'m rather proud of it... I am running into two issues... if someone can help with the sollution

2条回答
  •  情话喂你
    2021-01-26 19:32

    Matt

    Few Things

    1. On Error Resume Next is not proper handling. It should be avoided unless and until it is absolutely necessary.
    2. When you are working with Worksheet_Change event, it is better to switch off events and then turn them back on at the end to avoid possible endless loop.
    3. If you are switching events off then it is a must that you use proper error handling.
    4. Since you are storing the just a single cell in the PreviousValue so I am assuming that you do not want the code to run when the user selects multiple cells?

    I think this is what you are trying (UNTESTED)?

    Option Explicit
    
    Dim PreviousValue
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim sLogFileName As String, nFileNum As Long, sLogMessage As String
        Dim NewVal
    
        On Error GoTo Whoa
    
        Application.EnableEvents = False
    
        sLogFileName = ThisWorkbook.Path & Application.PathSeparator & "Log.txt"
    
        If Not Target.Cells.Count > 1 Then
            If Target.Value <> PreviousValue Then
                If Len(Trim(Target.Value)) = 0 Then _
                NewVal = "Blank" Else NewVal = Target.Value
    
                sLogMessage = Now & Application.UserName & _
                " changed cell " & Target.Address & " from " & _
                PreviousValue & " to " & NewVal
    
                nFileNum = FreeFile
                Open sLogFileName For Append As #nFileNum
                Print #nFileNum, sLogMessage
                Close #nFileNum
            End If
        End If
    LetsContinue:
        Application.EnableEvents = True
        Exit Sub
    Whoa:
        MsgBox Err.Description
        Resume LetsContinue
    End Sub
    
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        PreviousValue = Target(1).Value
    End Sub
    

提交回复
热议问题