我找到的原始代码(Excel VBA)可以很好地跟踪一列:
Private Sub Worksheet_Change(ByVal Target As Range)
'Update 20140722
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("P:P"), Target)
xOffsetColumn = 2
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each Rng In WorkRng
If Not VBA.IsEmpty(Rng.Value) Then
Rng.Offset(0, xOffsetColumn).Value = Date
Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy"
Else
Rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub
我想跟踪两列。下面,您将找到新添加的代码。即使我在Dim之后更改了变量名(通过添加b),它也不起作用。简单地复制粘贴旧代码,然后只将范围从P:P更改为S:S,xOffsetColumn也不起作用。
Private Sub Worksheet_Change_b(ByVal Target As Range)
'Update 20140722
Dim WorkRngb As Range
Dim Rngb As Range
Dim xOffsetColumnb As Integer
Set WorkRngb = Intersect(Application.ActiveSheet.Range("S:S"), Target)
xOffsetColumnb = 3
If Not WorkRngb Is Nothing Then
Application.EnableEvents = False
For Each Rngb In WorkRngb
If Not VBA.IsEmpty(Rngb.Value) Then
Rngb.Offset(0, xOffsetColumnb).Value = Date
Rngb.Offset(0, xOffsetColumnb).NumberFormat = "dd-mm-yyyy"
Else
Rngb.Offset(0, xOffsetColumnb).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub
答案 0 :(得分:2)
对原始Worksheet_Change事件宏的此修改应该处理这两个列,包括将多个值粘贴到包含一列或两列的范围内。
Private Sub Worksheet_Change(ByVal Target As Range)
'Update 20150930
If Not Intersect(Target, Union(Columns("P"), Columns("S"))) Is Nothing Then
On Error GoTo bm_Safe_Exit
Application.EnableEvents = False
Dim rng As Range
For Each rng In Intersect(Target, Union(Columns("P"), Columns("S")))
If Not VBA.IsEmpty(rng) Then
rng.Offset(0, 2 - CBool(rng.Column = 19)) = Date
rng.Offset(0, 2 - CBool(rng.Column = 19)).NumberFormat = "dd-mm-yyyy"
Else
rng.Offset(0, 2 - CBool(rng.Column = 19)).ClearContents
End If
Next rng
End If
bm_Safe_Exit:
Application.EnableEvents = True
End Sub
为了简单地说明偏移量,我只是简单地处理了从P列到N列的两列。我不确定为什么第二个事件宏样本只会移回到P列;我不认为您打算覆盖P列中的值。
Application.ActiveSheet.Range("P:P")
列引用是不必要的,如果事件宏由更改其中一个值的代码触发而另一个工作表保持ActiveSheet property,则可能存在危险。工作表代码页默认是私有的;模块代码页默认是公共的。您可以引用单元格和范围,而无需在工作表代码表中明确声明其父级,而这在模块代码表中是错误的编码实践。
我还将用于时间戳的值从Date
更改为Now
。单元格格式仍然只显示日期,但如果您需要它,您也将有时间。