使用VBA删除具有多个条件的行

时间:2015-08-24 08:56:07

标签: excel vba excel-vba

我在excel中有一个原始数据作为xls扩展。 我想根据3个条件删除行。

  1. 删除包含带有文字的字段的行"否"在第c栏
  2. 删除包含带有文字&#34的字段的行; ExtBUD"和" ExtItaly"在D栏
  3. 删除C和D列中的空白行。
  4. 这是数据

          A            B               C               D
           Fname         Lname        activeconnect      Clustername
    1.     ram           raju            Yes             ExtIndia
    2.     John          reynold         Yes             ExtBUD
    3.     Sree           olaf           No              ExtUSA
    4.                consider as Blank row
    5.     alois         lobmier           No             ExtPeru
    6.      Niko          papa            yes             ExtItaly
    

    示例输出应如下

             A            B               C               D
           Fname         Lname        activeconnect      Clustername
    1.     ram           raju            Yes             ExtIndia
    

    这里我的代码适用于第一个条件,也删除了包含" ExtBUD"字段的行。请有人帮帮我吗

    Sub Import()
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    row_number = 1
    Do
    DoEvents
       row_number = row_number + 1
       active_connect = Sheets("WX Messenger Export 20150819").Range("U" & row_number)
       cluster_name = Sheets("WX Messenger Export 20150819").Range("X" & row_number)
       If InStr(active_connect, "No") >= 1 Then
       If InStr(cluster_name, "ExtBUD") >= 1 And InStr(cluster_name, "ExtItaly") >= 1 Then
    
       Sheets("WX Messenger Export 20150819").Rows(row_number & ":" & row_number).Delete
       row_number = row_number - 1
       End If
        End If
    
     Loop Until active_connect = ""
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

试试这个:

Public Sub deleteRow()

    Dim row, lastRow As Integer

    With Sheets("WX Messenger Export 20150819")

        'Set the start row
        row = 2

        'Get the last row
        lastRow = .Range("A2").SpecialCells(xlCellTypeLastCell).row

        'loop from first row to last row
        Do While row <= lastRow

            'If condition are equal, delete row
            If .Range("C" & row) = "No" Or .Range("D" & row) = "ExtBUD" Or .Range("D" & row) = "ExtItaly" Or (.Range("C" & row) = "" And .Range("D" & row) = "") Then

                .Rows(row).Delete

                lastRow = lastRow - 1

            'Else go to next row
            Else

                row = row + 1

            End If

        Loop

    End With

End Sub