检查VBA中的数据类型

时间:2017-10-22 14:11:36

标签: excel vba excel-vba

我在VBA中有一个程序,我希望用户只输入一个数字。我希望能够在他们输入字符串时让他们再次尝试。这就是我尝试过的:

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

但这不起作用。

4 个答案:

答案 0 :(得分:3)

尝试这样的事情......

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

答案 1 :(得分:2)

第二行的语法错误。请尝试下面的代码。仅当用户输入是有效数字时,代码才会继续。

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

答案 2 :(得分:2)

我认为您可以使用现有参数在Excel VBA中强制执行数字输入。

annualInterest = Application.InputBox("Please enter your annual interest rate as a decimal. ", , , , , , , 1)

它将确保有效的数字输入并可以保存呼叫。

答案 3 :(得分:0)

IsNumeric返回一个布尔值,并且仅在通过或未通过数字检查时才告诉您用户输入的数据类型。虽然在您的情况下可能会起作用,但另一个选择是VarType函数。

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