VBA宏,删除列中包含关键字的行

时间:2015-06-03 14:13:36

标签: excel vba loops keyword

我试图为VBA写一个宏,它将通过其中一个列(比方说D),并将其中的名称与我将在Sheet 2上的排除列表进行比较。然后需要删除一行带有匹配的单词并向上移动列表,直到整个列表中没有带有这些单词的行。

据我所知,但由于某种原因,它没有做任何事情。

    Sub Delete_Exeptions()
     x = 2
     Do While ThisWorkbook.Sheets("List1").Cells(x, 4) <> ""
        i = 11
        Do While ThisWorkbook.Sheets("List2").Cells(i, 1) <> ""
           If ThisWorkbook.Sheets("List1").Cells(x, 4).Value = ThisWorkbook.Sheets("List2").Cells(i, 1).Value Then ThisWorkbook.Sheets("List1").Cells(x, 4).EntireRow.Delete
           i = i + 1
        Loop

        x = x + 1
     Loop
如果有人不感兴趣,这个工作得非常顺利:

Sub Delete_Exeptions()
     x = 2
    Do While ThisWorkbook.Sheets("List1").Cells(x, 4) <> ""



        i = 11
        Do While ThisWorkbook.Sheets("List2").Cells(i, 1) <> ""


            If ThisWorkbook.Sheets("List1").Cells(x, 4).Value <> ThisWorkbook.Sheets("List2").Cells(i, 1).Value Then

            Else: ThisWorkbook.Sheets("List1").Cells(x, 4).EntireRow.Delete


            End If
            i = i + 1
        Loop

       x = x + 1
    Loop

End Sub

嗯,它的最终eddit,我已经改变了推荐,所以第一个循环从最后一行到第一个,因为我遇到了问题,当我连续两次排除时。但是我决定不使用其他方法(Match和CurentRegion),因为它们并没有真正为我工作。

Sub Test_Bottom_toup()

Dim str As String
Dim strArr() As String
Dim ws As Worksheet
Dim lRow As Long

Set ws = ThisWorkbook.Sheets("List1")

With ws
    lRow = .Range("D" & .Rows.Count).End(xlUp).Row
End With

x = lRow
    Do While x <> 1


    str = ThisWorkbook.Sheets("List1").Cells(x, 4)
    strArr = Split(str, " - ")
    ' This one is for my data spesifically as I had a random number before actual name, which might not be on the list of exlusions.

    i = 11

     Do While ThisWorkbook.Sheets("List2").Cells(i, 1) <> ""

     If strArr(1) <> ThisWorkbook.Sheets("List2").Cells(i, 1) Then

     Else: ThisWorkbook.Sheets("List1").Cells(x, 4).EntireRow.Delete


     End If

     i = i + 1
     Loop

    x = x - 1
    Loop

End Sub

0 个答案:

没有答案