In cell B2 I have variable with the value 297.123 before doing calculations In VBA I would like to round this to 297.12. See the code below as to what I have tried. Both have evaluated fuel to 297. What am I doing wrong?
Dim fuel As Integer
Dim linecount As Long
linecount2 = 2
fuel = Format(ws.Cells(linecount2, 2), "0.00")
fuel = Round(ws.Cells(linecount2, 2), 2)
VBA Round function uses “round to even” logic. If the number you are trying to round has the last digit after decimal >= 0.6, VBA Round function rounds it up (Round UP). If the number you are trying to round have the last digit after decimal <= 0.4, it rounds it down (Round Down).
For example: If you wanted to use the number from cell A2 and have it rounded to two decimal places, you could enter =ROUND(A2,2). Or, if you want to divide cell B2 by cell C2, and round the result to 3 decimals, you would use =ROUND(B2/C2,3).
Change Dim fuel As Long
-> Dim fuel As Double
And both of your formula will work.
Dim fuel As Double
Dim linecount2 As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
linecount2 = 2
fuel = Format(ws.Cells(linecount2, 2), "0.00")
fuel = Round(ws.Cells(linecount2, 2), 2)
fuel = WorksheetFunction.Round(ws.Cells(linecount2, 2), 2) '@suggested by T.M.
MsgBox "try"
End Sub
Dim Long
is for Integers (whole numbers)Dim Double
is for numbers with decimal points (can store more decimal
points, up to 15 digits)Dim Single
is for numbers with decimal points (store less decimal
points, up to 7 digits)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With