Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have written below code which will create a csv file and store the dates for a month specified. The problem is i want the date format in mm/dd/yyyy but i am getting the date as 6/21/2013 instead of 06/21/2013. Can you please let me know how i can achieve this. Below is my code. Let me know where i am going wrong:
VB
cMonth = Month(Now)
cYear = Year(Now)
cDays = Days(cMonth, cYear)
rowCount = ws.UsedRange.Rows.Count
Set newwkbk = Workbooks.Add
k = 0
For i = 6 To (rowCount - 4) Step 1
    emp_cd = ws.Cells(i, 1).Value
    shift_cd = ws.Cells(i, 2).Value
    dateValue = ws.Cells(i, 3).Value
    If dateValue <> "" Then
        tempArray = Split(dateValue, "to")
        For j = tempArray(0) To tempArray(1) Step 1
        If j <= cDays Then
            dtmNewDate = DateSerial(cYear, cMonth, j)
            intDay = weekDay(dtmNewDate)
            If (intDay <> 7 And intDay <> 1) Then
                k = k + 1
                With newwkbk.Worksheets(1)
                    .Cells(k, 1).Value = emp_cd
                    .Cells(k, 3).Value = shift_cd
                    dateFormatted1 = j & "/" & cMonth & "/" & cYear
                     dateFormatted = Format(dateFormatted1, "dd-mm-yyyy")
                     .Cells(k, 2).Value = dateFormatted
                End With
            End If
        End If
        Next j
    End If
Next i


Thanks
Posted
Comments
CHill60 21-Jun-13 15:05pm    
When you say you are getting the date in the wrong format is that in the CSV file when viewed in something like notepad, or in .Cells(k, 2).Value ?
archies_gall 21-Jun-13 22:46pm    
when viewed in notepad

1 solution

Replace
VB
dateFormatted1 = j & "/" & cMonth & "/" & cYear
dateFormatted = Format(dateFormatted1, "dd-mm-yyyy")
.Cells(k, 2).Value = dateFormatted

With
VB
.Cells(k, 2).NumberFormat = "mm/dd/yyyy" ' Change to dd/mm/yyyy if you prefer day first format
.Cells(k, 2).Value = CDate(cyear & "-" & cmonth & "-" & j) ' yyyy-mm-dd ISO format eliminates ambiguity of month first vs. day first formats


Tested on Excel 2010

By default, Excel formats a date value as m/d/yyyy. By setting the NumberFormat property, we tell Excel to use the format specified rather than the default format.
 
Share this answer
 
v5
Comments
archies_gall 21-Jun-13 22:48pm    
Thanks Mike for the quick solution. It worked

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900