检查VBA中的数据types
我在VBA中有一个程序,我希望用户只input一个数字。 当他们input一个string并让他们再次尝试时,我希望能够抓住他们。 这是我试过的:
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
你在第二行的语法是错误的。 请尝试下面的代码。 只有在用户input是有效的号码时,代码才会进行。
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中强制input一个数字。
annualInterest = Application.InputBox("Please enter your annual interest rate as a decimal. ", , , , , , , 1)
它将确保一个有效的数字input,并可以保存通话。