2016-05-03 182 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爲真。

編輯:哦好吧,其他人更快找到它:)