simple want when user click on close form button.all the form should close except Mdi form.but MDI Form also get close.Kindly let me know. any help would be Highly appreciated.here is the code what i have written.

Private Sub FrmClose_Click() 
Dim frm As Form 
 For Each frm In Forms 'it will loop until it finish all the form in a collection forms. 
   Unload frm 
  Next frm 
  End Sub

Dani AI

Generated

Short summary and a safer approach

The Forms collection contains every open form, including the MDI parent, so a blind loop that unloads every entry will close the MDI too. Both and were on the right track: skip the MDI parent. A couple of notes on their replies — ’s first example needs the MDI reference actually assigned (otherwise the identity check does nothing), and ’s type check is valid but you still need to avoid mutating the Forms collection while enumerating it.

Safer pattern: avoid changing the Forms collection while you iterate it. Two reliable options are (a) iterate by numeric index from Forms.Count-1 down to 0 so removals don’t shift remaining indices, or (b) build a short list of targets to close and then loop that list. The index-based method is compact and works well in VB6.

Example (replace MDIForm1 with your actual MDI form instance/name):

Dim i As Long
For i = Forms.Count - 1 To 0 Step -1
  If Not (Forms(i) Is MDIForm1) Then
    Unload Forms(i)
  End If
Next i

Extra tips

  • Modal windows (Show vbModal) will block code flow; close them first if needed.
  • Unload fires QueryUnload/Unload events (which can cancel); if you have logic there, add a module flag to distinguish a “mass close” operation.
  • If you want to preserve form state, use Hide instead of Unload.
  • After unloading, release object references where appropriate.

These practices avoid accidental closing of the MDI parent and prevent odd behavior caused by modifying the Forms collection while iterating.

Recommended Answers

All 3 Replies

Several ways....

Dim F As Form, M As MDIForm
For Each F In Forms
  If F Is M Then
  Else
    Unload F
  End If
Next
Dim F As Form, M As MDIForm
For Each F In Forms
  If F.Name = "MDIForm1" Then
  Else
    Unload F
  End If
Next

and I could probably think of a few more but either one should do ya!


Good Luck

Standard Solution:

Dim objFrm As Form
For Each objFrm In Forms
    If [B]Not [/B]([B]TypeOf[/B] objFrm Is [B]MDIForm[/B]) Then
        Unload objFrm
    End If
Next

Standard Solution:

Thank You.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.