【发布时间】:2016-03-28 15:53:11
【问题描述】:
下面的代码按预期工作得很好,唯一的缺点是它很慢,因为我使用它来搜索子字符串的所有实例并删除整个工作簿的任何单元格中的整行。
目标很简单,如果在任何单元格字符串中找到输入的字符串,只需删除整行
Dim wo As Worksheet, ws As Worksheet
Dim I As Long, j As Long, m As Long
Dim toFind As String, testStr As String
Dim pos As Long
Dim lstRow As Long, cutRow As Long
Dim WS_Count As Integer
Dim Cell As Range
Option Compare Text
Option Explicit
Sub SearchDelete()
toFind = InputBox("Enter the substring you want to search for.", "Welcome", "AAAA")
toFind = Trim(toFind)
j = 0
If toFind = "" Then
MsgBox "Empty String Entered.Exiting Sub Now."
Exit Sub
Else
WS_Count = ActiveWorkbook.Worksheets.Count
'Begin the loop.
For I = 1 To WS_Count
Label1:
For Each Cell In Worksheets(I).UsedRange.Cells
If Trim(Cell.Text) <> "" Then
pos = 0
pos = InStr(1, Trim(Cell.Text), toFind, vbTextCompare)
If pos > 0 Then 'match Found'
cutRow = Cell.Row
Worksheets(I).Rows(cutRow).EntireRow.Delete
j = j + 1
GoTo Label1
Else: End If
Else: End If
Next Cell
Next I
End If
MsgBox "Total " & j & " Rows were deleted!"
End Sub
【问题讨论】:
-
试试
range.find?编辑:但这可能更适合代码审查。 -
一个非常简单的提高速度的方法是在您的子目录的开头使用
Application.ScreenUpdating = False,在您的子目录的末尾使用Application.ScreenUpdating = True。这只会在您的 sub 结束时更新屏幕,而不是在每次删除一行时更新。 -
@findwindow 我会这样做,但我不知道
Range.Find是否会返回找到的部分匹配的所有行号以及如何在循环中使用它?在这种情况下,任何实施示例都会对我有所帮助! -
有
range.findnext -
@newguy
Range.Find将找到您搜索的任何内容的第一个实例。Range.FindNext将返回下一个匹配的单元格并继续这样做,直到范围内没有更多单元格与搜索匹配,此时它将返回Nothing
标签: performance vba excel search