简体   繁体   中英

vba - change value of cell based on number format

I have a bunch of dates that I need to upload into mySQL, and their values need to be in the YYYY-MM-DD format. The dates in Excel however have a literal cell value of MM/DD/YYYY . I can use numberFormat to change the way they look , but I don't know how to change the literal value of the cell to YYYY-MM-DD so it will upload correctly into mySQL.

Eg -

Excel's cell value is 11/23/2009

I can use activecell.numberFormat = "YYYY-MM-DD" to change that to 2009-11-23 , but the value in the cell is still 11/23/2009 , so the mySQL upload fails.

How do I do this?

Select the cells you wish to process and run:

Sub FixDate()
    Dim r As Range, v as String

    For Each r In Selection
        With r
            .NumberFormat = "yyyy-mm-dd"
            v = .Text
            .Clear
            .NumberFormat = "@"
            .Value = v
        End With
    Next r
End Sub

Use Activecell.Text instead of Activecell.value

or Format(activecell.value, "yyyy-mm-dd")

Try this link if you dont want to make the change in a macro https://support.office.com/en-ca/article/Format-a-date-the-way-you-want-8e10019e-d5d8-47a1-ba95-db95123d273e

You can create a custom date format and make it default for those cells. Though, I would say Sobigen has a better answer for your purposes.

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