VBA InputBox运行错误(错误的variablestypes)重新运行InputBox
嘿,伙计们,我要写我在VBA的第一个基本步骤,我遇到了以下问题。
Test1: qm = InputBox("Wie viele Quadrat Meter hat die Wohnung?" & vbLf & "Bitte geben sie die QM Zahl an.", Angabe) If IsError(qm) Then GoTo Test1
qm
被定义为一个Integer
,= 0,下面有一个Select Case
mutilple选项,它将qm
从1-600改为一个数字。
当InputBox运行时,我input一个像“嘿家伙”的Word,Excel给了我错误13(运行时错误13':types错配)。
我的目标是在崩溃时重新运行InputBox,并给用户一个新的机会给一个数字正确的input。 (就像它崩溃,你会得到一个msgbox它说:“对不起你的input不可用,请重试”,它会跳回到味精框)
我试图find堆栈溢出的适合的解释和谷歌search,但无法find解决scheme相同的问题。
如果你能帮我解决问题,或者给我一个合适的解释,我会非常感激。
这就是为什么在VBA中可以使用带有第四个参数Type
的Application.InputBox
。 如果您使用Type:=1
则只允许数字值。
代码 :
Dim qm As Integer qm = Application.InputBox("Wie viele Quadrat Meter hat die Wohnung?" _ & vbLf & "Bitte geben sie die QM Zahl an.", "Angabe", Type:=1)
尝试下面的东西
Sub Demo() Dim qm As String qm = 0 Test1: qm = InputBox("Enter value") If Not IsNumeric(qm) Then GoTo Test1 End Sub
声明qm
作为String
并检查其数字与否。 那么你必须使用CInt()
将String
转换为Integer
。
您可以replaceIf IsError(qm) Then GoTo Test1
与On Error GoTo Test1
,并On Error GoTo 0
重置error handling程序。
有很多方法可以解决这个问题。 我会build议定义一个variables作为variant
(可以容纳任何数据types),并检查它是否是数字:
dim answer as variant, qm as integer do while true answer = InputBox(...) if isNumeric(answer) then qm = cInt(answer) exit do endif loop
您可以设置一个事件来validation文本框的每次更改时的内容。 我检查这是一个数字,但你可以validation你需要的任何其他条件。
Private Sub TextBox1_Change() validator = IsNumeric(TextBox1.Value) If validator = False Then MsgBox "WARNING! You must enter a number!" TextBox1.BackColor = &HFF8& End If End Sub