简体   繁体   English

Excel VBA基于列值删除行

[英]Excel VBA Delete Row based on column value

I wanted to write a Excel Macro that goes though K1--->K(lastrow) and looks for the value "OptedOut", and if it finds that value then it deletes that row. 我想编写一个通过K1 ---> K(lastrow)并查找值“ OptedOut”的Excel宏,如果找到该值,则删除该行。 I appreciate the help guys. 我感谢帮助人员。 The only part that is wrong is the For Each C part, because I don't understand arrays, and possibly "c.Value = "OptedOut" Then Rows(c).Delete" kinda pulled that out of my ass. 唯一错误的部分是For Each C部分,因为我不理解数组,并且可能“ c.Value =“ OptedOut”然后Rows(c).Delete“有点把它从我的屁股里拉了出来。

Thanks all! 谢谢大家!

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

Loop backwards when deleting rows (or other objects). 删除行(或其他对象)时向后循环。

Also, instead of using ActiveSheet try to fully qualify your Worksheet object, such as Sheets("ClientsAndEmailsThatAreOK") . 另外,不要使用ActiveSheet尝试完全限定您的Worksheet对象,例如Sheets("ClientsAndEmailsThatAreOK")

Try the code below, explanation inside the code's comments: 尝试以下代码,并在代码注释中进行解释:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM