简体   繁体   中英

Find cell based on Date in Excel VBA

I have a file with a few columns including one with dates and another with some integers.

I want to obtain the row number of a cell based on its date. So in column B, I want the row number of the cell containing the date 31st of December 2018. The display format in the workbook is "31-Dec-2018" and when clicking on the cell it shows 12/31/2018. I tried using

ActiveSheet.Range("B3:B500").Find(What:=CDate("Dec. 31, 2018")).Activate

and

ActiveSheet.Range("B3:B500").Find(What:=12/31/2016).Activate

But neither works as I get an error "Object Variable not set"). I have been googling a lot and couldn't find a suitable solution which activates the relevant cell. What's wrong with my approach?

This appears to work:

Sub dural2()
    Dim lDate As Date, r As Range
    lDate = DateSerial(2018, 12, 31)
    Set r = ActiveSheet.Range("B3:B500").Find(What:=lDate)
    r.Select
End Sub

在此处输入图片说明

Simply verify that the data in column B are real Excel dates rather than text values that resemble dates.
Creating the range using FIND() will permit you to test it before you attempt to Select it and trap any errors yourself.

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