I'm trying to produce all the dates between two dates. What I've written so far can produce the dates flawlessly but It kicks out leading zeros from months and days.
I've tried with:
Sub GenerateCustomizedDates()
Dim FirstDate As Date, LastDate As Date, DateIter As Date
FirstDate = "01/01/2012"
LastDate = "01/30/2012"
For DateIter = FirstDate To LastDate
R = R + 1: Cells(R, 2) = Replace(DateIter, "/", "_")
Next DateIter
End Sub
Output I'm having are like:
1_1_2012
1_2_2012
1_3_2012
1_4_2012
Output I wish to have:
01_01_2012
01_02_2012
01_03_2012
01_04_2012
How can I achieve the format of latter output using vba?
Use Range.NumberFormat
to apply the date format (escaping the underscore _
with a backslash \\
). Replace
returns a String
; better to just apply the date formatting directly after writing the values to the sheet.
For DateIter = FirstDate To LastDate
Dim R As Long
R = R + 1: Cells(R, 2) = DateIter
Next DateIter
Range("B1:B" & R).NumberFormat = "mm\_dd\_yyyy"
I personally wouldn't do this, but you could also use Format(DateIter, "mm\\_dd\\_yyyy")
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.