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 color it in red
- Use
Range.Find()
Thus, I create a code, looping from 1 to 30 and writing the first date of each month. Then I use Rows(1).Find(CDate("01.01.2016"))
or Rows(1).Find(DateSerial(2016,1,1))
and I consider my task almost ready.
I run the code and I see this in both Excel 2010 and Excel 2016:
Question:
Is there any reason behind it? Or is the Range.Find()
function documented to act like this?
Public Sub TestMe()
Cells.Clear
Dim cnt As Long
For cnt = 1 To 30
Cells(1, cnt) = DateAdd("M", cnt - 1, DateSerial(2016, 1, 1))
Cells(1, cnt).NumberFormat = "MMM-YY"
Next cnt
Dim foundRange As Range
Set foundRange = Rows(1).Find(CDate("01.01.2016"))
'Set foundRange = Rows(1).Find(DateSerial(2016, 1, 1)) 'the same false result
'Set foundRange = Rows(1).Find("01.01.2016") 'does not find anything
If Not foundRange Is Nothing Then
foundRange.Interior.Color = vbRed
End If
End Sub
In general, the Range.Find()
has an optional After
parameter, which is the first cell of the Range
. In our case, the After
parameter is omitted, thus it is considered to be A1
and it is checked last. If you stop the code after the first loop and you manually delete Nov 16
from Excel, then you continue the code, it will return the cell Jan 16
in red.
As far as November is considered found, it gives it back and it does not go further. The question is more like - in what logic is 1-November-2016 the same as 1-January-2016, even partially?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…