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])