Search code examples
excelvbado-loops

How can I limit the number of loops in a Do While loop?


So I've written a function that that uses text-box inputs to search for corresponding values in another sheet. The problem is if it doesn't find a match it goes into an infinite loop. Can I limit the loops so it doesn't crash? If there is another solution rather than limiting loops, I'm all ears. Here's what I'm working with:

Function Most_Recent_Deployment(Label1 As String, Label2 As String, Label3 As String) As Long
    Dim all_rows As Range
    Dim row As Range
    Dim LastCell As Range
    Dim LastCellRowNumber As Long
    Set LastCell = Sheet7.Cells(Sheet7.Rows.Count, "A").End(xlDown).End(xlUp)
    LastCellRowNumber = LastCell.row + 1
    Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)
    Do While row.row > 1

        If (Sheet7.Cells(row.row, 2).Text = Label2) And (Sheet7.Cells(row.row, 3).Text = Label3) Then
            Most_Recent_Deployment = row.row
            Exit Function
        End If
        LastCellRowNumber = row.row
        Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)

    Loop
    Most_Recent_Deployment = 0
End Function

Solution

  • You could add an 'AND' piece to your 'Do While' loop with a counter inside the loop that will indicate when you have reached the end of data in your spreadsheet.

    Something like:

    dim counter as integer    
    Do While row.row > 1 and counter > worksheetfunction.counta(sheet7.range("A:A")
    
        If (Sheet7.Cells(row.row, 2).Text = Label2) And (Sheet7.Cells(row.row, 3).Text = Label3) Then
            Most_Recent_Deployment = row.row
            Exit Function
        End If
        LastCellRowNumber = row.row
        Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)
        coutner=counter+1
    
    Loop
    

    I mean, yes, it's a bit basic, but I think think that it will do the job you're looking for without having to change your code too much. Hope it helps.

    Edit:

    LastCellRowNumber=row.row
    temp2=temp1
    temp1=LastCellRowNumber
    
    Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)
    
    if row.row=temp1 and temp1=temp2 then
        exit do
    end if