xlDialogSaveAs – 如果select“取消”,则结束所有代码

编辑:我想出了自己。 我觉得非常愚蠢,但用“结束”取代“退出子”完美的作品。

背景:我有一个使用“调用”函数在一个Sub中运行多个子的Sub(请参见下面的代码#1)。

Option Explicit Sub MIUL_Run_All() Dim StartTime As Double Dim SecondsElapsed As String 'Remember time when macro starts StartTime = Timer Call OptimizeCode_Begin Call Format_MIUL Call Custom_Sort_MIUL Call Insert_Process_List Call Format_Process_List Call OptimizeCode_End 'Determine how many seconds code took to run SecondsElapsed = Format((Timer - StartTime) / 86400, "ss") 'Notify user in seconds MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation End Sub 

我的第一个被称为“Format_MIUL”的代码使用下面的代码行(见下面的代码#2)提示用户保存文件。 这个代码可以工作,但问题是,如果用户按下“取消”button,主子代码(上面代码#1)中调用的其余代码将继续运行。 如果用户按下取消button,我希望所有代码停止。 我似乎无法弄清楚如何做到这一点。

 'Save file as .xlsm MsgBox " Save as Excel Workbook (.xlsx)!" Dim userResponse As Boolean On Error Resume Next userResponse = Application.Dialogs(xlDialogSaveAs).Show(, 51) On Error GoTo 0 If userResponse = False Then Exit Sub Else End If 

任何帮助是极大的赞赏。

Call关键字已过时20年,您可以将其删除。

End关键字将会有效的结束执行,但是如果给定的代码结构正确的话,它实际上就是一个很大的红色的“自毁”button,你根本不需要使用它。

看起来像Format_MIUL是一个Sub过程。 使其成为一个Function返回一个Boolean值,告诉调用者是否可以继续,或者是否应该取消其余的操作:

 Private Function Format_MUIL() As Boolean '... 'Save file as .xlsm MsgBox " Save as Excel Workbook (.xlsx)!" Dim userResponse As Boolean On Error Resume Next userResponse = Application.Dialogs(xlDialogSaveAs).Show(, 51) On Error GoTo 0 'return False if userResponse isn't a filename, True otherwise: Format_MUIL = Not VarType(userResponse) = vbBoolean End Function 

而现在,而不是这个:

 Call Format_MIUL 

来电者可以这样做:

 If Not Format_MIUL Then Exit Sub 

在那里你可以走出去,没有任何自毁button被按下。