Domanda

I have the following code:

minDate = CDate(Table.Cell(i, 4).Range.Text)

But I get a "Type mismatch error". Table.Cell(i, 4) is in a "dd.mm.yy" format.

È stato utile?

Soluzione

I wrote a macro to test this and the date format dd.mm.yyyy is invalid, it seems you must use dd/mm/yyyy (using slashes instead of period) or dd-mm-yyyy (using hyphens instead of periods):

Sub Macro1()

    Dim minDate As Date
    Dim DateStr As String

    ' with slashes, ok
    DateStr = "27/12/2013"
    minDate = CDate(DateStr)

    ' replace periods w/ slashes, ok
    DateStr = "27.12.2013"
    minDate = CDate(Replace(DateStr, ".", "/"))

    ' replace periods w/ hyphens, ok
    DateStr = "27.12.2013"
    minDate = CDate(Replace(DateStr, ".", "-"))

    ' type mismatch
    DateStr = "27.12.2013"
    minDate = CDate(DateStr)

End Sub

So, to solve your problem, you just need to replace all periods in your date to either hyphen or slash:

minDate = CDate(Replace(Table.Cell(i, 4).Range.Text, ".", "/"))

Altri suggerimenti

Try

minDate = CDate(Table.Cell(i, 4))

The date conversion performance depends on the date format settings in Region and Language.
The following function ensures a successful conversion:

Function TextToDate(vstrText) As Variant
' Description: Convert Text Date to Date
'--
    Dim d As Variant
    Dim sDate As String
    sDate = Replace(vstrText, ".", "-")
    If Right(sDate, 1) = "-" Then
        sDate = Left(sDate, Len(sDate) - 1)
    End If
    If IsDate(sDate) Then
        d = CDate(sDate)
    Else
        d = ""
    End If
    TextToDate = d
End Function
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top