[RESOLVED] Exit For within the body of a "For Each" statement-VBForums
Results 1 to 13 of 13

Thread: [RESOLVED] Exit For within the body of a "For Each" statement

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2010
    Posts
    264

    Resolved [RESOLVED] Exit For within the body of a "For Each" statement

    I guess it should be possible to have an "Exit For" within the body of a "For Each" statement, but I am not sure.
    We have all used "Exit For" within For statements that enumerate for example For i = 1 to 10
    But I have never seen an "Exit For" within "For Each"
    Does it exist? Is it valid?
    For example:
    Code:
       For Each Item In Shell32.NameSpace(TheFldrPath).Items
          ...
          ...
          If some condition Then
             Exit For
          End If
          ...
          ...
       Next
    I googled and there is no such example for VB6. There are some examples for VB.Net but not for VB6.
    And no VB6 tutorial mentions it either.
    Can anybody advise please.
    Can anybody please provide a link to a VB6 tutorial that mentions this?
    Thanks.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    96,329

    Re: Exit For within the body of a "For Each" statement

    What happened when you tried it for yourself?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    MSDN "How Do I?" Videos: VB | C#
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Frenzied Member gibra's Avatar
    Join Date
    Oct 2009
    Location
    ITALY
    Posts
    1,375

    Re: Exit For within the body of a "For Each" statement

    Quote Originally Posted by IliaPreston View Post
    But I have never seen an "Exit For" within "For Each"
    Same thing of For i / Next i

  4. #4
    PowerPoster
    Join Date
    Feb 2006
    Posts
    17,371

    Re: Exit For within the body of a "For Each" statement

    The only real difference I can think of is:

    With For... Next an Exit For leaves the control-variable set, and if you fall through it is incremented (or decremented) past the last value used.

    With For Each... Next an Exit For leaves the each-variable set, but if you fall through it is Empty.

  5. #5
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    2,975

    Re: Exit For within the body of a "For Each" statement

    It's not advised to do this (although I must admit that I occasionally do), but the "control-variable" is always outside of the loop's parameters on a "For idx" loop once it drops out. (In this case, we're saying the control-variable is idx.)

    For instance, in the following:

    Code:
    
        Dim idx As Long
        For idx = 1 To 5
            ' do something
        Next idx
        MsgBox idx ' <--- Here, idx = 6, just outside the loop's parameters.
    
    Now, if we use a "Step -1" then things will be different, but still predictable. And if we use something like "Step 3", they're still predictable.

    So, when we recognize this, for me, I think of "For Each" and "For idx" working quite similarly.

    If we use an "Exit For", idx will be at whatever it was set at (still inside the loop's parameters), and if we're using "For Each ... Exit For" our Variant_Or_Object_Idx will just be set to whatever it was when we exit the loop. As dilettante stated, if a "For Each" loop drops out, if we're enumerating objects, our Object_Idx will be "Nothing", or, if we're enumerating variants, our Variant_Idx will be "Empty".

    It all seems fairly straightforward to me.

    Best Regards,
    Elroy


    EDIT1: And just for grins, I searched my primary project for "Exit For" used in conjunction with "For Each". It seems that I have an "Exit For" in about half of my "For Each" loops, of which there are many. Here are a couple of examples:

    Code:
    
    
    
        ' This is code I recently wrote, but it does show an "Exit For".
    
        For Each exc In vExcludedContainers
            If exc Is ctl Then
                bOk = False
                Exit For
            End If
        Next exc
    
    
    ' This is a very old procedure I often use.
    ' Looking at it, it could clearly be tightened a bit, but it does show a good use of "Exit For".
    
    Private Function TextOfSelectedCheckbox(chk As Object) As String
        Dim c As CheckBox
        '
        For Each c In chk
            If c.Value = vbChecked Then
                TextOfSelectedCheckbox = c.Caption
                Exit For
            End If
        Next c
    End Function
    
    
    ' This one uses "Exit Function" rather than "Exit For" in the loop, but the principle is the same.
    
    Public Function IsLoaded(FormName As String) As Boolean
        ' Does not have the side effect of needing to load the form just to see if it's loaded.
        Dim frm As Form
        For Each frm In Forms
            If frm.Name = FormName Then
                IsLoaded = True
                Exit Function
            End If
        Next frm
    End Function
    
    
    
    Last edited by Elroy; Apr 15th, 2017 at 08:35 AM.

  6. #6
    PowerPoster
    Join Date
    Feb 2006
    Posts
    17,371

    Re: Exit For within the body of a "For Each" statement

    Quote Originally Posted by Elroy View Post
    It's not advised to do this (although I must admit that I occasionally do), but the "control-variable" is always outside of the loop's parameters on a "For idx" loop once it drops out.
    Since it is defined behavior there is nothing wrong with relying on it. The manual explicitly says:

    After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.
    You might consider this a liberal interpretation of the statement in the manual. However it works and has through several versions of VB. In any case VB6 is unlikely to change any time soon anyway. I consider it a feature that can be relied on.

  7. #7
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,133

    Re: Exit For within the body of a "For Each" statement

    I see no problem at all with using an Exit For in either case so long as you understand how it works there will be no issue.

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2010
    Posts
    264

    Re: Exit For within the body of a "For Each" statement

    Quote Originally Posted by jmcilhinney View Post
    What happened when you tried it for yourself?
    Actually I forgot to mention in my first post that I tested it, and it worked for me.
    However, I just decided to check the documentation to make sure what I was doing was standard.
    And I couldn't find any documentation about it online.
    All my google searches found documentation about VB-2015, VB-2008 and VB.Net, but nothing about VB6.
    For example these ones:
    https://msdn.microsoft.com/en-us/library/5ebk1751.aspx
    https://msdn.microsoft.com/en-us/library/t2at9t47.aspx
    https://msdn.microsoft.com/en-us/lib...(v=vs.90).aspx
    https://msdn.microsoft.com/en-us/library/5z06z1kb.aspx
    Or a good example (not documentation) which is about VB.Net:
    http://stackoverflow.com/questions/5...-for-in-vb-net
    Looks like there is no documentation on this issue (the full definition of the For...Each statement similar to the first three links above) for VB6, or if there is, I couldn't find it.
    Can anybody please point me to the proper documentation if it exists?
    Regards.

  9. #9
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    12,133

    Re: Exit For within the body of a "For Each" statement

    There was lots of documentation online related to VB6 but you've got to consider that the product is nearing 20 years in age now and most of that stuff has been archived away some of it has been gone for a decade already.

  10. #10
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    2,975

    Re: Exit For within the body of a "For Each" statement

    @dilettante post #6: Yeah, understanding what the compiler (and p-code interpreter) must be doing, I'd agree that it can be relied upon. I suppose why I said that it's not necessarily recommended is that it's a bit obscure when reading code that does it. But I do agree that it's probably quite reliable, and that's almost certainly the case in just about any programming language we happen to be working with.

    @IliaPreston: Here's a copy-paste from the VB6 installed MSDN:

    Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example If…Then, and transfers control to the statement immediately following Next.
    And that's in the help page titled "For Each...Next Statement". In fact, here's the syntax they provide:

    Code:
    Syntax
    
    For Each element In group
    [statements]
    [Exit For]
    [statements]
    
    Next [element]
    Take Care,
    Elroy

  11. #11
    Fanatic Member
    Join Date
    Feb 2017
    Posts
    526

    Re: Exit For within the body of a "For Each" statement

    Quote Originally Posted by IliaPreston View Post
    Can anybody please point me to the proper documentation if it exists?
    Regards.
    https://msdn.microsoft.com/en-us/library/hh127509.aspx

    Product Documentation --> Reference --> Language Reference --> Statements --> A-H --> For Each...Next Statement

    https://msdn.microsoft.com/en-us/lib...(v=vs.60).aspx

    Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example IfThen, and transfers control to the statement immediately following Next.

  12. #12

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2010
    Posts
    264

    Re: Exit For within the body of a "For Each" statement

    Thanks a lot for all the great help and advice
    I am going to close this thread.

  13. #13

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2010
    Posts
    264

    Re: Exit For within the body of a "For Each" statement

    By the way, I tried to rate the posts before closing this thread, but it doesn't let me do so.
    It says: "You must spread some more reputation around before giving it to ..."
    Have a good day everybody.
    Ilia

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.