每次在特定工作表中更改单元格时,我都会在日志表中创建一个创建日志的宏。
那个宏工作得非常好但不幸的是有点太好!!因为每次我删除一行或一列时,它都会记录该行或列中已被删除的每个单元格!! (那是很多细胞!所以电子表格只是摔倒了)
有没有办法让我的宏只记录一行已被删除(而不是该行中的每个单元格?如果没有...我可以让它忽略创建日志文件,如果行或列是删除?
或者我可以将代码限制在特定范围内。例如。如果我删除一行,它只会记录已删除的单元格A13:BC13
我到目前为止使用的代码如下:
Const intUsernameColumn = 1
Const intCellRefColumn = 2
Const intNewValueColumn = 3
Const intTimestampColumn = 4
Private Sub Worksheet_Change(ByVal Target As Range)
Dim shtLog As Worksheet
Dim cll As Variant
Dim lngNextRow As Long
Set shtLog = ThisWorkbook.Sheets("Log")
For Each cll In Target.Cells
lngNextRow = shtLog.Cells.Find(What:="*", After:=[A1], Searchorder:=xlByRows, _
SearchDirection:=xlPrevious).Row + 1
shtLog.Cells(lngNextRow, intUsernameColumn).Value = Environ("username")
shtLog.Cells(lngNextRow, intCellRefColumn).Value = cll.Address
shtLog.Cells(lngNextRow, intNewValueColumn).Value = cll.Value
shtLog.Cells(lngNextRow, intTimestampColumn).Value = Format(Now, "dd-mmm-yy hh:mm:ss")
Next cll
End Sub
我仍然相当新,所以任何帮助都会受到赞赏
谢谢!
答案 0 :(得分:0)
这不是使用For
循环 - 它只是确定是否更新了多个单元格
如果已删除或粘贴行或列
Option Explicit
Private Const USR_COL = 1
Private Const REF_COL = 2
Private Const VAL_COL = 3
Private Const DT_COL = 4
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wsLog As Worksheet, nextRow As Long, ref As String
Set wsLog = ThisWorkbook.Worksheets("Log")
Application.EnableEvents = False
If IsError(Target.Cells(1)) Then Target.Cells(1) = "Error"
With Target
ref = .Address(False, False)
If .CountLarge > 1 Then ref = "Rows: " & .Rows.Count & ", Columns: " & .Columns.Count
End With
With wsLog
nextRow = .Cells(.Rows.Count, USR_COL).End(xlUp).Row + 1
.Cells(nextRow, USR_COL) = Environ("username")
.Cells(nextRow, REF_COL) = ref
.Cells(nextRow, VAL_COL) = "Val: """ & Target.Cells(1) & """"
.Cells(nextRow, DT_COL) = Format(Now, "dd-mmm-yy hh:mm:ss")
End With
Application.EnableEvents = True
End Sub
如果对一个单元格进行了更改,则会显示
UserName K9 Val: "5" 01-May-18 09:31:59
否则
UserName Rows: 1, Columns: 2 Val: "10" 01-May-18 09:31:59
UserName Rows: 3, Columns: 1 Val: "Error" 01-May-18 09:31:59