如何从日期范围中删除假期Excel VBA

时间:2019-12-24 15:14:57

标签: excel vba

我在A列(Sheet1)中有一个日期列表,我想删除与Sheet2中找到的任何假期日期匹配的整个行。例如:

日期(A列,表格1)

23/12/2019                                
24/12/2019                                
25/12/2019
26/12/2019
27/12/2019
28/12/2019
29/12/2019

假日(A栏,Sheet2)

25/12/2019
26/12/2019

运行代码后,应删除工作表1中包含12月25日和26日的行。另外,可能有几个月没有假期可以删除。任何帮助将不胜感激。

我尝试了以下代码。该循环似乎有效,但是由于某些原因,没有行被删除

With Sheets("Sheet1")
    lastrow = Cells(Rows.Count, 1).End(xlUp).Row
 For i = lastrow To 7 Step -1
    If Not IsError(Application.Match(Sheets("Sheet1").Range("A" & i).Value, 
         Sheets("Sheet2").Columns("A"), 0)) Then 
         Sheets("Sheet1").Rows(i).Delete
    Next i
End With

1 个答案:

答案 0 :(得分:1)

尝试一下:

Sub RemoveDates()

Dim RemovalList()

SheetOneLastRow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
SheetTwoLastRow = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
Count = 0

'Collect all the dates that need to be removed into a list
For r = 1 To SheetTwoLastRow
    ReDim Preserve RemovalList(0 To Count)
    RemovalList(Count) = Sheets("Sheet2").Range("A" & r).Value
    Count = Count + 1
Next

For r = SheetOneLastRow To 1 Step -1
    If IsInArray(Range("A" & r).Value, RemovalList) Then
        Sheets("Sheet1").Range("A" & r).Delete
    End If
Next

End Sub


Function IsInArray(SearchFor As String, MyArray As Variant) As Boolean
    Dim st As String
    st = "$" & Join(MyArray, "$") & "$"
    IsInArray = InStr(st, "$" & SearchFor & "$") > 0
End Function

希望这会有所帮助!