好的,我有一个不应该触发的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
我有消息框告诉我它确实正在发生。目前HP为29,HPMax为60.
答案 0 :(得分:8)
您没有将文本框值转换为数字。假设您要比较整数值,请将您的比较更改为:
If IsNumeric(HP.Value) Then
If Int(HP.Value) > Range("HPMax").Value Then
如果小数位很重要,请使用Double:
If IsNumeric(HP.Value) Then
If CDbl(HP.Value) > Range("HPMax").Value Then
编辑回复您的评论:
VBA平等(=
,<>
,<=
,>=
,>
,<
),添加({{1} }}和串联(+
)运算符在两个操作数都是&
类型时,以及当一个或两个操作数是数字类型时表现不同。
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
但如果Dim x As String
x = "1"
Debug.Print x < "80", Int(x) < "80" 'Prints True True
以x
开头,则您有错误
"9"