检查 VBA 中的数据类型

Tfa*_*IIV 5 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
Run Code Online (Sandbox Code Playgroud)

但这行不通。

Ret*_*oid 5

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

VarType 函数返回一个 Integer,指示变量的子类型

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
Run Code Online (Sandbox Code Playgroud)


Kre*_* L. 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
Run Code Online (Sandbox Code Playgroud)