Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current Year Using VBA [closed]

Tags:

excel

vba

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

like image 730
sharkantipav Avatar asked Nov 02 '25 17:11

sharkantipav


2 Answers

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

like image 164
SQLMason Avatar answered Nov 05 '25 11:11

SQLMason


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.

like image 26
Brad Avatar answered Nov 05 '25 09:11

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!