Problem with decimals in VBA code

chiidzzz

New Member
Joined
Sep 2, 2012
Messages
32
Hi, there is something that I can't figure out in this code,
Code:
Sub test()
Dim i As Integer
Dim diff05 As Double
diff05 = 0.8
        For i = 2 To 4
            If Sheet1.Cells(i, 2).Value >= diff05 And Sheet1.Cells(i, 2).Value < diff05 + 0.05 Then
                    Sheet1.Cells(i, 11) = Sheet1.Cells(i, 2).Offset(0, 6)
            End If
       Next


End Sub
In row 3, the value of cell(3,2) is 0.85
Logically, the code should read sheet1.cells(3,2)>= diff05 "as true" and sheet1.cells(3,2)< diff05 + 0.05 "as false"
But it is returning sheet1.cells(3,2)< diff05 + 0.05 "as true"
If I remove diff05+0.05 and I just put 0.85, it reads "false", what may be the problem?
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
The problem is your order of operations. You need parentheses in it like this:
Code:
If Sheet1.Cells(i, 2).Value >= diff05 And Sheet1.Cells(i, 2).Value < (diff05 + 0.05) Then
Otherwise, if will compare the value in Cells(i,2) to diff05, and after it does that comparison, then it will add 0.05.
That is not what you want. You want it to compare the value to diff05 + 0.05. So you need to use parentheses around that addition.
 
Upvote 0
Incorrect, comparison operators are already treated last in the chain. The problem here is an IEE rounding error.
Code:
Sheet1.Cells(i, 2).Value-(diff05+0.05)
yields this value: -1.11022302462516E-16
 
Upvote 0
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,182
Members
453,021
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top