简体   繁体   English

将日期格式化为单元格中的yyyy-mm-dd

[英]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: 在[excel-vba]中,我尝试从UserForm文本框格式化文本,将其格式化为yyyy-mm-dd并使用以下代码将其输入到单元格中:

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. 单元格中的输出以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. 我试过yyyy - mm - dd例如,它工作,但每次我尝试上面代码中列出的格式,它没有。

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. 最好保留该真实日期值并更改单元格的Range.NumberFormat属性以按您希望的方式显示日期。

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. 或者, Range.Value属性设置为text-that-like-a-date 之前 ,将单元格的Range.NumberFormat属性设置为Text而不是General。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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