Exit an Excel VBA Main Procedure from a Subroutine
Question details
Pass a user's overwrite or retry choice from a VBA prompt back to the main procedure so it can decide whether to exit.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- A main macro checks for a duplicate file and calls another procedure to ask the user what to do.
- Observed behavior
- Exiting the called subroutine does not automatically exit the main procedure.
Open the workbook in a version of Excel that supports VBA and make sure the Developer tab is available. Use a macro-enabled workbook and enable macros only if you trust the code.
Return the user's choice to the main VBA procedure
Use a function to return the prompt result, then let the calling procedure handle the choice and exit when appropriate.
Exit Sub ends only the procedure in which it runs. A called procedure cannot directly use Exit Sub to terminate its caller.
In Excel, select Developer > Visual Basic, then open the module containing your main macro.
In the module, outside any existing procedure, add: Function PromptOnDuplicateFile() As String Dim Answer As VbMsgBoxResult Answer = MsgBox("Duplicate file found. Overwrite?", vbExclamation + vbYesNo) If Answer = vbYes Then PromptOnDuplicateFile = "Overwrite" Else PromptOnDuplicateFile = "Retry" End If End Function
At the duplicate-file check in your main Sub, call the function and act on its result: Dim NextAction As String NextAction = PromptOnDuplicateFile() If NextAction = "Retry" Then Exit Sub End If ' Continue with your overwrite code here.
Run the main macro from Developer > Macros with a duplicate file present. Choose No to confirm the main procedure exits, and Yes to confirm it reaches your overwrite code.

Work with Excel files in WPS Office
WPS Office is a free, lightweight Office alternative with a familiar spreadsheet interface and support for common Excel formats, making it easier to move everyday workbook tasks. It does not fix Excel's VBA behavior; macro support and compatibility can vary by WPS edition and platform.

Frequently Asked Questions
Why doesn't Exit Sub stop the main macro?
Exit Sub stops only the Sub containing that statement. Return a value to the main procedure and have the main procedure run its own Exit Sub when needed.
What does the No button do in this example?
The function returns "Retry" when the user selects No. The main procedure then exits; add a loop or another action if you want an immediate retry.
Where should I put the prompt function?
Open Developer > Visual Basic and place the function in a VBA module outside the main Sub. The main procedure can then call PromptOnDuplicateFile().
Does this code overwrite a file automatically?
No. Selecting Yes returns "Overwrite" and allows the main procedure to continue. You must add your own file overwrite code after the choice check.




