无法将数据从InputBoxparsing为整数(Visual Basic for Excel)
我试图得到一个值,用户手动input一个整数,我不得不考虑到用户可能不input一个整数的事实。 这就是为什么我想赶上types不匹配的错误。 但是,当我input一个整数值,我仍然得到types不匹配错误。
这是造成这个错误的那段代码。
Dim number As Integer On Error GoTo error number = InputBox("Enter an integer:") error: MsgBox ("Input error. Make sure you enter an integer value.") Exit Sub
Application.InputBox Method
允许你指定返回的数据types。
MSDN Application.InputBox方法(Excel)
Sub Example1() Dim number As Integer number = Application.InputBox(Prompt:="Enter an integer:", Type:=1) End Sub
因为带有Type 1参数的Application.InputBox
将返回0,如果用户取消,我宁愿使用标准的InputBox
。 使用它的方法是有一个单独的variables捕获值并testing返回值是否符合您的标准。 这样,你可以避免任何错误。
Sub Example2() Dim number As Integer Dim result As String result = InputBox("Enter an integer:") If result = "" Then MsgBox "Good Bye", vbInformation, "Action Cancelled" Exit Sub ElseIf IsNumeric(result) Then If CDbl(result) > CInt(result) Then MsgBox "You entered a Decimal" & vbCrLf & "Try Again", vbInformation, "Intergers Only" Else number = result End If Else MsgBox "Intergers Only" & vbCrLf & "Try Again", vbInformation, "Intergers Only" End If End Sub
这是一个方法:
Dim number As Integer On Error Resume Next number = InputBox("Enter an integer:") If Err.number <> 0 Then MsgBox ("Input error. Make sure you enter an integer value.") Exit Sub End If On Error GoTo 0
请注意,这将接受非整数的条目; 目前尚不清楚这是否是一个问题。