PDA

View Full Version : [SOLVED:] Subtracting Single and Formular values



JannikR13
07-26-2023, 07:58 PM
Good day,
I was trying to subract two values with vba and write it into a specific cell.

Value1 is a Single value with one decimal place from a userform textbox (e.g. 1200.4)
Value2 is a value coming from a formular on a spreadsheet (e.g. H1 + H2 + H3 = 1100.5)

As soon as I subtract Value 2 from Value 1 the outcome is a single with a lot of decimal places like:
1200.6 - 1100.5 = 100.100567

I can't explain myself how I get rid of that weird ending... I already tried to store both Value 1 and 2 as a Single and subtract then...
Till the subtraction the MsgBox for each value is only a one decimal place number as it supposed to be!

Every help is well appreciated. Thank you all!

June7
07-26-2023, 10:31 PM
I just get 100.1 in cell.

Want to provide workbook for analysis? Follow instructions at bottom of my post.

georgiboy
07-26-2023, 10:33 PM
Welcome to the forum,

You can use the round function demonstrated below:

Sub test()
Dim val1 As Double
Dim val2 As Double

val1 = 1200.41123423
val2 = 1100.5112346

MsgBox val1 + val2 ' not rounded
MsgBox Round(val1 + val2, 1) ' rounded to one decimal place
End Sub

JannikR13
07-27-2023, 08:09 PM
Hey,
thanksfor the fast replies.
I cannot share the workbook because it's more a whole program then small workbook and contains company values...

That's the line that causes problem:

hour_extention = done_TTIS - TTIS

hours_extention as Single
done_TTIS as Single 'from userform textbox as one decimal
TTIS as Single = ThisWorkbook.Sheets(p_plate).Cells(row_maintenance, 6) is a formular H3+G3+3 and all numbers only contain one decimal

If I stop the code just after this line it shows me:
done_TTIS = 8188.4
TTIS = 8187.3
soooo I expect the value 1.1 (!) and not 1.100098

I kinda get the feeling that there is a rest value stored somewhere but i cnt find it... All numbers are only one decimal.

JannikR13
07-27-2023, 08:38 PM
Hey all,
I figured out that even 0.2 as Single is stored a infinitely repeating binary fraction with a stored value of 0.20000001.
Somehow declaring all variables as Variants and putting a CDec() infront of every value declaration helped...
Not too sure if thats the proper way for this problem but it gives me a one decimal result.

Aussiebear
07-28-2023, 12:22 AM
Well Done Jannik13