删除值与列表不同的行

时间:2017-09-27 14:28:47

标签: excel vba excel-vba

我有4个excel文件,每个文件大约有2000行。 在A列中,我有几个4个字符的字符串。

我想删除除代码以<:p>开头的所有行

E,L,GC,UD,UG,UB,UK,B

有太多的过滤器一个接一个,我猜一个宏会是一个更好的解决方案。

我的代码是这个,但它只是留下B值而不是所有有趣的值:

ActiveSheet.Range("$A$1:$A$1379").AutoFilter Field:=1, Criteria1:=Array("=E*", _
    "=GC*", "=UD*", _
    "=UG*", "=UB*", _
    "=UK*", "=B*"), _
    Operator:=xlOr

你会怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用For循环遍历行,使用If语句确定哪些Cell符合条件。这将是if语句的长字符串,但应该起作用:

Dim i as Long, LR as Long
LR = cells(rows.count,1).End(xlUp).Row
For i = 2 to LR
    If Left(Cells(i,1).Value,1) = "E" OR Left(Cells(i,1).Value,1) = "L" OR Left(Cells(i,1).Value,2) = "GC" OR Left(Cells(i,1).Value,2) = "UD" OR Left(Cells(i,1).Value,2) = "UG" OR Left(Cells(i,1).Value,2) = "UB" OR Left(Cells(i,1).Value,2) = "UK" OR Left(Cells(i,1).Value,1) = "B" Then
        'Nothing
    Else
        Rows(i).Delete
    End If
Next i

所有的工作都在那个If语句中。如果你想放弃Else部分,你可以制作If Not Left(...)。这假设您在第1列(A)中工作。

修改

根据我留在帖子上的第二条评论,尝试使用.Delete代码处理新工作表:

Sheets("SOURCENAME").Copy Sheets(Sheets.Count)

然后,您将在新创建的工作表上运行循环

<强> EDIT2:

删除单元格时,您需要向后移动:

For i = LR to 2 Step -1
    'Stuff
Next i

答案 1 :(得分:1)

在上面的每张工作表中运行以下

Sub RemoveRows()

    Dim sh As Long
    Dim i As Long

    sh = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

    For i = 1 To sh

    ' Checking criteria section:        
    If InStr(1, Cells(i, "A").Value, "E") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "L") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "GC") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "UD") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "UG") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "UB") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "UK") = 1 Then Exit Sub
    If InStr(1, Cells(i, "A").Value, "B") = 1 Then Exit Sub

    Cells(i, "A").EntireRow.Delete

End Sub

方面。