Excel VBA If语句错误触发

Yaw*_*wrf 1 excel vba excel-vba

好的,我有一个不应该触发的If语句,但确实如此.这是当前的设置:

If HP.Value > Range("HPMax").Value Then
    MsgBox (HP.Value & "/" & Range("HPMax").Value)
    HP.Value = Range("HPMax").Value
    MsgBox (HP.Value & "/" & Range("HPMax").Value)
 End If
Run Code Online (Sandbox Code Playgroud)

我有消息框,告诉我它确实发生了.目前HP为29,HPMax为60.

Thu*_*ame 8

您没有将文本框值转换为数字.假设您要比较整数值,请将您的比较更改为:

If IsNumeric(HP.Value) Then
    If Int(HP.Value) > Range("HPMax").Value Then
Run Code Online (Sandbox Code Playgroud)

如果小数位很重要,请使用Double:

If IsNumeric(HP.Value) Then
    If CDbl(HP.Value) > Range("HPMax").Value Then
Run Code Online (Sandbox Code Playgroud)

编辑回复您的评论:

所述VBA平等(=,<>,<=,>=,>,<),添加(+)和级联(&)运营商的行为不同,当两个操作数都是String类型,并且当一个或两个操作数是数值类型.

'equality operators do string comparisons if both operands are strings, regardless of whether they're numeric
Debug.Print "25" < "200" 'Prints False
Debug.Print 25 < "200"   'Prints True
Debug.Print "25" < 200   'Prints True
Debug.Print 25 < 200     'Prints True

Debug.Print "25" > "200" 'Prints True
Debug.Print 25 > "200"   'Prints False
Debug.Print "25" > 200   'Prints False
Debug.Print 25 > 200     'Prints False

'+ concatenates if both items are strings, regardless of whether they're numeric
Debug.Print "25" + "200" 'Prints 25200
Debug.Print 25 + "200"   'Prints 225
Debug.Print "25" + 200   'Prints 225
Debug.Print 25 + 200     'Prints 225

'- always casts both operands to numbers, and if either is non numeric, throws a Type Mismatch error
Debug.Print "25" - "200" 'Prints -175
Debug.Print 25 - "200"   'Prints -175
Debug.Print "25" - 200   'Prints -175
Debug.Print 25 - 200     'Prints -175

'& Always concatenates
Debug.Print "25" & "200" 'Prints 25200
Debug.Print 25 & "200"   'Prints 25200
Debug.Print "25" & 200   'Prints 25200
Debug.Print 25 & 200     'Prints 25200
Run Code Online (Sandbox Code Playgroud)

您可能拥有这样的代码,大部分时间都可以使用

Dim x As String
x = "1"
Debug.Print x < "80", Int(x) < "80"  'Prints True True
Run Code Online (Sandbox Code Playgroud)

但如果x开始"9",你有一个错误

x = "9"
Debug.Print x < "80", Int(x) < "80"  'Prints False True
Run Code Online (Sandbox Code Playgroud)

  • 听起来你需要紧急检查项目的其余部分.看我的编辑. (2认同)