将表与其他工作表中的列表进行比较,并删除没有匹配项

时间:2018-09-05 09:03:57

标签: excel vba compare

我有以下代码,用于比较两个列表(工作表1中的A列和工作表2中的C列),并删除工作表2的列表中不存在的值。此代码可以正常工作,但在以下情况下不起作用工作表1中的A列和工作表2中的C列都有表。请让我知道如何修改此代码以使其也适用于表。另外,如何从多个工作表中没有任何匹配项删除,这些工作表的C列(表2)中的常量是一个列表?

Sub Stridhan()

Dim lr As Integer, x As Integer   
lr = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
Application.ScreenUpdating = False  
For x = lr To 2 Step -1  
    If Application.WorksheetFunction.CountIf(Sheets("Sheet2").Range("C:C"), Sheets("Sheet1").Cells(x, 1).Value) = 0 Then  
        Sheets("Sheet1").Rows(x).EntireRow.Delete  
    End If  
Next x  
Application.ScreenUpdating = True  
End Sub

1 个答案:

答案 0 :(得分:0)

为了让它遍历更多工作表,您可以使用如下代码

Sub cycle_sheets()
For Each sh In Worksheets
    If sh.Name <> "Sheet2" Then
        'your code to cycle through the data where instead of Sheets("SheetX"). you use sh. like this
        sh.Rows(x).EntireRow.Delete
    End If
Next
End Sub

这将遍历所有工作表,并且对于所有与“ Sheet2”不同的名称,它将执行if中的内容。因此,您只需要获取代码,更改工作表引用并将其放在if中。

编辑: 如果您希望它跳过由于过滤而无法看到的行,则可以在确定是否要使用

删除它之前检查该行
If sh.Rows(x).Hidden = False Then
相关问题