j = 0.2
For i = -3 To 3 Step j
Debug.Assert i <> 3
Debug.Print i
Next
End Sub
If I run this code the last step 3 will not run.
If I modify I to 2.5 it does. What's going on?
This is a common side-effect of computer binary arithmetic. Most
numbers with decimal fractions cannot be represented exactly.
Consequently, results of even simple arithmetic might not be "exact",
i.e. match the internal representation of the equivalent constant.
For example, the following will output False(!) [1]:
Debug.Print 10.1 - 10 = 0.1
If the step is ostensibly non-integer, it is best to use integers for
loop controls, then compute the floating-point value within the loop.
For example, instead of i = -3.0 to 3.0 step 0.2, do:
For x = -30 To 30 Step 2: i = x / 10
PS: For broader participation, you might want to post future
inquiries using the MS Answers Forums at
http://social.answers.microsoft.com/Forums/en-US/category/officeexcel.
It's not that I like that forum. It's just that MS has ceased to
support the Usenet newsgroups. Hence, participation here is limited
to the sites that share a common newsgroup mirror, which is no longer
centralized at MS.
-----
Endnotes
[1] 10.1 is exactly
10.0999999999999,996447286321199499070644378662109375
10.1-10 is exactly
0.0999999999999996,447286321199499070644378662109375
0.1 is exactly
0.100000000000000,0055511151231257827021181583404541015625