编辑- 将 row = ActiveCell.row 更改为 row = Target.row (如果您不再在同一行上,则允许)
像这样的东西应该工作。显然,如果您只想在某些字段发生更改时进行更新等,您可能需要考虑添加一些错误处理和进一步验证,但这肯定涵盖了基础知识:
Private Sub Worksheet_Change(ByVal Target As Range)
' declare constants and variables
Const owner_col As String = "I"
Const date_col As String = "J"
Dim row As Double
Dim owner_addr As Range
Dim date_addr As Range
' initialise
row = Target.row
Set owner_addr = Range(owner_col & row)
Set date_addr = Range(date_col & row)
' check that the update is not to the fields you want to update to avoid infinite loop
If Target.Address <> owner_addr.Address And Target.Address <> date_addr.Address Then
' set values
owner_addr.Value = Environ("username")
date_addr.Value = Now()
End If
' free up the memory
Set owner_addr = Nothing
Set date_addr = Nothing
End Sub
这需要添加到您希望在其中跟踪更改的工作表(即不是模块或整个工作簿)。如果您有任何问题,请告诉我。
Environ("username") 从 Windows 环境变量中获取用户名。