Excel VBA基于列值删除行

我想编写一个Excelmacros,通过K1 —> K(lastrow)并查找值“OptedOut”,如果它find该值,那么它将删除该行。 我感谢帮助的人。 唯一的部分是错误的For Each C部分,因为我不明白数组,可能“c.Value =”OptedOut“然后行(c)。删除”有点拉出我的屁股。

谢谢大家!

Sub DuplicateDelete() Sheets("ALL CLIENTS").Range("A1:J10000").Copy Destination:=Sheets("ClientsAndEmailsThatAreOK").Range("A1:J10000") With ActiveSheet LastRow = .Cells(.Rows.Count, "K").End(xlUp).Row MsgBox LastRow End With 'Dim c As Range For Each c In Range(Range(Cells("K1"), Cells(LastRow, "K"))) If c.Value = "OptedOut" Then Rows(c).Delete Next c End Sub 

删除行(或其他对象)时向后循环。

此外,而不是使用ActiveSheet尝试完全限定您的Worksheet对象,如Sheets("ClientsAndEmailsThatAreOK")

尝试下面的代码,在代码的评论里面的解释:

 Option Explicit Sub DuplicateDelete() Dim C As Range Dim i As Long, LastRow As Long Sheets("ALL CLIENTS").Range("A1:J10000").Copy Destination:=Sheets("ClientsAndEmailsThatAreOK").Range("A1:J10000") ' I'm assuming you want to work with sheet "ClientsAndEmailsThatAreOK" (if not then switch it) With Sheets("ClientsAndEmailsThatAreOK") LastRow = .Cells(.Rows.Count, "K").End(xlUp).Row MsgBox LastRow ' always loop backwards when deleting rows For i = LastRow To 1 Step -1 If .Range("K" & i).Value2 = "OptedOut" Then .Rows(i).Delete Next i End With End Sub