Home |
Search |
Today's Posts |
#7
![]()
Posted to microsoft.public.excel.programming
|
|||
|
|||
![]()
On Jul 14, 11:43*am, VTengineer
wrote: Pasted below is an excerpt from VBA code I'm working on. For some reason it will not properly execute this logic. When StopLong = 0.085 it cannot make the first If..then logical comparison. Passes right over it. Have been using VBA for 10years and have no clue whats going on. For BuyLim = 0.001 To 0.07 Step 0.002 For GainSell = 0.001 To 0.08 Step 0.003 For StopLong = 0.001 To 0.09 Step 0.003 If StopLong = 0.085 Then * * If GainSell = 0.001 Then * * * * If BuyLim = 0.001 Then * * * * * * weird = False * * * * End If * * End If End If Next Next Next Another approach: If you want to use equality and StopLength, etc. are variants you can use the CDec() function to make VBA treat these as decimal numbers. The round-off error that prevents StopLong from reaching 0.085 exactly is due to the fact that singles and doubles are in base 2 and that many numbers which have a finite decimal expanson in base 10 (e.g. 0.003 or 0.085) have an infinite (though repeating) decimal exapansion in base 2 hence can't be precisely represented by a single/double. CDec uses (I believe) base 10 in its representation of numbers, hence no round off error would build in this case. In any event, the following code fragment works: Sub test() Dim StopLong As Variant For StopLong = CDec(0.001) To 0.09 Step 0.003 If StopLong = 0.085 Then MsgBox "This works" Next End Sub The problems with this approach a 1) Variants and decimal subtypes are less efficient 2) Variants might switch sub-types unexpectedly, thus leading to difficult to maintain code. On the other hand, if you know that you are dealing with decimal numbers there might be a gain in readability in writing the code in such a way that comparisons can be expressed in a straightforward manner. -scattered |
Thread Tools | Search this Thread |
Display Modes | |
|
|
![]() |
||||
Thread | Forum | |||
Logical operators not working with text??? | Excel Worksheet Functions | |||
Multiple Logical Conditions With Date and String Comparison Not wo | Excel Worksheet Functions | |||
Working with logical functions | Excel Worksheet Functions | |||
Logical Test comparison using cell color | Excel Discussion (Misc queries) | |||
Logical Comparison of Two cells | Excel Programming |