Excel VBA:运行时错误“13”:由于无法识别的日期格式而导致类型不匹配

时间:2021-07-30 09:19:15

标签: excel vba

我正在使用一个非常简单的 VBA 代码来识别日期之间的时间段,但是当我运行宏时,Excel 似乎没有将单元格识别为日期并生成类型不匹配错误,请您帮忙解决这个问题吗?非常感谢。

date cells

Sub datesexcelvba()

Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long

Dim x As Long
lastrow = Sheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For x = 8 To lastrow

mydate1 = Cells(x, 10).Value
mydate2 = mydate1

Cells(x, 25).Value = mydate2

datetoday1 = Date
datetoday2 = datetoday1

Cells(x, 20).Value = datetoday2

If mydate2 - datetoday2 = 3 Then
    
    Cells(x, 29) = "yes"
    Cells(x, 29).Interior.ColorIndex = 3
    Cells(x, 29).Font.ColorIndex = 2
    Cells(x, 29).Font.Bold = True
    Cells(x, 30).Value = mydate2 - datetoday2
End If
Next
 
End Sub

1 个答案:

答案 0 :(得分:0)

粘贴评论作为答案,因为我认为它应该可以解决您将字符串转换为日期的问题。


您可以在 VBA 中使用函数 Split() 来利用字符串的每一部分,因为它有三 (3) 部分:年、月和日。

以下代码更改 Cells(1,1) 中的日期字符串并在 Cells(1,2) 中输出序列日期:

Option Explicit

Sub convertDateStringToDateSerial()
    With Sheets(1)
        Dim dateString As String
        dateString = .Cells(1, 1).Value
        'can add an if-statement to check for "/" presence, if needed
        Dim dateArray As Variant
        dateArray = Split(dateString, "/")
        Dim dateYear As Long
        dateYear = dateArray(2)
        Dim dateMonth As Long
        dateMonth = dateArray(0)
        Dim dateDay As Long
        dateDay = dateArray(1)
        .Cells(1, 2).Value = DateSerial(dateYear, dateMonth, dateDay)
    End With
End Sub

输入输出分别为: enter image description here