簡體   English   中英

VBA代碼刪除整個行,如果該行的特定列的值在另一個工作表中不匹配

[英]Vba code to delete the entire row if value for particular column for that row does not match in another worksheets

我正在嘗試刪除兩個工作表中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

我建議通過從下到上反轉循環。
For x = Lastrowo To 1 Step - 1

參見其他處理類似代碼的帖子: https : //stackoverflow.com/a/47062983/4636801

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM