user941568
user941568

Reputation: 41

VBA if condition is true, however actually is false, what's wrong with it?

I wrote code in VBA to extract data from Access database to Excel based on some input parameters. When it comes to If statement, one of the criteria which exam the range of "Speed" variable is true, however, I checked that this criteria should be wrong. For example, speed=49, VSP=1.5, 1<=Speed<25 in 1st if condition indicates true which is ridiculous, and VSP<0 indicates false, so it goes to 1st elseif condition, 1<=Speed<25 still indicates true and 0<= VSP<3 is also true, then function returns the value from Access database. Else, if speed=49, VSP=6.5, the function still executes the "ElseIf (1 <= Speed < 25) And (0 <= VSP < 3) Then, statement 2" part. It seems it only always regard 1st elseif condition as true.

What's wrong with my if statement? Any advice?

Code:

Function F (ByVal Speed, VSP as single)

.............

If (1 <= Speed < 25) And (VSP < 0) Then

   statement 1

ElseIf (1 <= Speed < 25) And (0 <= VSP < 3) Then

   statement 2

ElseIf (25<= Speed < 50)) And (0<= VSP <3) Then

   statement 3

End if

End function

Upvotes: 2

Views: 5622

Answers (3)

phoog
phoog

Reputation: 43046

Nobody has yet pointed how 1 <= Speed < 25 is evaluated. First, 1 <= Speed is evaluated as True or False, then that value is compared with 25. This requires interpreting True or False as an integer. True is interpreted as -1; False is interpreted as 0. Both of these are less than 25, so the expression will always evaluate to True.

Upvotes: 9

tjg184
tjg184

Reputation: 4676

This should be the following:

Function F(ByVal Speed, VSP As Single)

    If (1 <= Speed And Speed < 25) And (VSP < 0) Then
        ' statement 1
    ElseIf (1 <= Speed And Speed < 25) And (0 <= VSP And VSP < 3) Then
        ' statement 2
    ElseIf (25 <= Speed And Speed < 50) And (0 <= VSP And VSP < 3) Then
        ' statement 3
    End If

End Function

Upvotes: 2

gbianchi
gbianchi

Reputation: 2138

Your if is totally wrong.. you can't write the if in that way... You should check one condition at each time, or at least, check one condition and then other and then other...

So

If (1 <= Speed < 25) And (VSP < 0) Then

Should be

If (1 <= Speed) and (Speed < 25) And (VSP < 0) Then

I could not understand why you are not getting any error on this...

What you've done, has check for 1<= speed (that could be true) and then has check true < 25... and so on... no good...

Upvotes: 0

Related Questions