While working on a function in VBA, I noticed that sometimes during my tests I would get different results from when I ran the same function with different parameters. I wrote the following sub to try to figure out what was going on.
When the for-loop
is executed with bounds in the thousandths place, it loops through the for
statements 3 times, as I expect it to. Here, the immediate window generously prints a "3" for me:
Const vStart = 0.001
Const vStep = 0.001
Const vStop = 0.003
Sub LoopThru()
Dim myVar As Double
Dim counter As Integer
For myVar = vStart To vStop Step vStep
counter = counter + 1
Next myVar
Debug.Print counter
End Sub
When I reduce the bounds and step by a magnitude, however, the for-loop
only executes the for
statements twice.
Const vStart = 0.0001
Const vStep = 0.0001
Const vStop = 0.0003
Sub LoopThru()
Dim myVar As Double
Dim counter As Integer
For myVar = vStart To vStop Step vStep
counter = counter + 1
Next myVar
Debug.Print counter
End Sub
In my actual project, I'm creating a large 3D array of values as a lookup table. Since the first dimension of the array has to be generated using Solver, I will greatly reduce the application's runtime by creating this lookup table instead of having to recalculate using Solver over and over again while the application is running.
Since it is a 3D array, there are 3 nested for loops, the second of which may range through values from the hundred-thousandths to the tenths place.
Perhaps a do-while loop
is more fitting for this situation - in fact I'm rewriting the code now to use a while loop instead. Or a conditional set of for-loops
. Either way, I would like to know the best solution for this problem, as well as why there is a difference in the number of loops executed depending on the magnitude of the bounds in these for loops
.