xlDialogSaveAs - 如果选择“取消”,则结束所有代码

时间:2017-10-20 16:41:36

标签: excel vba excel-vba

编辑:我自己想通了。我觉得很傻,但用“End”替换“Exit Sub”非常有效。

背景:我有一个使用“调用”功能的Sub在一个Sub中运行多个subs(参见下面的代码#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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

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

End关键字将有效地结束执行,但它几乎是一个大红色"自我毁灭"给定结构化的代码,实际上永远不需要使用的按钮。

看起来Format_MIUL是一个Sub程序。将其设为Function返回一个Boolean值,告诉调用者是否可以继续,或者是否应取消其余操作:< / p>

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

然后你走了,没有按下任何自毁按钮,优雅的退出。