VBA在错误AddSheet

所以我正在尝试使用On Error来完成以下操作。 我正在尝试从活动工作表中select下一张工作表(试图避免使用工作表名称)。 如果这样会产生一个错误,即活动工作表之后没有工作表,那么需要添加一个新工作表。 我希望有一些简单的如果…是错误然后….但是没有。

我已经尝试了错误的多种变化,没有运气。 即使在活动页面之后还有另外一个页面(即没有错误)的情况下,它仍会创build一个新页面,但我只是希望它select该页面。 它应该只添加一张纸,当它去select下一张纸,并产生一个错误。 有什么build议么?

On Error GoTo AddSheet: Worksheets(ActiveSheet.Index + 1).Select AddSheet: Sheets.Add After:=ActiveSheet Resume Next 

刚刚尝试过这个也没有运气:

 On Error GoTo AddSheet: Worksheets(ActiveSheet.Index + 1).Select Resume Label1: AddSheet: Sheets.Add After:=ActiveSheet Label1: 

你的问题是Resume Label1:

将其更改为Goto Label1:

附录 :我不知道为什么应该使用Goto而不是Resume,所以我做了一些实验。

在下面的代码中,Resume有效地忽略了提供的标记,因为Resume被devise为进入error handling程序。 因为没有发生任何错误,所以任何对Resume的调用都会将代码推送到On Error GoTo <Label>定义的On Error GoTo <Label>即使您只是调用不带标签的Resume

 Sub ErrorHandlingPlay() On Error GoTo AddSheet Resume Label1: 'Resume moves flow to AddSheet instead Label1: Exit Sub AddSheet: Debug.Print "This gets printed." End Sub 

但是,如果你把你的error handling标签中的Resume,它成功地移动stream程:

 Sub ErrorHandlingPlay() On Error GoTo AddSheet: Debug.Print 1 / 0 'To throw an error Label1: Exit Sub AddSheet: Resume Label1: 'Flow successfully moves to Label1 after the error is caught. Debug.Print "This is not printed" End Sub 

所以基本上…如果您从error handling标签中使用它,请使用Resume 。 否则使用Goto

如果遇到问题,您只需要告诉程序先离开子程序。 你也想Resume而不是Resume Next来重试导致错误的行,在这种情况下,我认为你会的。

 On Error GoTo AddSheet: Worksheets(ActiveSheet.Index + 1).Select Exit Sub 'or Exit Function if you are in a function AddSheet: Sheets.Add After:=ActiveSheet Resume 

并注意,实际应用时:

 Sub Foo() ' Some Code On Error GoTo AddSheet: Worksheets(ActiveSheet.Index + 1).Select On Error GoTo 0 'This turns off the error handling in case after it is no longer needed ' the rest of your code Exit Sub AddSheet: Sheets.Add After:=ActiveSheet Resume End Sub 

更多信息: http : //www.cpearson.com/excel/errorhandling.htm