在VBA中检查数据类型
我有一个VBA程序,我希望用户只输入一个数字。我希望能够捕捉到他们输入的字符串,并让他们再试一次。这就是我尝试过的:在VBA中检查数据类型,vba,excel,Vba,Excel,我有一个VBA程序,我希望用户只输入一个数字。我希望能够捕捉到他们输入的字符串,并让他们再试一次。这就是我尝试过的: Sub getInterest() annualInterest = InputBox("Please enter your annual interest rate as a decimal. ") If TypeOf annualInterest Is Double Then 'Continue with program
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
但是这不起作用。第二行的语法是错误的。请尝试下面的代码。仅当用户输入为有效数字时,代码才会继续
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
我认为您可以通过使用现有参数在ExcelVBA中强制输入数字
annualInterest=Application.InputBox(“请以十进制形式输入您的年利率。”、、、、1)
它将确保输入一个有效的数字,并可以保存通话。试试这样的方法
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
IsNumeric返回布尔值&仅当用户输入的数据通过或未通过数字检查时,它不会告诉您用户输入的数据类型。虽然它可能在您的情况下工作,另一个选项是VarType函数
使用isnumeric。
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