VBA Override Error 6 Overflow (Create Infinite Loop)?

215 views Asked by At

I want an infinite loop in VBA (I have done this in Java and C++ before). I keep getting "Overflow" with the VBCritical red circle X.

Here is my code. The Error <>0 is supposed to recognize the overflow and ignore it to let the macro continue looping infinitely, but I still get the overflow VBCritical MsgBox.

I want to print the numbers out in column A. This part works right now: it prints "2".

Here is my code:

Sub InfiniteLoop()
Dim counter As Integer
counter = 1
Do While counter > 0
    counter = counter + 1

Loop
If Error <> 0 Then
    Do While counter > 0
    counter = counter + 1
    Cells(counter, "A").Value = counter
    Loop
End If
End Sub
2

There are 2 answers

1
99moorem On

Could you not just do this? and not increment counter at all?

Sub InfiniteLoop()
Dim counter As Integer
counter = 1
Do While counter > 0

Loop
End Sub
0
Alex K. On

For a loop that will run from 0..32767 repeatedly (the max an integer can hold)

Do While True
    counter = (counter + 1) Mod 32768
    ...
Loop

If you dim counter as a Long the maximum will be 2147483647.