删除包含搜索字符串的行的代码会跳过包含字符串的某些行

问题描述 投票:0回答:2

我在下面的Excel VBA中编写了一些代码,它根据用户输入删除行。它几乎完全有效但在某些情况下会在数据中留下一个或两个搜索字符串实例。

Dim SrchStr As String

'enter email address to be searched

SrchStr = InputBox("Enter email")

'open each file and if email address is found, delete that row and save workbook

Workbooks.Open File1
Dim Cell As Variant
Dim SrchRng As Range
Set SrchRng = ActiveSheet.UsedRange

For Each Cell In SrchRng
    If Cell.Value = SrchStr Then
        Cell.EntireRow.Delete
    End If
Next Cell

ActiveWorkbook.Close SaveChanges:=True
excel vba
2个回答
1
投票

试试这段代码:

Dim SrchStr As String

'enter email address to be searched

SrchStr = InputBox("Enter email")

'open each file and if email address is found, delete that row and save workbook

Workbooks.Open File1
Dim Cell As Variant
Dim SrchRng As range
Set SrchRng = ActiveSheet.UsedRange

lastIndex = SrchRng.Rows.Count

For i = lastIndex To 1 Step -1
    For Each Cell In SrchRng.Rows(i).Cells
        If Cell.Value = SrchStr Then
            Cell.EntireRow.Delete
            Exit For
        End If
    Next
Next

ActiveWorkbook.Close SaveChanges:=True

3
投票

你需要从底部删除。这是因为当你删除一行时,下面的行向上移动,这意味着它需要检查的“下一个”单元格将在同一行而不是下一行。从头到尾工作可以很好地解决这个问题。

Dim i as Long
With SrchRng
    For i = .Cells.Count To 1 Step -1
        If .Cells(i).Value = SrchStr Then
        .Cells(i).EntireRow.Delete
        End If
    Next 
End With
© www.soinside.com 2019 - 2024. All rights reserved.