1

I'm looking for a way to convert strings to Date data type in VBA. I can use CDate() function for this purpose, but it uses its own implicit algorithm for parsing strings and I would like to specify my own format to differentiate between "DD/MM/YY" and "MM/DD/YY", for example.

Please notice that unlike Visual Basic, VBA has no DateTime.TryParseExact function.

ADD: As some answers suggest, I can write my own parser. If there is no built-in solution, it will be my choice.

4
  • Assuming you mean CVDate() you dont get more options. Commented Aug 24, 2017 at 15:24
  • can you post the format of your strings Commented Aug 24, 2017 at 15:38
  • @braX, Microsoft: CVDate is identical to CDate except for the declared type of its return value. I use CDate to get Date variable. Commented Aug 24, 2017 at 15:42
  • @GowthamShiva Let's say my string is "01/02/2017". I want to tell VBA what it is ("DD/MM/YYYY" or "MM/DD/YYYY") explicitly. Commented Aug 24, 2017 at 15:45

3 Answers 3

2

Do something like this...

strDate = Split(strDate,"/")
newstrDate = strDate(1) & "/" & strDate(0) & "/" & strDate(2)
strDate = CDate(newstrDate)
Sign up to request clarification or add additional context in comments.

Comments

1

In this case I would avoid CDate alltogether and instead split the date string into year, month and day and use DateSerial(year, month, day). This way you have full control.

Comments

0

Can you use the below code

Msgbox Format("24/01/2017","MMM, DD, YYYY")

This will give you output as Jan, 24, 2017 . You can use other format which is easily available when you click on the Format cells. Thanks

2 Comments

Wrong way round. Read the question again.
I suppose that this will first convert "24/01/2017" to Date data type and then format it using "MMM, DD, YYYY". I want to control the first stage so that I can specify that "01/02/2017" is February, 1 and not January, 2 (or other way round).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.