A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
This is not a bug in Year(). It looks like it's a type issue.
From your Watch window, CleanDataSheet.Cells(Pstart, 1) and CleanDataSheet.Cells(i + 1, 1) are shown as Variant/String, not as Date. Even though they display as 1/1/2024 and 1/2/2024, they are text values that look like dates.
Month() is more tolerant and will implicitly coerce certain date-looking strings to a date. Year() is stricter on Mac VBA and in some regional settings will throw Run-time error 13 if the string cannot be safely coerced to a Date.
So what is happening is implicit conversion working in one case and failing in the other.
The correct fix is to explicitly convert the value to a Date before calling Year or Month.
Use:
Year(CDate(CleanDataSheet.Cells(Pstart, 1).Value))
and
Year(CDate(CleanDataSheet.Cells(i + 1, 1).Value))
or:
If IsDate(CleanDataSheet.Cells(Pstart, 1).Value) Then
y = Year(CDate(CleanDataSheet.Cells(Pstart, 1).Value))
End If
A likely even better solution would be to ensure the cells contain real dates, not text. You can check this:
Debug.Print TypeName(CleanDataSheet.Cells(Pstart, 1).Value)
If it prints String, they are text. If it prints Date or Double, they are real Excel dates.
To force conversion in the sheet you can use:
CleanDataSheet.Columns(1).TextToColumns Destination:=CleanDataSheet.Range("A1"), DataType:=xlDelimited
or multiply by 1 in a helper column.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin