vba 从日期 Excel 单元格值中获取年份不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18220377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:44:32  来源:igfitidea点击:

get year from Date Excel cell value not working

excelvbadatepart

提问by Jimmyt1988

I have the following code:

我有以下代码:

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

Date Part or "Year" functions are not returning the year part of the date. Any ideas?

日期部分或“年”函数不返回日期的年份部分。有任何想法吗?

enter image description here

在此处输入图片说明

回答by PatricK

Just one correction to your own answer - Year()returns Integer, not String. Bring up Immediate window (Ctrl-G) type ?typename(year(now))and press enter. VBE is smart that it convert the Integer to String for you in background.

只需对您自己的答案进行一次更正 -Year()返回整数,而不是字符串。调出立即窗口 (Ctrl-G) 类型?typename(year(now))并按 Enter。VBE 很聪明,它在后台为您将整数转换为字符串。

?typename(year(now))
Integer

回答by Jimmyt1988

the Year() function returns a String not a Date.. DOIIIII.

Year() 函数返回一个字符串而不是日期.. DOIIIII。

    Dim currentYear As String
    currentYear = year(currentDate)

    Dim nextYear As String
    nextYear = year(nextRowDate)