vba - 在单独的日志表中记录对单元格范围的更改的宏
问题描述
我有一个创建日志的宏,每次特定工作表中的单元格发生更改时,都会在日志表中。
那个宏真的很好用,但不幸的是有点太好了!!因为每次我删除一行或一列时,它都会记录该行或列中已删除的每个单元格!(那是很多单元格!所以电子表格就倒塌了)
有没有办法让我的宏只记录已删除的行(而不是该行中的每个单元格?如果没有......如果删除了行或列,我可以让它忽略创建日志文件吗?
或者我可以将代码限制在特定范围内。例如。如果我删除一行,它只会记录单元格 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
我在这方面还是很新的,所以任何帮助都将不胜感激
谢谢!!
解决方案
这不是使用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
推荐阅读
- php - PHP 使用 mysqli_connect 连接到 Google Cloud Sql Instance 数据库
- c# - 如何使用 C# 将在代码中创建的 UIElement 转换为流?
- reactjs - 触发点击事件时如何在amcharts中获取气泡值
- ruby - 重新启动后,RVM 无法在使用 CodeDeploy 的 RHEL EC2 上运行
- reactjs - 子组件不使用 shouldComponentUpdate 重新渲染
- java - 我检查网站是否在线的代码有什么问题?
- php - 错误 - 预期的内容类型 text/json 得到 text/html
- php - 我如何解决upload_max_filesize 问题
- arrays - 如何在 PostgreSQL 中创建具有范围的数组
- javascript - 为什么在 React-Native 中打开 Screen 时总是默认打开 Modal?