Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Excel, mismatch for inputbox as integer

Tags:

excel

vba

My code

Dim a As Integer
a = InputBox("Enter the number", "Program", "", 7000, 6000)
If a = Empty Then
    ' do code...
Else
    MsgBox "Enter the number."
End If

If I leave an empty field , Excel returns a Type Mismatch error. I would like to display a message.

like image 396
Oskar Strasburger Avatar asked Feb 11 '13 10:02

Oskar Strasburger


2 Answers

Since a is an Integer, it cannot contain a String or be Empty. Use a Variant and then check to see what has been returned:

Dim a As Variant
Dim b As Integer

a = InputBox("Enter the number", "Program", "", 7000, 6000)

If Not IsNumeric(a) Then
    'a is not a number
Else
    'a is a number and can be converted to Integer
    b = CInt(a)
End If
like image 84
Olle Sjögren Avatar answered Oct 25 '22 19:10

Olle Sjögren


You have a defined as Integer. Integer cannot be empty. Use Variant instead of Integer:

Dim a As Variant
a = InputBox("Enter the number", "Program", "", 7000, 6000)
If a = Empty Then
    ' do code...
Else
    MsgBox "Enter the number."
End If
like image 30
Andrey Gordeev Avatar answered Oct 25 '22 19:10

Andrey Gordeev