2016-11-18 6 views
0

ユーザーが手動で入力する値を整数として取得しようとしていますが、ユーザーが整数を入力しない可能性があることを考慮する必要があります。だから私は型の不一致のエラーをキャッチしようとしている。しかし、整数値を入力すると、型の不一致エラーが発生します。InputBoxからデータを整数として解析できません(Visual Basic for Excel)

これはこのエラーを引き起こすコードです。ここで

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 
+1

エラーの前に 'exit sub'を追加してください: –

+1

エラーメッセージをスキップするメカニズムがないので、常に表示されます。 – Rory

+0

もう1つの提案 - あなたの名前を使用するときは、予約語や予約語を避けるようにしてください。したがって、 'error'ラベルの代わりにかなり一般的な' ErrorHandler'を使うことができます。 –

答えて

2

Application.InputBox Methodでは、返されるデータの種類を指定できます。

enter image description here

Sub Example1() 
    Dim number As Integer 
    number = Application.InputBox(Prompt:="Enter an integer:", Type:=1) 

End Sub 

MSDN Application.InputBox Method (Excel)

ユーザーがキャンセルした場合、0を返します。タイプ1のパラメータと Application.InputBoxので、私は標準 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 
+0

ありがとうございます。出来た。 –

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 

注意。それが懸念されるのかどうかは明らかではありません。

+0

ありがとうございます。これは整数値だけを格納するように修正する必要がありましたが、これはうまくいきました。 –

関連する問題