在excel中查找多个单词并使用vba删除行

时间:2018-03-24 05:00:58

标签: excel vba excel-vba

我尝试根据我在堆栈上找到的两个脚本创建自己的脚本,但我无法使它看起来有效。所以我想要做的是在我的Excel文档中找到某些单词,然后删除数据所在的行。

我正在寻找的字符串模式最终会及时增长,所以我需要能够更新我的数组并让我的vba脚本删除任何符合我模式的行。

Sub Deletrows_Click()

Dim WS As Worksheet
Dim pattern As String
Dim MyVar

For Each WS In ThisWorkbook.Worksheets
    With WS
        pattern = "string 1/ string 2/ string 3"
        MyVar = Split(pattern, "/")

        RowCount = ActiveSheet.UsedRange.Rows.Count

        Dim i As Integer
        For i = 2 To RowCount
            Dim j As Integer
            For j = 1 To 3 'find the word within this range
                If Cells(i, j) = pattern Then
                    Cells(i, j).EntireRow.Delete
                End If
            Next j
        Next i
    End With
Next WS

End Sub

1 个答案:

答案 0 :(得分:2)

首先,您有With WS,但其中的所有对象都未使用With语句引用,因为您缺少.

因此RowCount = ActiveSheet.UsedRange.Rows.Count应为RowCount = .UsedRange.Rows.CountIf Cells(i, j)...也应为If .Cells(i, j)...

第二次,检查某个单元格中某个字符串中是否有字符串的好方法,在您的案例中MyVar,其中包含您的所有pattern,请使用Match函数:

If Not IsError(Application.Match(.Cells(i, j).Value, MyVar, 0)) Then

以下代码中的更多解释:

<强> 代码

Option Explicit

Sub Deletrows_Click()

Dim WS As Worksheet
Dim pattern As String
Dim MyVar
Dim RowCount As Long, i As Long, j As Long
Dim DelRng As Range

' take it outside the loop, no need to re-create the array every time inside the loop
pattern = "string 1/ string 2/ string 3"
MyVar = Split(pattern, "/")

For Each WS In ThisWorkbook.Worksheets
    With WS
        RowCount = .UsedRange.Rows.Count

        For i = 2 To RowCount
            For j = 1 To 3 'find the word within this range

                ' you can use Match to see if cell's value is found within an array
                If Not IsError(Application.Match(.Cells(i, j).Value, MyVar, 0)) Then
                    If Not DelRng Is Nothing Then
                        Set DelRng = Application.Union(DelRng, .Cells(i, j))
                    Else
                        Set DelRng = .Cells(i, j)
                    End If
                End If
            Next j
        Next i
    End With

    ' after looping through all cells, delete all rows with words in pattern at onc shot
    If Not DelRng Is Nothing Then DelRng.EntireRow.Delete shift:=xlShiftUp

    Set DelRng = Nothing ' reset range object
Next WS

End Sub