Search code examples
excelvbadatedate-format

How do I validate a YYYYMMDD string is a date in Excel VBA?


The date is supplied as a string in the form: 20180503

The function is supposed to validate that the entry is:

  1. in the form YYYYMMDD
  2. a valid date

The following code does not do the trick:

Function formatDateYYYYMMDD(dateStr As String, dateFormat As String) As String
    Dim strToDate As Date
    strToDate = CDate(dateStr)
     If IsDate(strToDate) Then
        formatDateYYYYMMDD= format(dateStr, dateFormat)
     Else
        formatDateYYYYMMDD= "Not a date"
     End If
End Function

Solution

  • Perhaps:

    edit: original UDF changed as it would not flag certain invalid format dates.

    Option Explicit
    Function formatDateYYYYMMDD(dateStr As String, dateformat As String) As String
        Dim strToDate As Date
    On Error GoTo invalidDate
    If Len(dateStr) = 8 And _
        Left(dateStr, 4) > 1900 And _
        Mid(dateStr, 5, 2) <= 12 And _
        Right(dateStr, 2) <= 31 Then
            formatDateYYYYMMDD = Format(CDate(Format(dateStr, "0000-00-00")), dateformat)
        Exit Function
    End If
    invalidDate: formatDateYYYYMMDD = "Not a date"
    End Function
    

    The On Error will pick up invalid dates that otherwise meet the format criteria: eg Sep 31, Feb 30