Saturday, June 2, 2012

Convert a number to a date using VBA

This VBA procedure converts a number, in yyyymmdd format, to a regular date like mm/dd/yyyy.  For example, a number like 20090427 will get converted to 4/27/2009.





Public Function formatdatefromnumber(dateNumber)
On Error GoTo err_formatdatefromnumber

    Dim fmtYear, fmtMonth, fmtDay As String
        If IsNull(dateNumber) Then
            formatdatefromnumber = vbNullString
            Exit Function
            
        End If
        
        If Len(CStr(dateNumber)) <> 8 Then
            formatdatefromnumber = vbNullString
            Exit Function
        End If
        If Not IsNumeric(dateNumber) Then
            formatdatefromnumber = vbNullString
            Exit Function
        End If
        fmtYear = Mid(dateNumber, 1, 4)
        fmtMonth = Mid(dateNumber, 5, 2)
        
        If CInt(fmtMonth) > 12 Then
        formatdatefromnumber = vbNullString
        Exit Function
        End If
        fmtDay = Mid(dateNumber, 7, 2)
        If CInt(fmtDay) > 31 Then
        formatdatefromnumber = vbNullString
        Exit Function
        End If
        formatdatefromnumber = Format(DateSerial(fmtYear, fmtMonth, fmtDay), "mm/dd/yyyy")
        Exit Function

err_formatdatefromnumber:
MsgBox Err.Number & " " & Err.Description, vbCritical, "DateFromNumber()"
err_formatdatefromnumber = vbNullString
Exit Function
        
End Function

No comments:

Post a Comment