Let\'s say that I have the following trivial task:
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])
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)
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