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