在VBA中处理inputbox中的非整数

我有一个被称为“需要”的variables被定义为一个整数。 input框出现并提示用户。 如果他们键入一个整数,它会显示Msgbox“Got your number”。 如果我键入一个string,我得到运行时错误“13”:types不匹配。 我想如果我只是用了一个其他的陈述,就会说再试一次。 这不是那样做的。 在Else语句中是否需要error handling? 如果是的话,这条线是什么?

Sub gadgetmanuf() Dim need As Integer 'Dim rawneed As Single 'Dim rawavailable As Single need = InputBox("How many gadgets are needed?", "Insert a number") If TypeName(need) = "Integer" Then MsgBox ("Got your number") Else MsgBox ("Try again") End If End Sub 

使用types为1Application.InputBox强制用户input一个数字(为文本,范围等提供自己的错误信息)。 所以你需要处理的是Cancel选项,即

下面的代码使用了一个变体来处理这个问题,因为使用Cancel和一个IntegerLong给出了0 – 这可能是一个有效的条目。

 Sub TaylorWalker() redo: vStr = Application.InputBox("How many gadgets are needed?", "Enter a number", , , , , , Type:=1) If vStr = False Then GoTo redo End Sub 

更长的select

testinginput的variables是否大于0

 Sub EddieBetts() Dim StrPrompt As String Dim lngNum As Long StrPrompt = "How many gadgets are needed?" redo: lngNum = Application.InputBox(StrPrompt, "Enter an integer number (numbers will be rounded)", , , , , , Type:=1) If lngNum < 1 Then StrPrompt = "How many gadgets are needed - this must be a postive integer" GoTo redo End If MsgBox "User entered " & lngNum End Sub 

在你的例子中,'need'是一个整数数据types,所以它总是一个整数。

看看这个:

 Sub test() x = Range("A1").Value If Int(x) / x = 1 Then MsgBox "Value is an Integer" Else MsgBox "Value is not an Integer" End If End Sub 

或者假设A1有这个数字,在其他单元格中input公式:

 =IF(INT(A1)=A1,"True","False")