问题
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.)
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
回答1:
InputBox()
always returns a string, so TypeName()
will always return "String"
.
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
来源:https://stackoverflow.com/questions/31999974/do-until-loop-inputbox-infinitely-loops