在错误转到只能工作一次分析input框值

我有一个电子表格跟踪各种文件发送的时间。 对于每个文件,我都有一个input框,要求input文件的时间,还有一些其他选项可以放在input框中。

如果该人没有input有效的条目,我想将它们发回到input框,以便他们可以再次尝试。

这是我的代码,它适用于第一个错误,但如果有人第二次input错误的值,他们只是得到标准的“types不匹配”错误。 我正在为那些不了解VBA的人创造这个机会,并希望尽可能简单。

以下代码有多个实例,每个实例的文件时间不同。 提前致谢!

CFP: If Err Then MsgBox Error & " Invalid value. Please enter only 'blank', 'holiday', 'skip' or time value." Err.Clear tm = UCase(Application.InputBox("What time was the CFP file sent?")) On Error GoTo CFP If tm = "BLANK" Then ActiveCell.Value = "Blank" ElseIf tm = "HOLIDAY" Then ActiveCell.Value = "Holiday" ElseIf tm = "SKIP" Then ActiveCell.Value = "Skipped" Else ActiveCell.Value = TimeValue(tm) End If 

error handling程序在它们处理错误的过程下面

 Public Sub DoSomething On Error GoTo ErrHandler 'code here Cleanup: 'cleanup code here Exit Sub ErrHandler: 'error-handling code here Resume Cleanup End Sub 

发生什么事情是,一旦引发第一个错误, 因为error handling程序标签位于顶部 ,而不是跳转到error handling程序,代码跳回到顶部,VBA了解程序的其余部分是error handling子程序…永远不会返回到实际的程序体,因为它程序的主体。

您正在使用错误的控制stream程结构,请参阅@ Matteo的答案以了解您的需求。

而不是使用error handling程序,我会使用一个Loop ,只有当条件满足时才会中断。 例如:

问第一次:

 tm = UCase(Application.InputBox("What time was the CFP file sent?")) Dim inputOK As Boolean 

继续询问,直到用户input错误的值:

 inputOK = checkMyInput(tm) '<-- is the input "tm" ok or not? Do While inputOK = False '<-- if it's not ok, keep on asking MsgBox "Please enter a valid input" tm = UCase(Application.InputBox("What time was the CFP file sent?")) inputOK = checkMyInput(tm) '<-- and checking it again... Loop 

其中checkMyInput(tm)将是一个自定义函数返回TrueFalse如果您的input是好的或不是:

 Function checkMyInput(ByVal tm As Variant) As Boolean If tm ="BLANK" Or tm = "HOLIDAY" Or tm = "SKIP" Or IsDate(tm) Then checkMyInput = True Else checkMyInput = False End If End Function