IsNumeric中的边缘情况 - 这是对它的过度思考

时间:2015-12-11 00:03:36

标签: excel vba excel-vba

我的代码如下:

Select Case IsNumeric(somevariable)
    Case True
        Resume Next
    Case False
        Call notnum
    Else
        Call MyErrorHandler
End Select

这是否过度思考? IsNumeric是否有可能在此返回True或False之外的其他内容,或者这是一种错误的编程习惯?

3 个答案:

答案 0 :(得分:3)

不需要别的,因为它会是真的还是假的,但是,只要注意别人应该是Case Else(虽然你有意删除它但没有实际意义)

基于此,虽然我不会仅使用2个选项的案例:

If IsNumeric(somevariable) then
    Resume Next
Else
    Call MyErrorHandler
End if

编辑:以下是错误检查的工作原理:

Sub SheetError()
    Dim MySheet As String
    On Error GoTo ErrorCheck
    MySheet = ActiveSheet.name
    Sheets.Add
    ActiveSheet.name = MySheet
    MsgBox "I continued the code"
    ActiveSheet.name = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    MsgBox "I will never get to here in the code"
    End
ErrorCheck:
    If Err.Description = "Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by Visual Basic." Then
        Resume Next
    Else
        MsgBox "Error I am not designed to deal with"
    End If
End Sub

将此模块复制并粘贴到您的个人工作簿或新工作簿并运行它,使用F8逐行逐步查看它是如何实际处理错误的。

答案 1 :(得分:1)

来自OP的评论我没有使用我的错误处理程序。我想用有希望的数字输出

做一些事情
Sub demo()
    Dim inputs As Variant

    inputs = InputBox("Prompt", "Title", "Default")

    If Not IsNumeric(inputs) Then
        notnum
    Else
        ' Do what you want with numeric input inside the Else

    End If

    ' Maybe do more stuff irrespective of input

End Sub

Sub notnum()
    ' do not numeric stuff here
End Sub

或者,如果您希望在用户正确输入或取消

之前继续提示数字输入
Sub demo2()
    Dim inputs As Variant

    Do
        inputs = InputBox("Enter something Numeric", "Title", "Default")

    Loop Until IsNumeric(inputs) Or inputs = vbNullString
    If Not inputs = vbNullString Then
        ' Do wht you want with numeric input inside the Else
    End If

    ' Maybe do more stuff irrespective of input

End Sub

答案 2 :(得分:0)

输入框可以有不同类型的输入验证。试试这个

something = Application.InputBox("Pls Insert the Number", Type:=1)
If something = False Then Exit Sub
'Type:=0 A formula
'Type:=1 A number
'Type:=2 Text (a string)
'Type:=4 A logical value (True or False)
'Type:=8 A cell reference, as a Range object
'Type:=16 An error value, such as #N/A
'Type:=64 An array of values