如果该行的特定列的值在另一个工作表中不匹配,则可以使用Vba代码删除整行

我试图删除这两行工作表中列A的单元格的值不匹配的行,但给定的代码给我错误的输出并删除所有的数据。 请帮助我正确的代码版本。

Lastrowo = ws1.Cells(Rows.Count, "B").End(xlUp).Row Lastrowc = ws2.Cells(Rows.Count, "B").End(xlUp).Row For x = 1 To Lastrowo For m = 1 To Lastrowc If Workbooks("A.xlsx").Sheets("Sheet1").Cells(x, 1).Value <> Workbooks("B.xlsx").Sheets("Sheet1").Cells(m, 1).Value Then Workbooks("A.xlsx").Sheets("Sheet1").Rows(x).EntireRow.Delete Workbooks("B.xlsx").Sheets("Sheet1").Rows(m).EntireRow.Delete End If Next m Next x 

相同的代码,没有第二个循环

 Lastrowo = ws1.Cells(Rows.Count, "B").End(xlUp).Row Lastrowc = ws2.Cells(Rows.Count, "B").End(xlUp).Row For x = 1 To Lastrowo If Workbooks("A.xlsx").Sheets("Sheet1").Cells(x, 1).Value <> Workbooks("B.xlsx").Sheets("Sheet1").Cells(x, 1).Value Then Workbooks("A.xlsx").Sheets("Sheet1").Rows(x).EntireRow.Delete Workbooks("B.xlsx").Sheets("Sheet1").Rows(x).EntireRow.Delete End If Next x 

我会build议从底部到顶部颠倒循环。
For x = Lastrowo To 1 Step - 1

请参阅其他职位处理类似的代码: https : //stackoverflow.com/a/47062983/4636801