直到循环InputBox无限循环 [英] Do Until Loop InputBox infinitely loops
问题描述
我正在创建一个概率宏,用户可以在其中输入纸牌游戏中的玩家人数.如果我输入字符串(例如, Joe
),非整数(例如, 15.67
)或小于0的整数(例如, -25
),InputBox应该循环.但是,大于0的整数应终止循环.(无论用户输入什么,我都必须强制杀死Excel以停止InputBox.)
I am creating a probability macro where user enters number of players in a card game. If I enter string (ex, Joe
), non-integer(ex, 15.67
), or integer less than 0 (ex, -25
), the InputBox should loop. However, integers greater than 0 should terminate the loop. (I have to force kill Excel to stop the InputBox regardless of user input.)
一旦输入大于0的整数,我希望InputBox关闭/退出Sub.我在这里做什么错了?
I want the InputBox to close / Exit Sub once an integer greater than 0 is entered. What am I doing wrong here?
Sub GenerateCards()
Players = InputBox("How many players? Please enter an integer.")
Do Until TypeName(Players) = "Integer" And Players > 0 ' why does this loop even if both conditions are met (ex, Players=5?)
Players = InputBox("How many players? Please enter an integer.")
Loop
End Sub
推荐答案
InputBox()
始终返回字符串,因此 TypeName()
将始终返回"字符串"
.
InputBox()
always returns a string, so TypeName()
will always return "String"
.
但是您可以测试返回的字符串是否为整数.首先,您可以使用 IsNumeric()
来测试字符串是否为数字值.然后,您可以安全地将其强制转换为 Double
或 Integer
.实际上,您可以将其转换为两者,然后将它们相互比较.如果它们相同,则您将获得一个整数值.例如:
But you can test if the string that's returned is an integer. First, you can use IsNumeric()
to test if the string is a numeric value. Then, you can safely cast it to a Double
or an Integer
. In fact, you can cast it to both and then compare them against each other. If they're the same, you've got an integer value. For example:
Sub GenerateCards()
Do
Players = InputBox("How many players? Please enter an integer.")
If IsNumeric(Players) Then
If CDbl(Players) = CLng(Players) And Players > 0 Then
' Integer > 0 entered. Exit loop...
Exit Do
End If
End If
Loop
End Sub
这篇关于直到循环InputBox无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!