循环列表与另一个列表进行比较,如果相同则删除

时间:2017-06-29 08:27:01

标签: vba excel-vba excel

我正在尝试查找表4列A中的一系列值(大约有100个),然后使用此列表查看表2列C中更大的列表(200,000行)。在表4列A中出现的值我想检查表2列c中的每一行,如果值匹配,那么我想删除表2中的整行。

我的代码如下:

但它似乎没有用,说有一个对象错误

Option Explicit

Sub Test()
Dim rng As Range
Dim I As Long, J As Integer
Dim myCell As Range
Set rng = Worksheets("Sheet4").["A1:A" & Range("A" & 
Rows.Count).End(xlUp).Row)"]
With rng
For I = .Rows.Count To 1 Step -1
For J = 1 To .Columns.Count
For Each myCell In Worksheets("Sheet2").Range("C1:C" & Range("C" & 
Rows.Count).End(xlUp).Row)
If .Cells(I, J).Value = myCell Then
.Cells(I, J).EntireRow.Delete xlUp
Exit For
End If
Next
Next J
Next I
End With
Set rng = Nothing
End Sub

任何帮助都会很棒!

非常感谢

2 个答案:

答案 0 :(得分:2)

您可以使用1 For循环遍历For中“C”列中的所有单元格,而不是拥有2个Worksheets("Sheet2")循环,并且对于每一行,请使用{{ 1}}查看Application.Match中的“A”列是否匹配。

注意:在删除行时总是向后循环。

<强> 代码

Worksheets("Sheet4")

答案 1 :(得分:0)

You can use ADODB within the macro which can give you the result in seconds

Sub Filter()

Dim con As New ADODB.Connection

Dim rs As New ADODB.Recordset

Dim DBPath As String, sconnect As String

DBPath = ThisWorkbook.FullName  'Refering the sameworkbook as Data Source

'You can provide the full path of your external file as shown below
'DBPath ="C:\InputData.xlsx"

sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

'If any issue with MSDASQL Provider, Try the Microsoft.Jet.OLEDB:
'sconnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

con.Open sconnect

sSQLSting = "SELECT * From [Sheet2$] WHERE ColC not in (SELECT ColA FROM [Sheet1$])" ' Your SQL Statement (Table Name= Sheet Name=[Sheet1$])

rs.Open sSQLSting, con

Sheet3.Range("A2").CopyFromRecordset rs

End Sub



NOTE : In the Excel Code editor go to TOOLS->References and set a reference to Microsoft ActiveX Data Objects 6.1 Library