1

Sorry for not giving more detailed title, but it is because of this special case. My google search did not give me any similar topic.

The following simple code should give a series of numbers from 0.1 to 10 with step 0.1 (I hoped at least) in column A:

Cells(1, 1) = 0.1
For i = 2 To 100
Cells(i, 1) = Cells(i - 1, 1) + 0.1
Next i

Until 5.9 it works well, but after that the result is not as expected:

instead of 6 I get 5,99999999999999

instead of 6.1 I get 6,09999999999999

instead of 6.2 I get 6,29999999999999

...

Could anyone explain what is wrong with the code or why I get this result?

Thanks!

oort
  • 11
  • 1
  • 1
    you may want to see this: http://stackoverflow.com/questions/22322822/why-is-134-605100-not-equal-13460-5-in-vba-access/22323581#22323581 – Dmitry Pavliv Mar 31 '14 at 09:35
  • 1
    Thanks, in your link i found this http://support.microsoft.com/kb/78113 which answered my question. – oort Mar 31 '14 at 10:05

1 Answers1

1

Or simply this?

Sub Sample()
    Dim i As Long

    For i = 1 To 100
        '~~> Change Sheet1 to respective sheet
        ThisWorkbook.Sheets("Sheet1").Cells(i, 1) = i * 0.1
    Next i
End Sub

Or like this

Sub Sample()
    '~~> Change Sheet1 to respective sheet
    With ThisWorkbook.Sheets("Sheet1").Range("A1:A100")
        .Formula = "=Row()*.1"
        .Value = .Value
    End With
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • Originally I was looking for why I get wrong numbers, not another solution, but of course thank for your effort and answer! – oort Mar 31 '14 at 10:07
  • Yes I know but since @simoco already gave you a link which explains that, I simply gave you an alternative :) – Siddharth Rout Mar 31 '14 at 10:08
  • @SiddharthRout second `Sample()` a cool idea +1 :) actually the first one too :) –  Mar 31 '14 at 10:11