How to exit the VBA loop

Asked

Viewed 51 times

1

Hi guys vcs can help me, I’m running two loops, but I need to stop running the loop when the rows2 variable equals 38. I’m a beginner in programming. I don’t know how you solve.

Sub qty()
    
    rows1 = 2
    rows2 = 28
    
    contador = 0
    
    While linhas2 < 38
        
        While Sheets("teste").Cells(rows1, 2) <> ""
        
        
            If Sheets("teste").Cells(rows2, 1) = Sheets("teste").Cells(Rows, 1) Then
            
                Sheets("teste").Cells(rows1, 4) = Sheets("teste").Cells(Rows, 4) + Sheets("teste").Cells(rows2, 4)
                rows2 = rows2 + 1
                rows1 = rows1 + 1
                
            Else
                
                rows2 = rows2 + 1
            
            
            End If
        
        Wend
    
        
    Wend
    

End Sub

1 answer

0


You can do this by just adding a variable continuar then using it as a criterion for the While and updating the value of the variable at each loop.

To better understand, check below all the places where I included this variable continuar.

Sub qty()

    rows1 = 2
    rows2 = 28
    
    contador = 0
    continuar = True
    
    While linhas2 < 38 And continuar
        
        While Sheets("teste").Cells(rows1, 2) <> "" And continuar
        
            If Sheets("teste").Cells(rows2, 1) = Sheets("teste").Cells(Rows, 1) Then
            
                Sheets("teste").Cells(rows1, 4) = Sheets("teste").Cells(Rows, 4) + Sheets("teste").Cells(rows2, 4)
                rows2 = rows2 + 1
                rows1 = rows1 + 1
                
            Else
                
                rows2 = rows2 + 1
            
            
            End If
            
            continuar = rows2 < 38
            
        Wend
        
    Wend
    

End Sub
  • opa, vlw partner. Thank you very much! Helped me a lot!!

  • Cool! Having this answer helped you solve the problem, mark it as accepted to close the question. Abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.