How to get current Year Using VBA [closed]

2019-08-02 19:20发布

Hi I am using this past thread How To Get The Current Year Using Vba

The answer was to use Year(Date) so I implemented it like this:

Dim a As Integer
a = Year(Date)

But when I tried to use it, I am getting an error

Runtime 13 : Type Mismatch

标签: excel vba
2条回答
对你真心纯属浪费
2楼-- · 2019-08-02 20:17

In Excel VBA, you want to use DATEPART. Assuming that the data that you're trying to get the year from is valid (which is hard to know from the little information in your question).

From here:

MS EXCEL: DATEPART FUNCTION (VBA)

Learn how to use the Excel DATEPART function with syntax and examples.

DESCRIPTION

The Microsoft Excel DATEPART function returns a specified part of a given date.

SYNTAX

The syntax for the Microsoft Excel DATEPART function is:

DatePart( interval, date, [firstdayofweek], [firstweekofyear] )

and this specific example:

DatePart("yyyy", "15/10/2012") would return 2012

查看更多
对你真心纯属浪费
3楼-- · 2019-08-02 20:20

I suspect your type mismatch is somewhere else because Year(Date) is valid. The other option is to use Year(Now)

I suspect you have declared the variable you are trying to assign to as something weird because VBA will make a lot of bizarre casts for you

Dim a As String
a = Year(Now)   ' "2014"

Dim b As Double
b = Year(Now)   '2014

Dim c As Integer
c = Year(Now)   '2014

Dim d As Date
d = Year(Date)  '#7/6/1905#

Dim e
e = Year(Now)   ' 2014 (implicitly cast to integer)

Be sure that you have Option Explicit set at the top of your module and you compile the code.

查看更多
登录 后发表回答