IsNumeric中的边缘情况 – 这是过度的

我有这样的代码:

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

这是否超越了它? IsNumeric是否有机会在这里返回True或False以外的内容,或者这是不好的编程习惯?

从OP的评论我不使用我的error handling程序。 我想用希望的数字输出做东西

 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 

或者如果你想保持提示input数字,直到用户正确或取消

 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 

不需要别的东西,因为它可能是真的或者是错的,但是只要注意其他的就应该是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一行一行地查看它是如何处理错误的。

input框可以有不同types的inputvalidation。 尝试这个

 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