简体   繁体   English

根据两列的值删除行

[英]Delete rows based on values of two columns

I want to retain any rows in excel which only contain "ECGS2A" or "ECGS2B" in column E and "Customer Opt In" in column M but having difficulty with trying different VBA codes. 我想保留excel中仅在E列中包含“ ECGS2A”或“ ECGS2B”而在M列中仅包含“客户选择加入”的所有行,但是很难尝试使用不同的VBA代码。

I need to retain headers on row 4 but when trying to add range other than column E on: 我需要在第4行保留标题,但是在尝试添加除E列以外的范围时:

j = Range("E" & Rows.Count).End(xlUp).Row

I get an error or "Run time error '1004': Method of 'Range' of object_Global' failed 我收到错误或“运行时错误'1004':object_Global'的'范围'方法失败

' Deleting entire rows with MyTarget
Sub myDeleteRows2()

Const MyTarget = "*ECGS2A*"

Dim Rng As Range, DelCol As New Collection, x
Dim I As Long, j As Long, k As Long

' Calc last row number
j = Range("E" & Rows.Count).End(xlUp).Row

' Collect rows range with MyTarget
For I = 1 To j
If WorksheetFunction.CountIf(Rows(I), MyTarget) = 0 Then 'changed from > 0
k = k + 1
If k = 1 Then
Set Rng = Rows(I)
Else
Set Rng = Union(Rng, Rows(I))
If k >= 100 Then
DelCol.Add Rng
k = 0
End If
End If
End If
Next
If k > 0 Then DelCol.Add Rng

' Turn off screen updating and events
Application.ScreenUpdating = False
Application.EnableEvents = False

' Delete rows with MyTarget
For Each x In DelCol
x.Delete
Next


' Update UsedRange
With ActiveSheet.UsedRange: End With

' Restore screen updating and events
Application.ScreenUpdating = True
Application.EnableEvents = True

End Sub

also tried 也尝试过

Sub DeleteRowsBasedOnMultipleCriteria()

lRow = 13 ' Your last row with the data

Do While lRow >= 1

'1=Column A,6=Column F, 18=Column R
 If Cells(lRow, 5) = "ECGS9" _
        Or Cells(lRow, 13) = "Customer Opt Out" Then
        Rows(lRow).Delete
 End If

lRow = lRow - 1
Loop

End Sub

I expect to be left with column E only displaying anything with ECGS2A or ECGS2B and column M as Customer Opt In. 我希望保留E列,仅显示ECGS2A或ECGS2B的任何内容,而M列显示为“客户选择加入”。 If the columns display anything other than those mentioned, I want them deleted. 如果这些列显示的内容不是上述内容,我希望将其删除。

在此处输入图片说明

Sub Macro1()
Dim LRow As Long, i As Long
Application.ScreenUpdating = False
With ThisWorkbook.Worksheets("Sheet1") 'Change to your sheet name
    LRow = .Range("E" & .Rows.Count).End(xlUp).Row
    For i = LRow To 5 Step -1
        If Not ((.Cells(i,5) Like "ECGS2A*" Or .Cells(i,5) Like "ECGS2B*") And .Cells(i, 13) Like "Customer Opt In*")  Then
            .Rows(i).Delete
        End If
    Next i
End With
Application.ScreenUpdating = True
End Sub

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

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