根据日期过滤器比较一张纸与另一张纸的范围

时间:2019-03-27 05:12:44

标签: excel vba excel-formula

我下面有代码比较两个基于工作表的日期过滤器。如果唯一值低于指定日期,则记录将在sheet1中删除,超过指定日期的唯一值将被添加到sheet2中sheet1中的行。

我希望有人解释以下代码:

Option Explicit

Sub Operation()
    Dim Sheet1 As Excel.Worksheet
    Set Sheet1 = ThisWorkbook.Sheets("Sheet1")

    Dim Sheet2 As Excel.Worksheet
    Set Sheet2 = ThisWorkbook.Sheets("Sheet2")

    Dim SpdDate As Date
    SpdDate = DateSerial(2019, 3, 25)    '// DateValue("March 25,2019")

    DeleteOldTasks Sheet1, SpdDate, Sheet2
    InsertNewTasks Sheet2, Sheet1
End Sub

Private Sub DeleteOldTasks(ByRef Target As Excel.Worksheet, ByVal dt As Date, ByRef Source As Excel.Worksheet)
    Dim LastRow As Long
    LastRow = Target.Cells(Target.Rows.Count, 2).End(xlUp).Row

    Dim i As Long
    For i = LastRow To 2 Step -1
        Dim rng As Excel.Range
        Set rng = Target.Range("B" & i & ":C" & i)

        If (rng.Cells(2) < dt) Then
            If Not (TaskDateExist(Source, rng)) Then
                rng.Cells(2).EntireRow.Delete
            End If
        End If
    Next
End Sub

Private Function TaskDateExist(ByRef Source As Excel.Worksheet, ByRef rng As Excel.Range)
    Dim LastRow As Long
    LastRow = Source.Cells(Source.Rows.Count, 2).End(xlUp).Row

    Dim i As Long
    For i = 2 To LastRow
        Dim lookupRng As Excel.Range
        Set lookupRng = Source.Range("B" & i & ":C" & i)

        If ((rng.Cells(1).Value = lookupRng.Cells(1).Value) And _
           (rng.Cells(2).Value = lookupRng.Cells(2).Value)) Then
            TaskDateExist = True
        End If
    Next
End Function
Private Sub InsertNewTasks(ByRef Source As Excel.Worksheet, ByRef Target As Excel.Worksheet)
    Dim LastRow As Long
    LastRow = Target.Cells(Target.Rows.Count, 2).End(xlUp).Row

    Dim LastDate As Date
    LastDate = Target.Range("C" & LastRow)

    Dim RowToInsert As Excel.Range
    Set RowToInsert = Target.Range("A" & LastRow & ":" & "C" & LastRow).Offset(RowOffset:=1)

    LastRow = Source.Cells(Source.Rows.Count, 2).End(xlUp).Row

    Dim i As Long
    For i = 2 To LastRow
        If (Source.Range("C" & i) > LastDate) Then
            RowToInsert.Cells(1) = Source.Range("A" & i)
            RowToInsert.Cells(2) = Source.Range("B" & i)
            RowToInsert.Cells(3) = Source.Range("C" & i)
        End If
    Next
End Sub

0 个答案:

没有答案
相关问题