2016-05-03 181 views
-1

我正在学习VBA,并在使用.FindNext方法时卡住了循环。我尝试了很多方法来修复循环,但是我做了什么最终会陷入无限循环,并且您知道在Excel中编写代码时会有多恼人。请,如果任何人可以修复我的代码将是一个很好的帮助!无限循环调试在VBA中使用.FindNext方法

Private Sub cbGO_Click() 

    Dim ws As Worksheet, OutputWs As Worksheet 
    Dim rFound As Range 
    Dim strName As String 
    Dim count As Long, LastRow As Long 
    Dim IsValueFound As Boolean 


    IsValueFound = False 
    Set OutputWs = Worksheets("Summary") '---->change the sheet name as required 
    LastRow = OutputWs.Cells(Rows.count, "A").End(xlUp).Row 

    On Error Resume Next 
    strName = ComboBox1.Value 
    If strName = "" Then Exit Sub 
    For Each ws In Worksheets 

     If ws.Name <> "Lists" And ws.Name <> "Summary" Then 

      With ws.UsedRange 

       Set rFound = .Find(What:=strName, LookAt:=xlWhole) 
       If Not rFound Is Nothing Then 
        firstAddress = rFound.Address 

        Do 

        rFound.EntireRow.Cells(1, "B").Resize(1, 4).Copy 
        OutputWs.Cells(LastRow + 1, 1).PasteSpecial xlPasteAll 
        Application.CutCopyMode = False 
        LastRow = LastRow + 1 
        Set rFound = .FindNext(rFound) 

        Loop While Not rFound Is Nothing And rFound.Address <> fristAddress 

       End If 
      End With 
     End If 
    Next ws 
    On Error GoTo 0 
    If IsValueFound Then 
     OutputWs.Select 
     MsgBox "Result pasted to Sheet Output" 
    Else 
     MsgBox "Value not found" 
    End If 

End Sub 
+3

拼写错误'fristAddress'和'firstAddress'。 (使用'Option Explicit'并声明_all_变量来避免这种类型的错误) –

+0

击败我!通过一秒钟,还有一些括号,以确保该组合/优先级不是,而且是你真正想要的。但我怀疑拼写错误是个问题。 – NanoTera

+0

对不起,但我不明白。我宣布了fristAdress,但仍然无法正常工作。任何人都可以通过编写代码来检查它吗? –

回答

0

你需要写“firstAddress”而不是“fristAddress”。 :D

Loop While Not rFound Is Nothing And rFound.Address <> fristAddress 

修复这个错字后,它应该工作。

另一个注意:你还没有设置IsValueFound为真。

编辑:哦好吧,其他人更快找到它:)