VBA to Convert Date to String?

BAlGaInTl

Well-known Member
Joined
May 7, 2003
Messages
1,082
Hey all...

I want to prefix a filename in my macro with the date in the format.

yyyymmdd

To do this, I want to create a string (sDate) that will go on to be used with the GetSaveAsFilename function.

I've tried setting a string equal to the date function, but of course I get forward slashes in the string and that won't do. I also tried using the Year, Month, and Day functions applied to Date as well, but for example in January, I get 1 as the month and not 01.

What am I missing?
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK
If you want a formula to do it:
=TEXT(D5,"yyyymmdd")
will work.

If you want VBA , write back.

MIchael
 
Upvote 0
You can use daniels012's construction in a macro as follows:

Sub mydate()
Dim sDate As String
sDate = Application.WorksheetFunction.Text(Cells(1, 1), "yyyymmdd")
MsgBox sDate
End Sub

This assumes the date is in A1
 
Upvote 0
No need to call a worksheet function, assuming date in A1:

Code:
Sub mydate()
Dim sDate As String
sDate = Format(Range("A1"), "yyyymmdd")
MsgBox sDate
End Sub
 
Upvote 0
No need to call a worksheet function, assuming date in A1:

Code:
Sub mydate()
Dim sDate As String
sDate = Format(Range("A1"), "yyyymmdd")
MsgBox sDate
End Sub

Thanks...

I modified it slightly to this:

Code:
Sub mydate()
Dim sDate As String
sDate = Format(Date, "yyyymmdd")
MsgBox sDate
End Sub

It seems to be working.
 
Upvote 0

Forum statistics

Threads
1,221,490
Messages
6,160,133
Members
451,622
Latest member
xmrwnx89

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top