2

I am writing a loop in VBA for excel, and I would like to loop through a sequence of decimal numbers, rather than integers.

For example:

For i = 1 To 10
    'Do something
Next i

But rather than incrementibg by 1, I would like to increment by 0.5 (or perhaps 5, or really any number other than 1).

Zach
  • 29,791
  • 35
  • 142
  • 201
  • 1
    did you even look at the help file? (`For counter = start To end [Step step]`) – chris neilsen Oct 03 '11 at 19:52
  • @chris neilsen I did not. When I clicked the `help` menu and searched for `for loop` I got a lot of irrelevant information. – Zach Oct 03 '11 at 19:55

3 Answers3

8
Dim i as Single

For i = 1 To 10 Step 0.5
    '
Next

But note you can get some unwanted numbers because of the floating numbers not being precise.

Community
  • 1
  • 1
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • @Zach Because I like to declare my variables, and since we want a floating point variable, it's goint to be either `Single` or `Double`. If you prefer `Variant`s by default, just ignore that. – GSerg Oct 03 '11 at 19:57
3
Sub a()
  For i = 1 To 10 Step 0.1
   Debug.Print i
  Next i
End Sub
Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190
0

You can use a decimal generator.

def loop_decimal(loop_start_value, loop_stop_value, loop_step_value = 1):

# Input arguments error check
if not loop_step_value:
    loop_step_value = 1

loop_start_value = decimal.Decimal(str(loop_start_value))
loop_step_value = decimal.Decimal(str(loop_step_value))
loop_stop_value = decimal.Decimal(str(loop_stop_value))

# Case: loop_step_value > 0
if loop_step_value > 0:
    while loop_start_value < loop_stop_value:
        yield loop_start_value
        loop_start_value += loop_step_value

# Case: loop_step_value < 0
else:
    while loop_start_value > loop_stop_value:
        yield loop_start_value
        loop_start_value += loop_step_value

Calling the generator produces:

for x in (loop_decimal(0.1, 0.9, 0.1)):
    print(x)

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

To convert a float into an exact decimal value, use the str() in the decimal.Decimal() command. decimal.Decimal(str( float_value ))

If you pass None or 0.0 to the step argument, the default value of 1 will be used.

This works for incrementing and decrementing loops.

cinsight
  • 1
  • 1