Filter Results by date, or by beetwen two dates

2019-08-18 16:50发布

I have this code and i want do filter the autofill results by two dates (ex: from 01-01-2009 to 02-10-2010). How can i do this? Does anybody have a clue? The code bellow is simplified (the current one only have more Ranges). I´ve tried to add condidions in the If Function but i only get error... thanks for your help. By the way i had a great help for this code so i´m a litte noob in excel macro vba :).

The dimResult1, clean1 etc stands for the date values. What i can´t do is to skip to nextcell if oCellResult1.Offset(iCellCount, 0).Value = oCell.Offset(0, 4).Value isn´t between the two dates.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim oCell As Excel.Range
Dim oCellResult1 As Excel.Range
Dim oCellResult2 As Excel.Range
Dim oCellClean1 As Excel.Range
Dim oCellClean2 As Excel.Range
Dim oRangeID As Excel.Range
Dim iCellCount As Integer


If Target.Address = "$T$4" Then

    'Set source data
    Set oRangeID = Sheets("Registo_EPI").Range("A3:A5000")

    'Define initial target for the results obtained
    'data
    Set oCellResult1 = Sheets("Distribuição_EPI").Range("U12") 
    'luvas
    Set oCellResult2 = Sheets("Distribuição_EPI").Range("E12") 

    'Clear up any previous data
    Set oCellClean1 = oCellResult1
    Set oCellClean2 = oCellResult2
    While Len(oCellClean1.Value) > 0

        oCellClean1.ClearContents
        Set oCellClean1 = oCellClean1.Offset(1, 0)

        oCellClean2.ClearContents
        Set oCellClean2 = oCellClean2.Offset(1, 0)

    Wend

    'Scans source range for match data
    For Each oCell In oRangeID

        If oCell.Value = "" Then Exit For

        If oCell.Value = Target.Value Then

           'data
           oCellResult1.Offset(iCellCount, 0).Value = oCell.Offset(0, 4).Value 
           'luvas
           oCellResult2.Offset(iCellCount, 0).Value = oCell.Offset(0, 9).Value 
           iCellCount = iCellCount + 1

           If iCellCount = 14 Then iCellCount = iCellCount + 20


        End If

    Next oCell

End If

End Sub

1条回答
来,给爷笑一个
2楼-- · 2019-08-18 17:45

If I understood correctly what you're trying to achieve, we can add a new condition in our IF statement.

It would be something like:

    'Ensure the value in oCell is a date; otherwise the comparison won't work
    If oCell.Value = Target.Value and IsDate(oCell.Value) Then

        'Date Comparison
        if cDate(oCell.Value) > cdate("01-01-2009") and _
            cDate(oCell.Value) < ("02-10-2010") then

            'data
            oCellResult1.Offset(iCellCount, 0).Value = oCell.Offset(0, 4).Value 
            'luvas
            oCellResult2.Offset(iCellCount, 0).Value = oCell.Offset(0, 9).Value 
            iCellCount = iCellCount + 1

            If iCellCount = 14 Then iCellCount = iCellCount + 20

        end if

    End If
查看更多
登录 后发表回答