Range.Find not making a difference between January and November (February and December) in VBA Excel

后端 未结 3 698
忘了有多久
忘了有多久 2020-11-29 12:26

Let\'s say that I have the following trivial task:

  • Write the first date of the months from January 2016 to June 2018 on a row
  • Find 01-January-2016 and
相关标签:
3条回答
  • 2020-11-29 13:03

    Whenever .Find(LookAt:=xlPart) is used upon a range of dates, it takes the dates not with their .Value2, but it silently converts them to String following the American date format - MM/DD/YY and looks into this string. The display format of the date in Excel is completely irrelevant, as long as the cell is formatted as a date.

    Thus, every day of January can be found in November and every day of February can be found in December as a substring, making possible 58 (or 59 in a leap year) different mistakes within a calendar year:


    In order to avoid this mistake, the best solution is to look at xlWhole explicitly. If it is not referred, Range.Find() looks for partial string.

    Another issue is where Range.Find starts. According to The Documentation It starts AFTER the supplied or default cell and only looks at the start cell after it cycles back.

    The cell after which you want the search to begin. This corresponds to the position of the active cell when a search is done from the user interface. Notice that After must be a single cell in the range. Remember that the search begins after this cell; the specified cell isn't searched until the method wraps back around to this cell. If you do no specify this argument, the search starts after the cell in the upper-left corner of the range.

    So, by not defining XlWhole and a start cell, the first cell that is searched is B1 not A1, and it finds the date partially before finding the correct date when it cycles around.

    So setting the start cell at the end of the range will do it:

    Set foundRange = Rows(1).Find(DateSerial(2016, 1, 1), [XFD1])
    

    0 讨论(0)
  • 2020-11-29 13:15

    Not sure why it is finding 1 November, but you can fix it by specifying a value for the optional LookAt argument of the Find() method:

    Set foundRange = Rows(1).Find(CDate("01.01.2016"), Lookat:=xlWhole)
    
    0 讨论(0)
  • 2020-11-29 13:20

    I've found CDate to misbehave from time to time. This code appears to convert your date to a string first, not the numeric representation of the date. That conversion happens after you find the string. Since you mentioned it skips the first cell then the first date containing that string is 11/1/16.

    debug.print cdate("01/01/16")
    1/1/16
    
    Set foundRange = Rows(1).Find(CDate(#1/1/2016#))
    Debug.Print foundRange.Value2
    42675
    
    0 讨论(0)
提交回复
热议问题