PlayHardGoPro
PlayHardGoPro

Reputation: 2932

Error Type mismatch

Why am I getting this Type Mismatch error?

Code:

Dim data as Date

    data = CDate(Format(31, "00") & "/" & Format("1/9/2013", "mm/yyyy"))

When I try this with strings of course it works perfect.

Obs: It works if I use a different day than 31 like 28 for exemple... But Why this error occurs only with the day 31.

Upvotes: 1

Views: 708

Answers (3)

George Mastros
George Mastros

Reputation: 24506

It looks like you are trying to get the last day of the month. If that is the case, try this...

Dim data As Date
Dim OriginalDate As Date

OriginalDate = DateSerial(2013, 12, 20)

data = DateSerial(Year(OriginalDate), Month(OriginalDate) + 1, 0)

This code basically gets the first day of the next month and then subtracts one day. The nice thing about using the DateSerial function is that you can give it "invalid" values, For example, if you use Year = 2013 and Month = 13, you will get January 2014.

Upvotes: 3

George
George

Reputation: 2213

You have to watch out for dates because depending on what region your computer is in (Control Panel / Region and Language) sometimes your date of Format("1/9/2013", "mm/yyyy")) can be interpreted as September 1, 2013 or as January 9, 2013

If you can, use DateSerial to specifically hook in the month/day numbers without relying on the format output.

Upvotes: 2

PlayHardGoPro
PlayHardGoPro

Reputation: 2932

I found the answer, and it's stupid -.-" Month 9 = Agost = 30 days and not 31... I feel so stupid now ;x

Upvotes: 2

Related Questions