VBA比较两个日期

时间:2013-10-09 19:35:55

标签: vba datetime compare

我知道这听起来像一个简单的任务,但我一直在尝试各种方法,但仍然没有取得成功。

  1. 我有一个包含许多变量的大数据集,其中有两个是有用的。首先称为“符号”(aaa,bbb,ccc等),其次是“日期”(例如2012-05-15 20:00);一个符号对应多个日期;

  2. 我想删除一些具有特定日期的符号(例如,bbb,2012-05-15),我有删除符号的列表;

  3. 我试图在for循环中比较数据集中的日期和删除日期,如果特定符号彼此相等则删除整行,这就是问题所在;

    < / LI>
  4. 代码如下:

    Dim d1 As Date
    d1 = DateSerial(2012, 5, 15) 'This is the deleting date  
    MsgBox (IsDate(d1)) 'This returns true   
    MsgBox (IsDate(DateValue(Cells(4, 9)))) 'This returns true
    
    For j = lastRow To 2 Step -1  
       If Cells(j,2).Value = "bbb" And (CDate(d1) = DateValue(Cells(j, 9))) Then Rows(j).EntireRow.Delete  
    Next
    
  5. VBA给了我“类型不匹配”错误。我也尝试了如果d1 = DateValue(Cells(j,9))然后行(j).EntireRow.Delete但这也不起作用。屏幕截图在单元格中有值,当它引发错误时。

    The screenshot has the value is in the cell, when it raises the error

2 个答案:

答案 0 :(得分:2)

看起来你遇到了一个无法转换为DateValue的空单元格。

在即时窗口中,尝试:

?DateValue("")你会得到同样的错误。

您只需要扩展一下逻辑:

For j = lastRow To 2 Step -1  
   If Cells(j,2).Value = "bbb" And Not Cells(j,9) = vbNullString And IsDate(Cells(j,9) Then
      If (CDate(d1) = DateValue(Cells(j, 9))) Then Rows(j).EntireRow.Delete  
   End If
Next

答案 1 :(得分:0)

我实际上尝试了这个并且它有效。我唯一改变的是,我将实际日期放入日期栏,第一栏(其他评论者注意到也许是你的问题),我把lastrow作为一个数字。

确保您在第I列中有日期,最后一行是一个数字,您不应该得到该错误

相关问题