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

时间:2017-11-05 20:33:50

标签: excel vba excel-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

1 个答案:

答案 0 :(得分:1)

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

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

我建议通过从下到上来反转循环 For x = Lastrowo To 1 Step - 1

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