Excel: Use date-format only on date strings that match a pattern

0

I'm using Excel from Office 365

I have a date column that has three types of date strings:

string # 1: 12/9/2016 0:00  # this string has month, day, year, hours, minutes
string # 2: 201605 # this string has only year (2016) and month (05)
string # 3: 2016 # only has year (2016)

When I try to format the column using this date format: MM/DD/YY, I get

string # 1: 12/09/16 # correct
string # 2: 12/21/51 # clearly incorrect
string # 3: 07/08/05 # also incorrect

Is there any way to apply the date format ONLY to those cells that have a format of "MM/DD/YYYY H:MM" and LEAVE other strings "as is"?

Is this something requiring a macro? Something else?

pdanese

Posted 2018-03-25T16:06:12.040

Reputation: 121

Answers

2

If you have constants (not formulas) in column A, then try this short macro:

Sub INeedADate()
    Dim Kolumn As Long, rng As Range, r As Range
    Dim u As Long
    Kolumn = 1
    Set rng = Columns(Kolumn).Cells.SpecialCells(2)
    For Each r In rng
        u = UBound(Split(r.Text, "/"))
        If u = 2 Then
            r.NumberFormat = "mm/dd/yy"
        End If
    Next r
End Sub

Gary's Student

Posted 2018-03-25T16:06:12.040

Reputation: 15 540