1

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

日期单元格

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
4

1 回答 1

0

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


您可以使用Split()VBA 中的函数来利用字符串的每个部分,知道它包含三 (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

输入和输出是: 在此处输入图像描述

于 2021-07-30T15:37:07.170 回答