Excel VBA基于列值删除行

时间:2017-09-07 04:22:38

标签: excel vba excel-vba

我想编写一个Excel宏,通过K1 ---> K(lastrow)并查找值" OptedOut",如果找到该值,则删除该行。我很感激帮助人员。唯一错误的部分是For Each C部分,因为我不理解数组,可能" c.Value =" OptedOut"然后行(c)。删除"有点把它拉出我的屁股。

全部谢谢!

[self.testLabel selectText:self];
[[self.testLabel currentEditor] setSelectedRange:NSMakeRange(0, 0)];

1 个答案:

答案 0 :(得分:2)

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

此外,不要使用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