Your issue stems from the fact that Rnd
returns a datatype Single
. See here
When Round
is passed numdecimalplaces
> 0 and a Single
value, it honors that data type, and returns a Single
. WorksheetFunction.Round
does not: it returns a double. (If Round
is passed a Double
, it returns a Double
)
This does not matter within VBA itself (see image of Watch Window below for evidence)
The issue occurs when the values are placed in Excel Cells, and the are converted to Excel's cell data type. The conversion of Single
incurs Floating point precision issues
To fix this, your code could be
Cells(1, 2) = Round(CDbl(Rnd(-1)), 4)

To place the result in Cell(1, 4)
as text you can use
Cells(1, 4) = "'" & Format(Cells(1, 2), "0.0000")
or
Cells(1, 4) = "'" & Cells(1, 2).Text
Note: the "'" &
is necassary because Excel recognises the string as a number, and "helpfully" converts it back to number