Excel VBA无限循环

时间:2019-04-23 14:30:18

标签: excel vba loops

我对VBA还是很陌生

当我期望搜索在到达最后一次出现时停止时,下面的代码将导致无限循环。 (我在当前工作区中有2个包含>>>的单元格。)谁能告诉我怎么了?

Set titles = Range("A1:A1")
Dim bEndLoop As Boolean
bEndLoop = False
' lookup part of content in search
mCurLookup = xlPart
With possibleTitles
    Do While Not bEndLoop
        Set titles = .Find(What:=">>>", After:=ActiveCell)
        If Not titles Is Nothing Then
               Application.Goto titles, True
                MsgBox (titles.Address)
                titles.Activate
            Else
                MsgBox "Nothing found"
                bEndLoop = True
            End If
    ' Set t2 = titles(1).CurrentRegion
    Loop
End With

2 个答案:

答案 0 :(得分:2)

猜测答案应该像这样(来自https://docs.microsoft.com/en-us/office/vba/api/excel.range.findnext) 我不喜欢由两部分组成的查找,然后是FindNext(难道我只有一个循环吗?),但是如果这是官方的方法,我想最好还是坚持下去。

With Worksheets(1).Range("a1:a500")
     Set c = .Find(2, lookin:=xlValues)
     If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Value = 5
            Set c = .FindNext(c)
            If c is Nothing Then Exit Do
        Loop While c.Address <> firstAddress
      End If
End With

答案 1 :(得分:2)

下面是使用Find FindNext方法的代码示例。与使用For等效循环

相比,使用此方法要快得多
Dim titles As Range
Dim possibleTitles As Range
Dim firstAddress As String

Set possibleTitles = ActiveSheet.Range("A:A")

With possibleTitles
    Set titles = .Find(what:=">>>")
    If Not titles Is Nothing Then
        firstAddress = titles.Address

        Do
            MsgBox titles.Address
            Set titles = .FindNext(titles)
        Loop Until firstAddress = titles.Address
    End If
End With
相关问题