Excel VBA中的if运算符出现问题。

huangapple go评论70阅读模式
英文:

Excel vba if operator is broken

问题

I can't figure out what's wrong with this simple if a < b statement.
The txtMax is 100 while txtSafety is 50, when txtMax is lower than txtSafety then run some error msgbox.

       With Me
              If .txtMax.Value < .txtSafety.Value Then
                     MsgBox "Error"
                     Exit Sub
              End If
       End With

In this case, it should not run the error msgbox since max is higher than safety.
Please help...

英文:

I can't figure out what's wrong with this simple if a < b statement.
The txtMax is 100 whiletxtSafety is 50, when txtMax is lower thantxtSafety then run some error msgbox.

       With Me
              If .txtMax.Value &lt; .txtSafety.Value Then
                     MsgBox &quot;Error&quot;
                     Exit Sub
              End If
       End With

In this case, it should not run the error msgbox since max is higher than safety.
Please help...

答案1

得分: 4

它们几乎肯定是字符串,在比较时使用词典排序。

换句话说,它会逐个字符地检查,直到出现差异:

100
50

由于5的字符值大于1,所以50被视为其中的较大值。

如果您想将它们视为数值进行比较,您应该首先将它们转换为数值,可以使用类似以下的方法:

With Me
    if CInt(.txtMax.Value) < CInt(.txtSafety.Value) Then
英文:

They're almost certainly strings which, when compared, use lexicographical sorting.

In other words, it checks character by character until there's a difference:

100
50

Since 5 is a larger character value than 1, 50 is considered the greater of the two.

If you want to compare them as if they were numeric values, you should probably convert them into numerics forst, with something like:

With Me
    if CInt(.txtMax.Value) &lt; CInt(.txtSafety.Value) Then

Or turn them into numerics as quickly as possible if you never need to worry about the strings again:

With Me
    maxValue = CInt(.txtMax.Value)
    safetyValue = CInt(.txtSafety.Value)
    if maxValue &lt; safetyValue Then

huangapple
  • 本文由 发表于 2023年2月24日 12:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定