Home » excel » excel – Loop won't stop, leads to overflow

excel – Loop won't stop, leads to overflow

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am new to VBA, this seems simple, but when I run the code it continues to create random numbers until it finally gives me an overflow message. I can tell it can read the total, but I don’t know why it won’t stop.

Dim i As Integer
Dim total As Integer
i = 1
total = Range("C1")

Do While total < 180
    Cells(i, 1).Value = Int((10 - 3 + 1) * Rnd + 3)
    i = i + 1
Loop

Thanks for any help.

How to&Answers:

I am assuming that C1 has some type of a sum or something that is growing while the VBA is populating numbers if that is the case then you just need to re-evaluate total at the end of each loop. This was working for me…

Dim i As Integer
Dim total As Integer
i = 1
total = Range("C1")

Do While total < 180
    Cells(i, 1).Value = Int((10 - 3 + 1) * Rnd + 3)
    i = i + 1
    Application.Calculate 'Only needed if manual calculation is on
    total = Range("C1")
Loop

Answer:

I think that you are using the wrong variable for your while loop. Do you mean total < 180 or i < 180?