The VBA runtime error 402 ("Code must close the topmost modal form first") occurs when your macro tries to open a new dialog box or form *while a previous modal form remains open*. This happens because VBA treats modal dialogs as blocking—users must close them before proceeding. The error suggests you’re trying to open a form or dialog *directly after* another modal dialog was opened, without properly closing the first. The fix is always the same: **close the topmost modal form before opening a new one**. Below is a practical, step-by-step guide for Excel, Microsoft Access, and other VBA environments.
What You'll Need
- Your VBA project file (Excel workbook, Access database, or other app)
- VBA editor (press
Alt+F11in Excel or open the VBA IDE in Access) - Basic familiarity with forms and dialogs in the target application
- Optional: A test dataset or sample project to follow along
Step-by-Step
-
Identify modal forms in your code.
In your VBA project, search for any calls to:
MsgBox(modal dialog)- Form.ShowModal
- UserForm.ShowDialog
- Application.InputBox
ShowModalorShowDialogto block interaction with other windows. -
Check the sequence of form/open operations.
Review the code around the error-location line. Look for:
- Two modal forms opened in quick succession (e.g., a confirmation dialog followed by a data entry form)
- A dialog opened inside a loop or sub-procedure without a delay
- Conditional logic that skips closing the modal form (e.g.,
If condition Then CloseFormwas missed)
Dim frmLogin As New LoginForm frmLogin.ShowDialog ' Modal 1 opens Dim frmProcessing As New ProcessingForm frmProcessing.ShowDialog ' Modal 2 opens *while Modal 1 is still open -
Ensure modal forms are closed before opening new ones.
Add a validation step between your modal forms. Modify the code to:
- Check if the topmost modal form is open (
If frmShowing Is Nothing Then ...) - Close it explicitly before proceeding:
If frmLogin Is Nothing = False Then frmLogin.Hide frmLogin.Close End If
Note:Hidehides the form without closing it. UseCloseonly for forms not tied to the window.
Unloadevent for lingering references. - Check if the topmost modal form is open (
-
Debug with a breakpoint.
Insert a breakpoint on the line after the modal dialog opens, then step through the code. This reveals:
- Which form remains open when the error occurs
- If the form is actually being closed (check the Immediate Window with
?frmName.Visible)
Dim frmDetails As New DetailsForm frmDetails.ShowDialog ' Add breakpoint here to inspect form state -
Use a delay if forms can’t be closed cleanly.
For forms with complex state (e.g., linked tables in Access), add a small delay:
DoEvents ' Pauses execution briefly (~10ms) If frmLogin Is Nothing = False Then frmLogin.CloseAddDoEventsin a tight loop of form operations.
Common Mistakes
-
Skipping modal form checks.
The error often occurs when a macro assumes the last modal form is closed but isn’t. Always validate form state with
If frmName Is Nothingbefore opening new forms. -
Using
Hideincorrectly.Hideonly minimizes the form—it doesn’t release system resources. UseClosefor proper cleanup:frmLogin.Close ' Correct frmLogin.Hide ' Incomplete -
Opening forms in loops.
Repeatedly opening modal forms without closing them builds a stack. Add a counter or check for unclosed forms:
Dim openForms As Integer = 0 For Each form In Application.Forms If form.Visible Then openForms = openForms + 1 Next If openForms > 0 Then Exit Sub ' Prevent further errors - Global form variables. If forms reference shared variables, their state may persist across runs. Restructure code to avoid global dependencies.
Tips
-
Log form states.
Add debug statements to track form lifecycle:
Debug.Print "Form " & frmName.Name & " is open: " & (frmName.Visible)Copy this to the Immediate Window (Ctrl+Gin VBA) during execution. -
Use
Application.Waitfor delays. ReplaceDoEventswith:Application.Wait Now + TimeValue("00:00:01")This ensures predictable pauses. -
Check for hidden forms.
Use this query to find any open forms (Access/VBA):
DIM frmList As Object Set frmList = Application.Forms For Each frm In frmList If frm.Visible Then Debug.Print frm.Name Next - Test in isolation. Replicate the error in a minimal test project. Isolate the problematic code to pinpoint the exact trigger.
Troubleshooting
-
The error still occurs after closing forms.
The issue may stem from:
- A form tied to the Windows event loop (e.g., a userform with
AutoOpen). UseUnload frmin the form’sLoadevent to prevent lingering references. - A Windows message hook in your form code. Try replacing the form with a standard
MsgBoxto isolate the problem.
- A form tied to the Windows event loop (e.g., a userform with
-
Forms appear closed but don’t release resources.
In the Immediate Window, run:
? Application.TopLevelForms.CountIf the count remains high after closing forms, the issue is with form lifecycle management. -
The error only happens in certain contexts.
Check for conditional logic that hides forms:
If UserName = "Admin" Then frmAdmin.Close ' Forms may be hiddenUsefrmAdmin.Visibleto verify visibility. -
Forms are from a third-party library.
Some forms (e.g., those from ActiveX controls) may not respond to
Close. Replace them with standard forms or contact the library author for support.
Frequently Asked Questions
How do I check which form is the topmost modal?
Use this VBA code to list all visible forms:
Dim f As UserForm
For Each f In Application.UserForms
If f.Visible Then Debug.Print f.Name & " (Topmost: " & (f.Top = Application.ActiveWindow.Top) & ")"
Next
This shows which form occupies the screen.
Can I use Unload frm to force-close forms?
Yes, but only if the form isn’t currently open. In the form’s Load event, add:
Unload Me
This prevents forms from persisting when a modal operation completes.
Why does my form close but the error persists?
The form might still be referenced elsewhere. Search your code for:
frmName.Object
frmName
If you find lingering references, remove or replace them.
How do I debug forms in a tight loop?
Insert a Step Over breakpoint (F8) after each modal operation. Use Debug.Print to log form states before/after operations.
Is there a way to force-release all forms at once?
No built-in method exists, but you can loop through all forms:
For Each f In Application.UserForms
If f.Visible Then f.Close
Next
This is equivalent to pressing Alt+F4 manually.
Why does the error only happen in Release mode?
Debug builds may include optimizations that skip form cleanup. Test in Release mode to match production behavior and ensure forms are properly closed.
The root of error 402 is always a mismatch between form opening and closing. Use the steps above to systematically isolate and resolve the issue. If forms remain problematic, consider restructuring your code to avoid nested modal operations or use standard dialogs (MsgBox) where possible.