变量类型输入错误时重新运行InputBox
Rerun InputBox when there is a wrong variable type input error
我的目标是在 InputBox 崩溃时重新运行它,并给用户另一次提供正确输入类型的机会。 (就像它崩溃一样,你会得到一个消息框,上面写着 "sorry your entry is not available, please retry",然后它会跳回到 InputBox。)
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
多个替代项,它将 qm
更改为 1-600 之间的数字。
当我输入像 "Hey guys" 这样的文本时,Excel 给出了错误 13(运行时错误 13':类型不匹配)。
您可以将 If IsError(qm) Then GoTo Test1
替换为 On Error GoTo Test1
,以及 On Error GoTo 0
以重置错误处理程序。
试试下面的方法
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
有多种方法可以解决这个问题。我建议将变量定义为 variant
(可以保存任何数据类型)并检查它是否为数字:
dim answer as variant, qm as integer
do while true
answer = InputBox(...)
if isNumeric(answer) then
qm = cInt(answer)
exit do
endif
loop
您可以设置一个事件以在每次更改时验证 TextBox 的内容。我检查过这是一个数字,但您可以验证您需要的任何其他条件。
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
这就是为什么在 VBA 中您可以使用带第 4 个参数 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)
我的目标是在 InputBox 崩溃时重新运行它,并给用户另一次提供正确输入类型的机会。 (就像它崩溃一样,你会得到一个消息框,上面写着 "sorry your entry is not available, please retry",然后它会跳回到 InputBox。)
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
多个替代项,它将 qm
更改为 1-600 之间的数字。
当我输入像 "Hey guys" 这样的文本时,Excel 给出了错误 13(运行时错误 13':类型不匹配)。
您可以将 If IsError(qm) Then GoTo Test1
替换为 On Error GoTo Test1
,以及 On Error GoTo 0
以重置错误处理程序。
试试下面的方法
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
有多种方法可以解决这个问题。我建议将变量定义为 variant
(可以保存任何数据类型)并检查它是否为数字:
dim answer as variant, qm as integer
do while true
answer = InputBox(...)
if isNumeric(answer) then
qm = cInt(answer)
exit do
endif
loop
您可以设置一个事件以在每次更改时验证 TextBox 的内容。我检查过这是一个数字,但您可以验证您需要的任何其他条件。
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
这就是为什么在 VBA 中您可以使用带第 4 个参数 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)