开发者

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

开发者 https://www.devze.com 2023-04-12 02:28 出处:网络
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,

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 e开发者_C百科lseif 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


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.


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


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号