简体   繁体   中英

Excel - date - vba textbox to table

I have below vba for userform text box that sets todays date. Now when the data is entered into the table in my product listing sheet the date is reformatted.

Private Sub UserForm_Initialize()
txt_date.Value = Format(Date, "d/m/yyyy")
End Sub

So when the data is added into the sheet it makes it m/d/yyyy.

The data type used in your VBA + the way you write back to your sheet will influence how Excel will interpret your data. Have a look at beyond examples:

Sub TestDate()
    Dim datestr As String, dateDate As Date
    
    datestr = "11/05/2021"
    dateDate = "11/05/2021"
    
    Sheet1.Range("A1").Value = CDate(datestr)
    Sheet1.Range("C1").Value = dateDate
    
    Sheet1.Range("A2").Value2 = CDate(datestr)
    Sheet1.Range("C2").Value2 = dateDate
End Sub

By using "value2" you see how the raw data of a var defined as "date" type is send back to Excel. imho this is the best way, but you'll have to set the correct format directly in your Excel sheet (select column > Format Cell > Date => choose the format you want (you could set this in vba as well but I don't think it's needed here).

best of luck,

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