Goal: Assign values to variables and get the product of these variables
Problem: VBA returns incorrect result
I've been using VBA for well over a decade now and this is the first time I have been unable to find an answer or solution to this online. Hope you can help!
For reference, this is for the computation of wages.
How it's set up:
- variables declared as PUBLIC with data type SINGLE
Public REGHOURSRATE As Single
Public REGHOURSCOUNT As Single
Public REGHOURSAMOUNT As Single
Public HourlyRate As Single
- values assigned to these variables by referencing cells in excel. Resulting assigned values (verified in debug) are as follows
REGHOURSRATE = 1
REGHOURSCOUNT = 57.5
HOURLYRATE = 673.47
- variables multiplied
REGHOURSAMOUNT = REGHOURSCOUNT * REGHOURSRATE * HourlyRate
The correct product is 38,724.525 but strangely, VBA evaluates this as 38,724.52!
This results in minor variances which, while insignificant, cause accounting concerns.
What I've tried:
- using different data types (DOUBLE, VARIANT). These also yield the wrong result (38,724.5233154297)
- Multiplying the variables with decimals with a factor to turn them into whole numbers. Getting the product of the variables, and then dividing the product by the factors. ends up with the same incorrect result
- using ROUND and worksheetfunction.round to 2 decimal places. ends with the same incorrect result because it only had 2 decimal places to begin with
Am I doing anything wrong here? Or is this simply how VBA is set up?
Thank you.
EDIT: a friendly member of the community directed me to clues to the answer on a different page. what worked for me was to set the data type as CURRENCY.