Home > Software design >  How to do an infinite loop with Do While VBA
How to do an infinite loop with Do While VBA

Time:08-03

I have a column in excel with values and I would like that when the code run through all the cells it starts again, at the cell A2.

The code works smooth, I'm only having trouble to keep the loop going on.

Sub Loopall()
    i = 2
    
    
    Do While Cells(i, 1) <> ""
    
        Range("A2").Select
        Session.FindById("wnd[0]").maximize
        Session.FindById("wnd[0]/tbar[0]/okcd").Text = "fbl5n"
        Session.FindById("wnd[0]").sendVKey 0
        Session.FindById("wnd[0]/usr/ctxtDD_KUNNR-LOW").Text = Cells(i, 1)
        Session.FindById("wnd[0]").sendVKey 8
        Application.Wait (Now   TimeValue("0:00:02"))
        Session.FindById("wnd[0]").sendVKey 3
        
        i = i   1
        
            
    If Cells(i, 1) <> "" Then
        i = 2
    Else
        End If
        
        
        Loop
End sub

I've tried to place the if statement inside the loop, but then the code only reads the first cell. When placing the if outside the loop the code doesn't start the loop again when the cells are empty.

CodePudding user response:

If Cells(i, 1) <> "" Then is restarting your loop when the cell is not blank, which seems like the opposite of what you'd want?

Sub Loopall()
    Const START_ROW as Long = 2
    i = START_ROW 
    
    Do 
        Session.FindById("wnd[0]").maximize
        Session.FindById("wnd[0]/tbar[0]/okcd").Text = "fbl5n"
        Session.FindById("wnd[0]").sendVKey 0
        Session.FindById("wnd[0]/usr/ctxtDD_KUNNR-LOW").Text = Cells(i, 1)
        Session.FindById("wnd[0]").sendVKey 8
        Application.Wait (Now   TimeValue("0:00:02"))
        Session.FindById("wnd[0]").sendVKey 3
        i = i   1
        If Len(Cells(i, 1)) = 0 Then i = START_ROW 
    Loop
End sub

Probably want to add in some way to escape the loop...

  • Related