我一直在努力工作的时间超过了我想承认的范围。我正在比较两个工作表(A & B)。我正在循环访问A列(“B”),并且对于该列中的每个值,我都会根据B列(“C”)进行检查。如果有匹配,我想删除整行。删除所有包含值为VBA的行
我已经做了许多不同的方法,我只是无法让它工作。这是原件:
Option Explicit
Sub Purge()
Dim wipWS As Worksheet
Dim invWS As Worksheet
Dim C As Range
Dim SourceLastRow As Long
Dim DestLastRow As Long
Dim LRow As Long
Dim D As Range
Set wipWS = Worksheets("Work in Process")
Set invWS = Worksheets("Inventory Allocation")
With wipWS
' find last row in Work in Process Column B
SourceLastRow = .Cells(.Rows.count, "E").End(xlUp).Row
' find last row in Inventory Allocation Column C
DestLastRow = invWS.Cells(invWS.Rows.count, "B").End(xlUp).Row
' define the searched range in "Inventory Allocation" sheet
Set C = invWS.Range("B1:B" & DestLastRow)
Set D = wipWS.Range("E1:E" & SourceLastRow)
' allways loop backwards when deleting rows or columns
' choose 1 of the 2 For loops below, according to where you want to delete
' the matching records
' --- according to PO request delete the row in Column B Sheet A
' and the row in Column C in "Inventory Allocation" worksheet
' I am looping until row 3 looking at the PO original code
For LRow = SourceLastRow To 1 Step -1
' found a match between Column B and Column C
If Not IsError(Application.Match(.Cells(LRow, "E"), C, 0)) Then
.Cells(LRow, 2).EntireRow.Delete Shift:=xlUp
invWS.Cells(Application.Match(.Cells(LRow, "E"), C, 0), 2).EntireRow.Delete Shift:=xlUp
End If
Next LRow
End With
End Sub
它的工作原理,除了留下1行(应该删除)。我想我知道为什么会发生,除非我不知道如何去做。我已经尝试了一个For循环,它的工作原理,除了我必须设置一个范围(例如,“A1:A200”),我希望它只根据行数循环。
任何帮助将不胜感激!
对于初学者来说,你首先对于每一个不通过B列循环看一看由@cullan答案,这似乎是在做列循环,你想要的。 – dev1998
基本上你想要比较表A中的B列和B表中的C列,并且你有一个2个循环。问题:你在Sheet A Column B中独特的价值吗?如果他们是你可以只有1'For'循环并且使用'Match'函数或'VLookup',它会加快你的代码运行速度 –
@Twigs看看我的答案,使用'Match'函数 –