无法删除文本中包含特定关键字的行

时间:2017-08-15 07:28:31

标签: vba excel-vba excel

我编写了一个宏来删除包含某些文本的行。如果任一关键字包含任何文本,宏将删除该行。但是,宏根本不起作用。也许,我做错了。希望有人能帮助我纠正这个问题。提前谢谢。

以下是我正在尝试的内容:

Sub customized_row_removal()
    Dim i As Long
    i = 2
    Do Until Cells(i, 1).Value = ""
        If Cells(i, 1).Value = "mth" Or "rtd" Or "npt" Then
            Cells(i, 1).Select
            Selection.EntireRow.Delete
        End If
        i = i + 1
    Loop
End Sub

我正在搜索要删除的文字中的关键字:

AIRLINE DRIVE OWNER mth
A rtd REPAIRS INC
AANA MICHAEL B ET AL
ABASS OLADOKUN
ABBOTT npt P
AIRLINE AANA MTH
ABASS REPAIRS NPT

3 个答案:

答案 0 :(得分:1)

Or的VBA语法错误,

If Cells(i, 1).Value = "mth" Or "rtd" Or "npt" Then

应该是:

If Cells(i, 1).Value = "mth" Or Cells(i, 1).Value = "rtd" Or Cells(i, 1).Value = "npt" Then

但是,您需要使用字符串函数,例如InstrLike,以查看是否在更长的字符串中找到某个字符串。

<强> 代码

Option Explicit

Sub customized_row_removal()

Dim WordsArr As Variant
Dim WordsEl As Variant
Dim i As Long, LastRow As Long
Dim Sht As Worksheet

WordsArr = Array("mth", "rtd", "npt")

Set Sht = Worksheets("Sheet1")
With Sht
    ' get last row in column "A"
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    For i = LastRow To 2 Step -1
        For Each WordsEl In WordsArr
            If LCase(.Cells(i, 1).Value) Like "*" & WordsEl & "*" Then
                .Rows(i).Delete
            End If
        Next WordsEl
    Next i
End With

End Sub       

答案 1 :(得分:1)

试试这样。
那么使用Lcase。

Sub customized_row_removal()
    Dim rngDB As Range, rngU As Range, rng As Range
    Dim Ws As Worksheet

    Set Ws = Sheets(1)
    With Ws
        Set rngDB = .Range("a2", .Range("a" & Rows.Count))
    End With

    For Each rng In rngDB
        If InStr(LCase(rng), "mth") Or InStr(LCase(rng), "rtd") Or InStr(LCase(rng), "npt") Then
            If rngU Is Nothing Then
                Set rngU = rng
            Else
                Set rngU = Union(rngU, rng)
            End If
        End If
    Next rng
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete
    End If
End Sub

答案 2 :(得分:0)

如果您有任何疑问,请尽量让我的代码样本,请询问

  Private Sub remove_word_raw()
'PURPOSE: Clear out all cells that contain a specific word/phrase

Dim Rng As Range
Dim cell As Range
Dim ContainWord As String

'What range do you want to search?

  Set Rng = Range("A2:A25")

  'sub for the word

   shorttext1 = "mth"
   shorttext2 = "rtd"
   shorttext3 = "npt"
'What phrase do you want to test for?

  ContainWord1 = shorttext1
  ContainWord2 = shorttext2
  ContainWord3 = shorttext3

'Loop through each cell in range and test cell contents

  For Each cell In Rng.Cells
  If cell.Value2 = ContainWord1 Then cell.EntireRow.Delete

     Next
     For Each cell In Rng.Cells
     If cell.Value2 = ContainWord2 Then cell.EntireRow.Delete

     Next
     For Each cell In Rng.Cells

      If cell.Value2 = ContainWord3 Then cell.EntireRow.Delete
      Next cell
End Sub