简体   繁体   English

VBA 错误地评估 > 和 < 运算符

[英]VBA evaluates > and < operators incorrectly

I have the following simple code, which vba evaluates incorrectly (imho) and i can not figure it out even after searching the web extensively:我有以下简单的代码,vba 评估不正确(恕我直言),即使在广泛搜索网络后我也无法弄清楚:

ElseIf TextBoxSNo.Value < 1 Then
    MsgBox ("Please choose existing S.No")
    Exit Sub
ElseIf TextBoxSNo.Value > Cells(LastRow, 1).Value Then
    MsgBox ("Please choose existing S.No")
    Exit Sub

This Code ristricts the values one can enter into an Excel userform.此代码限制了可以输入 Excel 用户表单的值。 It works fine when the user enters a Value lower than 1 or higher than Cells(LastRow, 1).Value.当用户输入低于 1 或高于 Cells(LastRow, 1).Value 的值时,它工作正常。

However, it also Shows me the error message when I enter a valid value.但是,当我输入有效值时,它也会向我显示错误消息。 How can this be?怎么会这样? I even checked the values the code evaluates by printing them out in the MsgBox along with the Error Message.我什至通过在 MsgBox 中将它们与错误消息一起打印出来来检查代码评估的值。 It really seems like vba evaluates 5>100 as true and prints out the error message.似乎 vba 将 5>100 评估为真并打印出错误消息。

Edit: If I only Keep the first ElseIf Statement, it works as expected.编辑:如果我只保留第一个 ElseIf 语句,它会按预期工作。 Only when I add the second ElseIf, it evaluates incorrectly.只有当我添加第二个 ElseIf 时,它才会错误地评估。 LastRow is defined as an Integer, so I am comparing numbers to numbers LastRow 被定义为一个整数,所以我将数字与数字进行比较

Thanks for any help!谢谢你的帮助!

One tip - use the Val() function on any expression to ensure that you are comparing numbers with numbers.一个提示 - 在任何表达式上使用Val()函数以确保您将数字与数字进行比较。 Val() returns 0 if the expression cannot be converted - which can also be useful sometimes.如果表达式无法转换,则 Val() 返回 0 - 这有时也很有用。

Ok so I used the val() function and it works.好的,所以我使用了 val() 函数并且它有效。 Thanks for the tip!谢谢你的提示!

val(Cells(LastRow, 1).Value ) val(Cells(LastRow, 1).Value)

Dont really understand why i Need this though不太明白为什么我需要这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM