Can I close all open forms?

S

Sheila D

Hi

I have various menu options which open forms then other forms etc . Instead
of issuing DoCmd.Close for each is there a command to close all forms or a
specified number of forms?

Tx for any help


Sheila
 
D

DBS

There isn't a straightforward command to close all forms
that are open, so you'd have to create one of your own.
But it's simple to loop through the Forms collection to
close them all:
'==================================
Public Function CloseAllOpenForms()

Dim frm As Form

For Each frm In Forms
DoCmd.Close acForm, frm.Name
Next frm

End Function
'==================================

Hope that helps!

DBS (David Staas)
 
S

Sheila D

Hi David

Tx for this - I have set up the module but how do I then write the code to
run it as the On Click event - I'm not a very experienced VB person. I tried
doing it as a macro using Run COde command but for some reason I had to click
the button twice before it would work.

Tx

SHeila
 
D

Douglas J. Steele

Actually, there are problems using For Each frm In Forms in this case.

When you close the first form, the pointer is set to the next form. The Next
frm at the end of the loop advances you again, so you end up skipping what
was originally the 2nd form.

Use the following instead:

Public Function CloseAllOpenForms()

Dim frm As Form
Dim intLoop As Integer

For intLoop = (Forms.Count - 1) To 0 Step -1
Set frm = Forms(intLoop)
DoCmd.Close acForm, frm.Name
Next intLoop

End Function
 
S

Sheila D

Wow, works a treat

Thanks very much

Sheila

Douglas J. Steele said:
Actually, there are problems using For Each frm In Forms in this case.

When you close the first form, the pointer is set to the next form. The Next
frm at the end of the loop advances you again, so you end up skipping what
was originally the 2nd form.

Use the following instead:

Public Function CloseAllOpenForms()

Dim frm As Form
Dim intLoop As Integer

For intLoop = (Forms.Count - 1) To 0 Step -1
Set frm = Forms(intLoop)
DoCmd.Close acForm, frm.Name
Next intLoop

End Function
 
Top