在VBA中匹配日期

时间:2014-04-03 07:25:26

标签: excel vba

我正在使用此代码来匹配日期。

代码:

    strDate1 = Sheets("Part2").Cells(i, 1).Value
    date1 = DateSerial(Left(strDate1, 4), Mid(strDate1, 3, 2), Right(strDate1, 2))
    srtDate2 = Format(DateAdd("yyyy", -1, date1), "yyyymmdd")
    matchStartRow = Application.Match(CDbl(srtDate2), Sheets("1.A").Range("A:A"), 1)
    If IsError(matchStartRow) Then
        matchStartRow = 3
    Else
        matchStartRow = matchStartRow + 1
    End If

如果日期匹配,则matchstartrow应保持不变。如果不匹配,则需要添加一个。如何融入这个?代码似乎错了..

需要一些指导来修改它..

此代码来自:How to get date - 1 year in vba

1 个答案:

答案 0 :(得分:1)

试试这个:

strDate1 = Sheets("Part2").Cells(i, 1).Value
date1 = DateSerial(Left(strDate1, 4), Mid(strDate1, 3, 2), Right(strDate1, 2))
srtDate2 = Format(DateAdd("yyyy", -1, date1), "yyyymmdd")
'trying to find EXACT match
matchStartRow = Application.Match(CDbl(srtDate2), Sheets("1.A").Range("A:A"), 0)
If IsError(matchStartRow) Then
    'If exact match not found, searching for approx match
    matchStartRow = Application.Match(CDbl(srtDate2), Sheets("1.A").Range("A:A"), 1)
    If IsError(matchStartRow) Then
        'if approx match not found - that's means that target date is less than all dates in Sheets("1.A").Range("A:A"), so we get 3rd row with first date
        matchStartRow = 3
    Else
        'if approx match is found we add 1 to get first date greater than target
        matchStartRow = matchStartRow + 1
    End If
End If

或者这个应该有效:

strDate1 = Sheets("Part2").Cells(i, 1).Value
date1 = DateSerial(Left(strDate1, 4), Mid(strDate1, 3, 2), Right(strDate1, 2))
srtDate2 = Format(DateAdd("yyyy", -1, date1), "yyyymmdd")
matchStartRow = Application.Match(CDbl(srtDate2), Sheets("1.A").Range("A:A"), 1)
If IsError(matchStartRow) Then
    matchStartRow = 3
Else
    'if we found exact match, add 0, else add 1
    matchStartRow = matchStartRow + IIf(Sheets("1.A").Range("A" & matchStartRow).Value = CDbl(srtDate2), 0, 1)
End If