2017-09-16 61 views
0

如果值等於我正在查找的值,或者如果該行等於我正在查找的行,我試圖退出函數。退出函數不工作 - VBA

但每次我使用Exit Function,它都不起作用。如果我將其替換爲End Function它告訴我,我沒有End If if If語句。我迷路了。

Function recursion(whereItEnds As Integer, lookingFor As Variant, currentMarker As Range, I As Integer, wsEverything As Worksheet) As Integer 
    Dim col As Integer 
    Dim newMarker As String 
    newMarker = currentMarker.Value 
    Dim currentMarker1 As Range 
    recursion = 2 
    col = 2 
    If (StrComp(lookingFor, newMarker, vbTextCompare) = 0) Then 
     Exit Function 
    End If 

    While (IsEmpty(wsEverything.Cells(col, "B").Value) = False) 
     If (StrComp(wsEverything.Cells(col, "B").Value, newMarker, vbTextCompare) = 0) Then 
      wsEverything.Cells.Range("A" & col, "F" & col).Copy 
      Worksheets("Review").Cells.Range("A" & I).PasteSpecial 
      Worksheets("Review").Cells.Range("G" & I).Value = col 
      I = I + 1 
      Set currentMarker1 = wsEverything.Cells(col, "E") 

      If (col = whereItEnds) Then 
       Exit Function 
      End If 
      recursion = recursion(whereItEnds, lookingFor, currentMarker1, I, wsEverything) 
     End If 
     col = col + 1 
    Wend 
End Function 

我幾乎完全沒有想法,爲什麼都不起作用。

編輯:它擊中的if語句,它進入這些代碼。但是在調試時,它會觸及「退出功能」,但它會繼續。我只是想要它結束聲明。這是將數據從另一張長表中拉出並放在另一張表上。它正在檢查孩子的父母循環錯誤。未來的父母依賴於最初依賴它的孩子。

+0

你能提供的數據中發現的邏輯,你說這是不合作?退出功能應該工作 – Sgdva

+0

https://imgur.com/a/SOP4Q – mysizebarbi

+1

我還是有點迷路,我沒有看到函數應該如何表現以及爲什麼行爲不如預期。你可以嘗試用一行來編輯問題嗎?例如:「這就是我所擁有的...而這正是我所期望的......」這種指導? – Sgdva

回答

0

這是你想要的嗎?

之前(Sheet1中):

Sheet1


後(審查表):

ReviewSheet


Option Explicit 

Public Sub TestRecursion() 

    Dim result As Variant, ws As Worksheet 

    Set ws = Sheet1 

    result = Recursion(ws.Cells(2, 8), ws.Cells(2, 2), ws.Cells(2, 5), 2, ws) 

End Sub 

Public Function Recursion(ByVal whereItEnds As Long, lookingFor As Variant, _ 
          ByRef currentMarker As Range, ByVal i As Long, _ 
          ByRef wsEverything As Worksheet) As Long 

    Dim col As Long, newMarker As String, currentMarker1 As Range 

    newMarker = currentMarker.Value 
    Recursion = 2 
    col = 2 

    If StrComp(lookingFor, newMarker, vbTextCompare) = 0 Then Exit Function 

    While Len(wsEverything.Cells(col, "B").Value2) > 0 

     If StrComp(wsEverything.Cells(col, "B").Value2, newMarker, vbTextCompare) = 0 Then 

      wsEverything.Cells.Range("A" & col, "F" & col).Copy 
      Worksheets("Review").Cells.Range("A" & i).PasteSpecial 
      Worksheets("Review").Cells.Range("G" & i).Value = col 
      i = i + 1 

      Set currentMarker1 = wsEverything.Cells(col, "E") 

      If col = whereItEnds Then Exit Function 

      Recursion = Recursion(whereItEnds, lookingFor, currentMarker1, i, wsEverything) 
     End If 
     col = col + 1 
    Wend 
End Function 

如果是這樣,你可以提供更多的上下文解釋預期的結果

可能是一個不太複雜的解決方案可以爲這個

+1

'(True)'的表達式將等於'真',所以括號表達式不會成爲問題。 (就我個人而言,我討厭在那裏看到他們,但它不會造成問題。) – YowE3K