VBA代码无法识别特定格式的日期

时间:2013-11-11 14:44:37

标签: vba date excel-vba excel-2007 excel

我正在处理使用唯一ID号和关联日期的代码,以查看工作表中是否已存在相同的记录。这是我的代码:

第一段代码的一部分:

Else
   'If all the data has been entered, go to New_Record
   Check_Record ID:=Sheets("Information").Range("A1").Value, vDate:=Sheets("Information").Range("A2").Value
End If
End Sub

第一个代码后面的第二个代码:

Function Record(ID As String, vDate As String)

    Dim Current_ID_List As Range
    Dim vCaseWasFound, vDateWasFound, vLastDataRow As Range
    Dim DestinationRow As Integer
    Dim Go_ahead_msg As String

    Set ID_List = Sheets("Records").Range("A:A")
    Set Date_List = Sheets("Records").Range("D:D")

    '-- determine whether record exists
    Set vCaseWasFound = ID_List.Find(What:=ID, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)
    Set vDateWasFound = Date_List.Find(What:=vDate, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)
    Set vLastDataRow = Sheets("RawData").Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows)

    If Not vCaseWasFound Is Nothing And Not vDateWasFound Is Nothing Then
        Go_ahead_msg = "The record already exists."
    Else
        Go_ahead_msg = "This is a new record."
    End If

    If MsgBox(Go_ahead_msg, vbQuestion + vbYesNo) = vbYes Then
    New_Record
    Sheets("Sheet1").Activate
    Else
        With Sheets("Records")
        .Activate
        .Range("A1").Select
    End With

       End If

End Function

我遇到的问题是代码无法识别某些格式的相同日期。如果我有相同的ID和相同的日期(格式如12/12/2012),则代码将识别为同一记录,并将给出“记录已存在”的消息。但是,如果日期是格式,例如2013年1月1日或4/15/2012或4/1/2013,代码无法将其识别为同一日期。

1 个答案:

答案 0 :(得分:1)

这是因为它是字符串比较而不是日期比较。

如果要搜索日期,则无法使用Range.Find方法。 您必须将字符串转换为日期,然后搜索将每个值转换为日期然后进行比较的范围。

您可以先设置日期列的格式,然后再进行搜索。 如果您使用MM / DD / YYYY格式化它们,那可能会有效。 然后你可以比较字符串。 但是你还必须格式化你传入的那个。

将字符串值格式化为日期:

Set rngMatch = rngSearchMe.Find(What:=Format(strDateValue, "MM/DD/YYYY"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)

将范围格式化为mm / dd / yyyy:

   Set rngSearchMe = Sheets("Sheet1").Range("D:D")
   rngSearchMe.NumberFormat = "mm/dd/yyyy;@"