VBA For loop not exiting

前端 未结 3 965
-上瘾入骨i
-上瘾入骨i 2021-01-20 16:25

I am looping through rows of a table and deleting rows if certain conditions are not met. For some reason my for loop never exits even when its done. What am I doing wrong?<

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 16:56

    You are subtracting 1 from the loop variable, so it loops forever.

    In Visual Basic for loops, "from" and "to" are calculated once at the beginning (they are fixed), but the loop variable is increased each time. So

    For r = fromExp to toExp
      SomeCode()
    End For
    

           behaves the same as

        Dim f = fromExp
        Dim t = toExp
    
        r = f
    
        While (r < t)
           SomeCode()
           r = r + 1
        End While
    

    In your example, the code changes toExp

    For r = fromExp to toExp
       toExp = toExp + 1
       r = r - 1
    EndFor
    

           but that doesn't affect the loop:

        Dim f = fromExp
        Dim t = toExp
    
        r = f
    
        While (r < t)
           toExp = toExp + 1   // does not affect the loop
           r = r - 1
           r = r + 1           // r is unchanged
        End While
    

    The loop variable is unchanged, so it loops forever.

    Best practice: do not alter the loop variable within a For loop.

提交回复
热议问题