简体   繁体   English

VBA-Excel-出现错误时转到用户窗体

[英]VBA - Excel - On Error goto userform

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... 发生错误时,我想返回到用户窗体并更改在窗体上输入的信息,然后将其重新传递到宏中,然后从以下位置继续:如果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”上未定义标签

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. 当您使用“ On Error GoTo”语句时,您要告诉程序当它遇到错误时,请跳至当前过程中的特定行。 For example: 例如:

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). 在此示例中,当代码遇到错误时(在我的“ On Error”语句之后),它将停止正在执行的操作,并开始在ErrorHandler标签(由于末尾使用冒号而成为标签)上执行代码。 Running this code, you would never see the message box saying x = infinity. 运行此代码,您将永远不会看到消息框显示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. 一旦它试图通过除以零而遇到错误,它将跳到ErrorHandler标签,并给我一条消息,提示我不能除以零。

Chip Pearson has a good introduction to basic error handling here . Chip Pearson 在这里对基本错误处理进行了很好的介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM