从Date Excel单元格值中获取年份不起作用

时间:2013-08-13 22:34:08

标签: excel vba datepart

我有以下代码:

For rowIndex = rowOffset To 15
        Dim currentDate As Date
        Dim nextRowDate As Date
        currentDate = Cells(rowOffset, colIndex).Value
        nextRowDate = Cells(rowIndex + 1, colIndex).Value

        Dim currentYear As Date
        currentYear = DatePart("yyyy", currentDate)

        Dim nextYear As Date
        nextYear = DatePart("yyyy", nextRowDate)

        If currentYear <> nextYear Then
            Call RenderYearStyle(rowIndex, colIndex)
        Else
            Call ClearStyle(rowIndex, colIndex)
        End If
    Next rowIndex

日期部分或“年”功能未返回日期的年份部分。有什么想法吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

对您自己的答案进行一次更正 - Year()返回Integer,而不是String。打开立即窗口(Ctrl-G),键入?typename(year(now)),然后按Enter键。 VBE很聪明,它可以在后台将Integer转换为String。

?typename(year(now))
Integer

答案 1 :(得分:0)

Year()函数返回String而不是Date .. DOIIIII。

    Dim currentYear As String
    currentYear = year(currentDate)

    Dim nextYear As String
    nextYear = year(nextRowDate)