Hey Guys我即将在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
多个替代品,可将qm
更改为1-600之间的数字。
当InputBox运行并输入像“Hey guys”这样的Word时,excel会给出错误13(运行时错误13':类型不匹配)。
我的目标是在它崩溃时重新运行InputBox,并为用户提供一个给出正确输入数字的新机会。 (就像它崩溃了,你得到一个msgbox,它说“抱歉你的条目不可用,请重试”,它会跳回到msg框)
我试图找到关于堆栈溢出的合适解释并用谷歌搜索它,但是无法找到解决方案的相同问题。
如果你能帮我解决问题或给我一个合适的现有解释,我会非常感激。
答案 0 :(得分:2)
尝试以下内容
Sub Demo()
Dim qm As String
qm = 0
Test1:
qm = InputBox("Enter value")
If Not IsNumeric(qm) Then GoTo Test1
End Sub
将qm
声明为String
并检查其是否为数字。然后,您必须使用String
将Integer
转换为CInt()
。
答案 1 :(得分:2)
这就是为什么在VBA中你可以使用带有第4个参数Application.InputBox
的{{1}}。如果您使用Type
,则只允许使用数字值。
<强>代码强>:
Type:=1
答案 2 :(得分:1)
您可以将If IsError(qm) Then GoTo Test1
替换为On Error GoTo Test1
,将On Error GoTo 0
替换为错误处理程序。
答案 3 :(得分:1)
有多种方法可以解决这个问题。我建议将变量定义为variant
(可以保存任何数据类型)并检查它是否为数字:
dim answer as variant, qm as integer
do while true
answer = InputBox(...)
if isNumeric(answer) then
qm = cInt(answer)
exit do
endif
loop
答案 4 :(得分:1)
您可以设置事件以在每次更改时验证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