编辑:我自己想通了。我觉得很傻,但是用"结束"替换"退出子"效果很好。
背景:我有一个使用"呼叫"功能在一个Sub中运行多个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)。这段代码有效,但问题是,如果用户按下"取消"按钮,主子中调用的其余代码(上面的代码 #1)将继续运行。我希望所有用户代码在用户按下取消按钮时停止。我似乎不知道该怎么做。
'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
关键字将有效地结束执行,但它几乎是一个大的红色"自毁"按钮,在结构正确的代码下,您实际上永远不需要使用它。
看起来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
你去吧,优雅地退出,没有按下任何自毁按钮。