【问题标题】:Rerun InputBox when there is a wrong variable type input error出现错误的变量类型输入错误时重新运行 InputBox
【发布时间】:2017-09-13 08:01:05
【问题描述】:

我的目标是在 InputBox 崩溃时重新运行它,并给用户另一个机会来提供正确的输入类型。 (就像它崩溃一样,你会得到一个消息框,上面写着“抱歉你的条目不可用,请重试”,然后它会跳回 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 之间的数字。

当我输入“大家好”之类的文本时,Excel 给出错误 13(运行时错误 13':类型不匹配)。

【问题讨论】:

  • 你可以使用Application.InputBox版本的VBA,下面看我的回答

标签: excel vba inputbox


【解决方案1】:

这就是为什么在 VBA 中您可以将 Application.InputBox 与第四个参数 Type 一起使用。如果您使用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)

【讨论】:

  • 非常感谢您编辑我的问题,使其更具可读性。 Allpication.Inputbox 效果很好,我会尝试将您的编辑作为未来帖子和答案的示例。
【解决方案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 并检查其是否为数字。然后您必须使用CInt()String 转换为Integer

【讨论】:

  • 谢谢。 IsNumeric() 解决方案是为我的任务提供的提示,但我很高兴您向我展示了如何正确使用它。
【解决方案3】:

您可以将If IsError(qm) Then GoTo Test1 替换为On Error GoTo Test1On Error GoTo 0 以重置错误处理程序。

详情可以看https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/on-error-statement

【讨论】:

    【解决方案4】:

    有多种方法可以解决这个问题。我建议将变量定义为variant(可以保存任何数据类型)并检查它是否为数字:

    dim answer as variant, qm as integer
    do while true
        answer = InputBox(...)
        if isNumeric(answer) then
            qm = cInt(answer)
            exit do
        endif
    loop
    

    【讨论】:

    • 伙计,对我来说,这是一个聪明的解决方案。非常感谢。
    【解决方案5】:

    您可以设置一个事件以在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-11
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2016-11-27
      • 2015-09-02
      相关资源
      最近更新 更多