VBA不匹配计算天数

时间:2018-04-10 12:57:37

标签: excel vba excel-vba

在我的Excel电子表格中,我的代码已经工作了大约2个月。现在我运行代码时出现Mismatch 13类错误。代码中没有任何变化。我的日期在J和K列,起始单元格是#3,前两个是标题。列L为空白,日期等于8,单元格将颜色更改为绿色,并添加文本"电子邮件"也将文字颜色改为白色。其他单元格以数值显示日期,我将它们设为非活动状态,因为我只使用它们来证明公式。谢谢你的帮助

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

Dim x As Long

Lastrow = Sheets("TWO_List").Cells(Rows.Count, 1).End(xlUp).Row
For x = 3 To Lastrow 'Starting row

mydate1 = Cells(x, 11).Value ' TWO Required Completion Date
mydate2 = mydate1           'selects value to mydate2
'Cells(x, 41).Value = mydate2 'displays expire date

datetoday1 = Date               'sets date
datetoday2 = datetoday1         'selects todays date in datetoday2
'Cells(x, 42).Value = datetoday2 'display todays date

If mydate2 - datetoday2 = 8 Then 'Number of days email sent before TWO expired

    Cells(x, 12) = "Emailed" 'places Yes in Reminder cells
    Cells(x, 12).Interior.ColorIndex = 10 'Color format
    Cells(x, 12).Font.ColorIndex = 2 'text color
    Cells(x, 12).Font.Bold = True 'Changes to bold text

1 个答案:

答案 0 :(得分:1)

Dim Lastrow As Long不是String,日期应声明为Date类型。

这样的工作:

Option Explicit

Sub TestMe()

    Dim mydate1 As Date
    Dim mydate2 As Date
    Dim datetoday1 As Date
    Dim datetoday2 As Long
    Dim Lastrow As String    
    Dim x As Long

    Lastrow = Cells(Rows.Count, 1).End(xlUp).Row

    For x = 3 To Lastrow    
        mydate1 = Cells(x, 1).Value
        mydate2 = mydate1
        datetoday1 = Date
        datetoday2 = datetoday1

        If DateDiff("d", mydate2, datetoday2) = 8 Then
            Cells(x, 2) = "Emailed"
            Cells(x, 2).Interior.ColorIndex = 10
            Cells(x, 2).Font.ColorIndex = 2
            Cells(x, 2).Font.Bold = True
        End If
    Next x

End Sub