Vba Can';t将InputBox中的数据解析为整数(Visual Basic for Excel)
我试图得到一个用户手动输入为整数的值,我必须考虑到用户可能不会输入整数这一事实。这就是我试图捕捉类型不匹配错误的原因。但是,当我输入一个整数值时,仍然会出现类型不匹配错误 这是导致此错误的代码段Vba Can';t将InputBox中的数据解析为整数(Visual Basic for Excel),vba,excel,Vba,Excel,我试图得到一个用户手动输入为整数的值,我必须考虑到用户可能不会输入整数这一事实。这就是我试图捕捉类型不匹配错误的原因。但是,当我输入一个整数值时,仍然会出现类型不匹配错误 这是导致此错误的代码段 Dim number As Integer On Error GoTo error number = InputBox("Enter an integer:") error: MsgBox ("Input error. Make sure you enter an integer val
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
这里有一个方法:
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
Dim数字为整数
出错时继续下一步
数字=输入框(“输入整数:”)
如果错误号为0,则
MsgBox(“输入错误。请确保输入整数值。”)
出口接头
如果结束
错误转到0
请注意,这将接受非整数项;不清楚这是否是一个问题。这里有一种方法:
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
Dim数字为整数
出错时继续下一步
数字=输入框(“输入整数:”)
如果错误号为0,则
MsgBox(“输入错误。请确保输入整数值。”)
出口接头
如果结束
错误转到0
请注意,这将接受非整数项;不清楚这是否是一个问题。Application.InputBox方法允许您指定返回的数据类型 因为如果用户取消,带有Type 1参数的
Application.InputBox
将返回0,所以我更喜欢使用标准的InputBox
。使用它的方法是让一个单独的变量捕获该值,并测试返回值是否符合您的标准。这样,您就可以避免任何错误
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
Application.InputBox方法允许您指定返回的数据类型
因为如果用户取消,带有Type 1参数的Application.InputBox
将返回0,所以我更喜欢使用标准的InputBox
。使用它的方法是让一个单独的变量捕获该值,并测试返回值是否符合您的标准。这样,您就可以避免任何错误
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
请在错误:
之前添加Exit sub
,您没有任何机制可以跳过错误消息,因此它将始终出现。还有一个建议-在使用自己的姓名时,尽量避免使用保留字或类似保留字。因此,您可以使用非常常见的ErrorHandler
@kazimierrzjawor来代替error
标签,我知道错误处理是如何工作的。我要说的一点(正如你也提到的)是,发布的代码中没有任何内容可以跳过Msgbox
行。(注意:简单地添加Exit Sub
似乎会使代码变得有点无意义)请在错误之前添加Exit Sub
您没有任何机制可以跳过错误消息,因此它总是会出现。还有一个建议-在使用自己的名字时,尽量避免使用保留字或类似保留字。因此,您可以使用非常常见的ErrorHandler
@kazimierrzjawor来代替error
标签,我知道错误处理是如何工作的。我要说的一点(正如你也提到的)是,发布的代码中没有任何内容可以跳过Msgbox
行。(注意:简单地添加Exit Sub
似乎会使代码变得有点无意义)谢谢。虽然我不得不修改它,使其只存储整数值,但它仍然有效。谢谢。虽然我不得不修改它,使其只存储整数值,但它仍然有效。