VBA如果条件为真,但实际上为假,有什么问题吗?
我在 VBA 中编写了代码,根据一些输入参数将数据从 Access 数据库提取到 Excel。当谈到 If 语句时,检查“速度”变量范围的标准之一是正确的,但是,我检查这个标准应该是错误的。 例如,speed=49,VSP=1.5,第一个 if 条件中的 1<=Speed<25 表示 true,这很荒谬,而 VSP<0 表示 false,所以转到第一个 elseif 条件,1<=Speed<25 仍然表示true 且 0<= VSP<3 也为 true,则函数从 Access 数据库返回值。否则,如果speed=49,VSP=6.5,函数仍然执行“ElseIf (1 <= Speed < 25) And (0 <= VSP < 3) then, statements 2”部分。似乎它只总是将第一个 elseif 条件视为 true。
我的 if 语句有什么问题?有什么建议吗?
代码:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还没有人指出
1 <= Speed <如何
1 <= Speed < 25
被评估。首先,1 <= Speed
被评估为True
或False
,然后将该值与25
进行比较。这需要将True
或False
解释为整数。True
被解释为-1
;False
被解释为0
。这两个值均小于25
,因此表达式的计算结果始终为True
。Nobody has yet pointed how
1 <= Speed < 25
is evaluated. First,1 <= Speed
is evaluated asTrue
orFalse
, then that value is compared with25
. This requires interpretingTrue
orFalse
as an integer.True
is interpreted as-1
;False
is interpreted as0
. Both of these are less than25
, so the expression will always evaluate toTrue
.这应该是以下内容:
This should be the following:
你的 if 完全错误......你不能这样写 if ......
您应该每次检查一个条件,或者至少检查一个条件,然后检查其他条件,然后检查其他条件...
所以
应该是
我无法理解为什么您在这方面没有收到任何错误...
您所做的,检查 1<= 速度(这可能是真的),然后检查 true <= 25...等等...不好...
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
Should be
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...