Excel VBA - 如何在满足条件时停止查找功能

时间:2015-01-23 12:14:19

标签: excel vba excel-vba find

我在循环中使用这行代码:

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

2 个答案:

答案 0 :(得分:0)

我假设您在with或for循环中运行find函数,那么如果结果不为空,则可以退出sub。如果您希望宏从另一个特定点运行,那么您可以使用goto - >

If Not foundCell Is Nothing Then
    exit sub

If Not foundCell Is Nothing Then
    GoTo LineNumber or Identifier

答案 1 :(得分:0)

这个问题对我来说并不是很清楚,但是在你想要停止循环的地方添加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
相关问题