[英]Excel VBA - How to stop Find Function when criteria met
我在循環中使用以下代碼行:
Set foundCell = Cells.Find(What:=pasteValue, After:=ActiveCell, LookIn:=xlValues, MatchCase:=False, SearchFormat:=False)
它工作正常,但是由於文檔的大小,它非常慢。 即使在第一行滿足條件,“查找”功能也會一直搜索到EOF,並且我正在一個非常大的表上運行它。 有沒有辦法在第一個滿足條件時停止“查找”功能?
謝謝!
編輯:
Sub Finding()
Dim foundCell As Range
Dim pasteValue As String
Dim MyDataObj As MSForms.DataObject
Set MyDataObj = New MSForms.DataObject
Windows("Book3").Activate
Selection.Copy
Windows("Book1").Activate
MyDataObj.GetFromClipboard
pasteValue = MyDataObj.GetText(1)
pasteValue = Trim(Replace(pasteValue, Chr(13) & Chr(10), ""))
Do Until IsEmpty(pasteValue) Or pasteValue = ""
Set foundCell = Cells.Find(What:=pasteValue, After:=ActiveCell, LookIn:=xlValues, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
ActiveCell.EntireRow.Delete
Windows("Book3").Activate
Selection.Offset(0, 4).Select
ActiveCell.Value = "Y"
Selection.Offset(1, -4).Select
End If
Windows("Book3").Activate
Selection.Offset(1, 0).Select
Selection.Copy
Windows("Book1").Activate
MyDataObj.GetFromClipboard
pasteValue = MyDataObj.GetText(1)
pasteValue = Trim(Replace(pasteValue, Chr(13) & Chr(10), ""))
Loop
End Sub
我假設您在with或for循環中運行find函數,然后如果結果不為空,則可以退出sub。 如果希望宏從另一個特定點運行,則可以使用goto->
If Not foundCell Is Nothing Then
exit sub
要么
If Not foundCell Is Nothing Then
GoTo LineNumber or Identifier
這個問題對我來說不是很清楚,但可以在要停止循環的位置添加Exit Do
。 如果我理解正確,則應在匹配搜索並刪除行后的If
語句中:
If Not foundCell Is Nothing Then
ActiveCell.EntireRow.Delete
Windows("Book3").Activate
Selection.Offset(0, 4).Select
ActiveCell.Value = "Y"
Selection.Offset(1, -4).Select
Exit Do 'Exit the loop
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.