这是一个通用日志系统,由这里的几个人和我自己创建。我对此感到相当自豪...我遇到了两个问题...如果有人可以提供解决方案,那就太好了。
这是代码:
Option Explicit
Dim PreviousValue
Private Sub Worksheet_Change(ByVal Target As Range)
Dim sLogFileName As String, nFileNum As Long, sLogMessage As String
sLogFileName = ThisWorkbook.path & Application.PathSeparator & "Log.txt"
On Error Resume Next ' Turn on error handling
If Target.Value <> PreviousValue Then
' Check if we have an error
If Err.Number = 13 Then
PreviousValue = 0
End If
' Turn off error handling
On Error GoTo 0
sLogMessage = Now & Application.UserName & " changed cell " & Target.Address _
& " from " & PreviousValue & " to " & Target.Value
nFileNum = FreeFile ' next file number
Open sLogFileName For Append As #nFileNum ' create the file if it doesn't exist
Print #nFileNum, sLogMessage ' append information
Close #nFileNum ' close the file
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
PreviousValue = Target(1).Value
End Sub
这是两个问题。
8/30/2012 1:45:01 PM Matthew Ridge changed cell $K$3 from Test to
而不是 8/30/2012 1:45:01 PM Matthew Ridge changed cell $K$3 from Test to Blank or Empty
最佳答案
马特
一些事情
On Error Resume Next
处理不当。除非绝对必要,否则应避免使用它。 Worksheet_Change
时事件,最好关闭事件,然后在结束时重新打开,以避免可能的死循环。 PreviousValue
中仅存储一个单元格所以我假设您不希望在用户选择多个单元格时运行代码? 我认为这就是您正在尝试的( 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
关于excel - 我有一个在 Excel 表中记录使用情况的代码,但我遇到了一个错误和一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12203020/