Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

loop through all forms 1

Status
Not open for further replies.

belovedcej

Programmer
Nov 16, 2005
358
US
I have a main screen which I may be opening from any number of locations.

I want to close whatever I am on after opening the main screen without having to code an individual button. Instead, I'm just using a menu button with a macro telling it to run a function which opens the main form and close the other.

My thought was to simply loop through each form in the system and do an "if is open, close".

My problem is that since this is an adp file, I don't have a system table showing me all the forms in my project. How can I loop through all the forms in this case?

On the other hand, if there is a better solution, I am all ears.
 
run this on form load
Code:
Dim frm As Form
For Each frm In Application.Forms
If frm.Name <> Me.Name Then DoCmd.Close acForm, frm.Name
Next

 
This way of closing all the objects in a collection can work (and does with Access Forms), but it can also fail sometimes in certain instances. The reason it can fail is that the parent class which performs the enumeration you are stepping through does not always maintain its list correctly once you close one of the objects. I have seen instances where using the "for each x in collection: x.close" syntax fails or only closes half the objects (as they move "upward" in the list as you close each item, then the "next" operation occurs which ends up skipping one item).

A more reliable method in every instance is:

Code:
Do While Application.Forms.Count > 0
   DoCmd.Close acForm, Applications.Forms(0).Name
Loop
This will function in all circumstances and will not run into problems with the enumeration method of any collection. Good programming habit suggests getting used to using this method in order to avoid any possible problems in the future--problems not always detected at design time.

Erik
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top