我在下面的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
答案 0 :(得分: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
答案 1 :(得分: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