VBA功能:从字符串中提取日期-类型不匹配

时间:2018-10-16 13:05:28

标签: excel excel-vba

我写了一个简单的函数从单元格中提取日期。我有一些单元格包含字符串“ 5-Oct-2018”,而其他单元格包含“ 2018/10/10 Random Texts”。我想截断随机文本,并将其余字符串转换为相同格式的日期。

由于随机文本仅在字符串大于或等于10个字符时才会显示,因此我决定将所有内容都截断到右侧。

我写了以下内容,但是它一直卡在“ FnDateExtract = Format(CDate(RawExtract),“ yyyy / mm / dd”)”这一行,说类型不匹配。我在做什么错了?

Function FnDateExtract(fnFile, fnTab, fnRow, fnColumn) As Date
    Dim RawExtract As String
    With Workbooks(fnFile).Worksheets(fnTab)
        RawExtract = .Cells(fnRow, fnColumn).Text
        If Len(RawExtract) > 10 Then RawExtract = Left(RawExtract, 10)
        FnDateExtract = Format(CDate(RawExtract), "yyyy/mm/dd")
    End With
End Function

2 个答案:

答案 0 :(得分:3)

您的函数看起来不错,只需要进行一些小的更改即可:

Function FnDateExtract(fnFile, fnTab, fnRow, fnColumn) As Date
    Dim RawExtract As String
    With Workbooks(fnFile).Worksheets(fnTab)
        RawExtract = Left(CStr(.Cells(fnRow, fnColumn).Text), 10)
        FnDateExtract = CDate(Format(RawExtract, "yyyy/mm/dd"))
    End With
End Function

CDate()移动到Format()函数外部,以便将返回类型设置为Date

还请注意,您可以通过InStr(*string*, " ") - 1函数使用10代替Left()来获取日期字符串。在某些情况下可能更准确。

答案 1 :(得分:1)

似乎您的数据无法转换为日期。这意味着您必须使代码更健壮。第一个版本可能像这样

Function FnDateExtract(fnFile, fnTab, fnRow, fnColumn) As Date
Dim RawExtract As String
    With Workbooks(fnFile).Worksheets(fnTab)
        RawExtract = .Cells(fnRow, fnColumn).Text
        If Len(RawExtract) > 10 Then RawExtract = Left(RawExtract, 10)

        If IsDate(RawExtract) Then
            FnDateExtract = CDate(Format(RawExtract, "yyyy/mm/dd"))
        Else
            FnDateExtract = vbEmpty
        End If

    End With

End Function

在改进的版本中,可以像这样正确定义参数

Function FnDateExtract(ByVal fnFile As String, ByVal fnTab As String, _
                    ByVal fnRow As Long, ByVal fnColumn As Long) As Date

假设您有一个名为fnFile且工作表为fnTab的工作簿,则该功能仍然很容易被破坏。处理此问题的最简单方法(可能也是快速而肮脏的)是添加错误处理程序。

所以第二个版本看起来像这样

Function FnDateExtract(ByVal fnFile As String, ByVal fnTab As String, _
                    ByVal fnRow As Long, ByVal fnColumn As Long) As Date
Dim RawExtract As String

On Error GoTo EH

    With Workbooks(fnFile).Worksheets(fnTab)
        RawExtract = .Cells(fnRow, fnColumn).Text
        If Len(RawExtract) > 10 Then RawExtract = Left(RawExtract, 10)
        If IsDate(RawExtract) Then
            FnDateExtract = CDate(Format(RawExtract, "yyyy/mm/dd"))
        Else
            FnDateExtract = vbEmpty
        End If
    End With

    Exit Function

EH:
    FnDateExtract = vbEmpty

End Function