Automating financial models or schedule calculations in Microsoft Excel VBA often halts abruptly at Run-Time Error ’13’: Type mismatch. When executing procedures that compare cell values against calendar dates, calculate day differences via DateDiff(), or parse date strings, this error triggers whenever VBA encounters regional date format inconsistencies (such as DD/MM/YYYY vs MM/DD/YYYY), empty strings, or text-formatted date cells.
Validate Cell Content Using IsDate Before Type Casting
Directly passing cell ranges into CDate() crashes the macro if the user left a blank row or entered invalid text:
' Vulnerable code:
Dim myDate As Date
myDate = CDate(ws.Cells(i, 1).Value)
' Robust defensive syntax:
Dim cellVal As Variant
cellVal = ws.Cells(i, 1).Value
If IsDate(cellVal) Then
myDate = CDate(cellVal)
Else
' Handle blank or text headers cleanly
myDate = DateSerial(1900, 1, 1)
End If
Handle International Date Formats via DateSerial
VBA uses US English date formatting internally regardless of local Windows regional settings. Parsing European slash dates like "05/11/2026" can flip months and days or fail when days exceed 12:
- Split date strings manually to prevent ambiguous regional interpretation:
Dim parts() As String parts = Split(cellVal, "/") ' Assuming DD/MM/YYYY myDate = DateSerial(CInt(parts(2)), CInt(parts(1)), CInt(parts(0))) - Alternatively, store raw serial date numbers in Excel rather than formatted text strings.
Clear Error Cells and #N/A Values
If a referenced cell contains an underlying formula error (such as #VALUE! or #N/A), reading its value triggers Error 13 immediately. Test with If Not IsError(ws.Cells(i, 1).Value) Then before processing.