Question

I am just trying to figure out the easiest way to change the date format on a huge spreadsheet but the biggest problem seems to be that the year and month/day are switched around. I need it to be mm/dd/yyyy but currently it is yyyymmdd. Thanks for any help.

Was it helpful?

Solution

Can I change my date format from 20140129 to 01/29/2014 using VBA?

You mean Like this?

Sub Test()
    Dim temp As String
    Dim D As String, M As String, Y As String

    temp = "20140129"

    Y = Left(temp, 4)
    M = Mid(temp, 5, 2)
    D = Right(temp, 2)

    '~~> This will give you 01/29/2014
    Debug.Print Format(DateSerial(Val(Y), Val(M), Val(D)), "mm/dd/yyyy")
End Sub

EDIT

Followup from comments.

Use this code (TRIED AND TESTED). I am assuming that the dates (as string) are stored in Col A from A1 onwards in say Sheet1

Sub Test()
    Dim temp As String
    Dim D As String, M As String, Y As String
    Dim ws As Worksheet
    Dim lRow As Long, i As Long

    '~~> Change this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet2")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            temp = CStr(.Range("A" & i).Value)

            Y = Left(temp, 4)
            M = Mid(temp, 5, 2)
            D = Right(temp, 2)

            .Range("A" & i).NumberFormat = "mm/dd/yyyy"

            '~~> This will give you 01/29/2014
            .Range("A" & i).Formula = Format(DateSerial(Val(Y), Val(M), Val(D)), "mm/dd/yyyy")
        Next i


    End With
End Sub

ScreenShot

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top