Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking data type in VBA

Tags:

excel

vba

I have a program in VBA in which I'd like the user to only enter a number. I want to be able to catch when they they enter a string and have them try again. This is what I've tried:

Sub getInterest()
    annualInterest = InputBox("Please enter your annual interest rate as a decimal. ")
        If TypeOf annualInterest Is Double Then
            'Continue with program
        Else
            Call getInterest()  
        End If
End Sub

But this doesn't work.

like image 288
Tfarcraw IIV Avatar asked Sep 02 '26 07:09

Tfarcraw IIV


2 Answers

IsNumeric returns a boolean & doesn't tell you what the type of data user entered, only if it passed or failed numeric check. And while it may work in your case another option is VarType function.

VarType function returns an Integer indicating the subtype of a variable

Sub getInterest()
    annualinterest = InputBox("Please enter your annual interest rate as a decimal. ")
        If VarType(annualinterest) = vbDouble OR VarType(annualinterest)=vbSingle Then
            'crunch interest
        Else
            getInterest
        End If
End Sub
like image 185
ReturnVoid Avatar answered Sep 05 '26 15:09

ReturnVoid


Try something like this...

Sub getInterest()
Dim annualInterest As Double

Do While annualInterest = 0
    annualInterest = Application.InputBox("Please enter your annual interest rate as a decimal.", "Annual Interest Rate!", Type:=1)
Loop
MsgBox annualInterest
End Sub
like image 25
Subodh Tiwari sktneer Avatar answered Sep 05 '26 15:09

Subodh Tiwari sktneer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!