VBA - Excel - 出错时转到用户表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8919670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:58:42  来源:igfitidea点击:

VBA - Excel - On Error goto userform

vbaerror-handlingexcel-vbaexcel

提问by HL8

When there is an error, I want to go back to my userform and change the information entered on the form and re pass it into the macro and then continue from: If Len(Dir(sFilePath & newfol, vbDirectory)) = 0...

当出现错误时,我想返回到我的用户表单并更改在表单上输入的信息并将其重新传递到宏中,然后继续: If Len(Dir(sFilePath & newfol, vbDirectory)) = 0.. .

If Len(Dir(sFilePath & newfol, vbDirectory)) = 0 Then
            MkDir sFilePath & newfol & "\"
            On Error GoTo UserForm1
        Else
            MsgBox ("Folder already exists please re enter new folder name")
            'End
            UserForm1.Show
            MoveAndSave_Reports
End If

The above give me an error message: Compile error: Label not defined at "On Error GoTO UserForm1"

以上给了我一个错误信息:编译错误:标签未定义在“On Error GoTO UserForm1”

回答by Craig Rowe

When you use an "On Error GoTo" statement, you're telling the program that when it hits an error, skip to a specific line in the current procedure. For example:

当您使用“On Error GoTo”语句时,您是在告诉程序,当它遇到错误时,跳到当前过程中的特定行。例如:

On Error GoTo ErrorHandler
x = 10 / 0
msgbox "x = infinity!"

ErrorHandler:
msgbox "Cannot divide by zero"

In this example, when the code hits an error (after my "On Error" statement), it will stop what it's doing and begin executing code at the ErrorHandler label (it's a label because of the colon at the end). Running this code, you would never see the message box saying x = infinity. Once it hits the error by trying to divide by zero, it will jump down to the ErrorHandler label and give me a message saying I can't divide by zero.

在这个例子中,当代码遇到错误时(在我的“On Error”语句之后),它将停止它正在做的事情并开始在 ErrorHandler 标签处执行代码(它是一个标签,因为末尾有冒号)。运行此代码,您将永远不会看到消息框说 x = 无穷大。一旦它通过尝试除以零而遇到错误,它将跳到 ErrorHandler 标签并给我一条消息,说我不能除以零。

Chip Pearson has a good introduction to basic error handling here.

Chip Pearson在此处对基本错误处理进行了很好的介绍。