我在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
但是,这是行不通的。
尝试这样的事情...
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
你在第二排的语法是错误的。请尝试以下代码。代码将继续仅当用户输入一个有效的数字。
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
我想,你可以简单地使用现有的参数强制在Excel VBA数字输入。
annualInterest = Application.InputBox("Please enter your annual interest rate as a decimal. ", , , , , , , 1)
这将确保一个有效的数字输入,可以节省呼叫。
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