简体   繁体   中英

Formatting date to yyyy-mm-dd in cell

In [excel-vba], I am trying to format the text from a UserForm textbox, format it to yyyy-mm-dd and input it into a cell with the following code:

Private Sub GenerateButton_Click()
    Worksheets("Sheet1").Activate

    Sheet1.Unprotect
    Dim startTime, endTime, startDate
    startTime = t_daylasthour.Text
    endTime = t_daylasthour.Text
    startDate = t_startdate.Value

    Dim counter As Integer
    counter = 1

    Do
        Set field = ActiveWorkbook.Sheets("Sheet1").Cells(counter + 1, 1)
        field.Value = Format(t_startdate.Text, "yyyy-mm-dd") 
        counter = counter + 1
    Loop While counter < 10

End Sub

The output in the cell keeps coming out in the form yyyy/mm/dd. Any other format that I try in my code appears to work. I tried yyyy - mm - dd for example, and it work, but everytime I try the format listed in the code above, it doesn't.

Any ideas on what I'm doing wrong?

The value is coming in as text but the cell's General format is converting it to a true date value. It would be better to keep that true date value and change the cell's Range.NumberFormat property to display the date the way you want.

Do
    Set field = ActiveWorkbook.Sheets("Sheet1").Cells(counter + 1, 1)
    field = CDate(t_startdate.Text) 
    field.NUMBERFORMAT = "yyyy-mm-dd"
    counter = counter + 1
Loop While counter < 10

Alternately, set the cell's Range.NumberFormat property to Text rather than General before setting the Range.Value property to text-that-looks-like-a-date.

Do
    Set field = ActiveWorkbook.Sheets("Sheet1").Cells(counter + 1, 1)
    field.NUMBERFORMAT = "@"
    field.Value = Format(t_startdate.Text, "yyyy-mm-dd") 
    counter = counter + 1
Loop While counter < 10

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM