尝试在Excel上获取启用宏的工作表,以便在B或C列中输入任何值时自动填充日期和时间。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
For i = 2 To 100
If Cells(i, "B").Value <> " " And Cells(i, "C").Value = " " Then
Cells(i, "F").Value = Date & " " & Time
Cells(i, "F").NumberFormat = "m/d/yyyy h:mm AM/PM"
End If
Next
Range("F:F").EntireColumn.AutoFit
End Sub
我写的代码有什么问题吗?
发布于 2015-02-18 09:36:42
“目标”将是已更改的单元格。可以一次更改多个单元格(通过ctrl-enter组合键),因此检查Target中的所有单元格并不是一个坏主意。
如果你使用Intersect方法,它将只得到目标的面积和你想要检查重叠的范围。这将遍历这些单元格(如果有),如果找到一个值,就给它们加时间戳。
正如其他人所提到的,在插入戳记之前禁用事件将阻止调用另一个工作表更改事件。在调试时要小心,不要让事件关闭。
您可以在此处阅读有关事件参数的更多信息:https://msdn.microsoft.com/en-us/library/office/ff839775.aspx
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Excel.Range
Dim cll As Excel.Range
Set rng = Excel.Intersect(Target, Range("B:C"))
If Not (rng Is Nothing) Then
Excel.Application.EnableEvents = False
For Each cll In rng.Cells
If Len(cll.Formula) > 0 Then
Cells(cll.Row, 6).Value = Format$(Now, "m/d/yyyy h:mm AM/PM")
End If
Next
Range("F:F").EntireColumn.AutoFit
Excel.Application.EnableEvents = True
End If
End Sub
发布于 2015-02-18 09:58:09
您不希望每次工作表上的任何内容发生更改时都运行所有这些内容;只有在影响时间戳有效性的内容发生更改时才会这样做。通常,我们将使用Intersect
来确定更改的其中一个值是否应该接收新的时间戳。您也不希望例程尝试在自身之上运行,因此建议在更改值之前关闭事件处理(即添加时间戳)。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B:C")) Is Nothing Then
On Error GoTo SafeExit
Application.EnableEvents = False
Dim bc As Range 'no sense in declaring something until we actually need it
For Each bc In Intersect(Target, Range("B:C")) 'deal with every cell that intersects. This is how to handle pastes into more than one cell
If Not IsEmpty(Cells(bc.Row, "B")) And Not IsEmpty(Cells(bc.Row, "C")) Then
Cells(bc.Row, "F").Value = Now 'Now is the equivalent of Date + Time
Cells(bc.Row, "F").NumberFormat = "m/d/yyyy h:mm AM/PM"
End If
Next bc
'Range("F:F").EntireColumn.AutoFit 'this slows things down. you may want to comment this out and just set an apprpriate column width that will handle everything
End If
SafeExit:
Application.EnableEvents = True
End Sub
这就是我对这个老问题的看法。有很多例子。查看此页面右侧下方的相关部分,可以找到其中几个的链接。
发布于 2015-02-18 09:38:23
几个小变化:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Application.EnableEvents = False
If Target.Column = 2 Or Target.Column = 3 Then
For i = 2 To 100
If Cells(i, "B").Value <> " " And Cells(i, "C").Value = " " Then
Cells(i, "F").Value = Date & " " & Time
Cells(i, "F").NumberFormat = "m/d/yyyy h:mm AM/PM"
End If
Next
End If
Range("F:F").EntireColumn.AutoFit
Application.EnableEvents = True
End Sub
关闭even,这样在代码进行修改时就不会触发它,并测试目标列以查看它是B还是C,如果是,则仅触发
此外,您知道您的代码将更新第2行到第100行,而不管哪一行被更改,对吗?如果您只想要已更改的行,则可以使用target.row获得它
https://stackoverflow.com/questions/28574399
复制相似问题