简体   繁体   中英

How do I set an Excel cell to the current date using VBA?

I am running into an error when trying to set an excel cell to the current date whenever somebody makes a change in other cells in the worksheet.

Here is the code:

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

I am getting an object required error every time I try to make a change in one of these cells. How can I make this work??

I think your issue was not declaring RowNum or ColNum as anything. You want those both to be some numeric type (I use Long in this example).

Like PatricK stated, ActiveWorksheet should be ActiveSheet . You also had some other syntax mistakes, but just take a look at my code for a working version of what you want.

I don't know were you put this code. I would host the code in the Worksheet object as a Change Event .

Working Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM