[英]How do I set an Excel cell to the current date using VBA?
每当有人在工作表中的其他单元格中进行更改时,尝试将excel单元格设置为当前日期时,我都会遇到错误。
这是代码:
Dim EditDate As Date
RowNum = ActiveCell.Row
ColNum = ActiveCell.Column
If ColNum = 11 Or ColNum = 13 Or ColNum = 19 Or ColNum = 20 Or ColNum = 21 Or ColNum = 22 _
Or ColNum = 23 Or ColNum = 24 Then
Application.EnableEvents = False
EditDate = Date()
ActiveWorksheet.Range("Y," & RowNum).Value = EditDate
Application.EnableEvents = True
End If
每当我尝试在其中一个单元格中进行更改时,我都会收到一个对象必需的错误。 我该如何做?
我认为您的问题不是将RowNum
或ColNum
声明为任何东西。 您希望它们都是某种数字type
(在此示例中,我使用Long
)。
就像PatricK所说的那样, ActiveWorksheet
应该是ActiveSheet
。 您还遇到了其他一些语法错误,但是请看一下我想要的工作版本的代码。
我不知道您是否输入了这段代码。 我会将代码作为Change Event
托管在Worksheet
对象中。
工作代码:
Sub Worksheet_Change(ByVal Target As Range)
Dim EditDate As Date
Dim RowNum As Long
Dim ColNum As Long
RowNum = ActiveCell.Row
ColNum = ActiveCell.Column
If ColNum = 11 Or ColNum = 13 Or ColNum = 19 Or ColNum = 20 Or ColNum = 21 Or ColNum = 22 _
Or ColNum = 23 Or ColNum = 24 Then
Application.EnableEvents = False
EditDate = Format(Now(), "d/m/yyyy hh:mm")
ActiveSheet.Range("Y" & RowNum).Value = EditDate
Application.EnableEvents = True
End If
End Sub
您应该使用ActiveSheet.Range("Y," & RowNum).Value = EditDate
,而不是ActiveWorksheet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.