Search code examples
loopsvbscriptasp-classicfilesystemobject

In a set of loops, why is only the first one being considered?


This code is part of a function thats is being called several times.

for r = 0 to 4
    do until searchname.AtEndOfStream
        lineData = lcase(searchname.ReadLine())
        if instr(lineData,N(r))>0 then
            if (r = 0) then
                v = v + 1
            elseif (r = 1) then
                w = w + 1
            elseif (r = 2) then
                x = x + 1
            elseif (r = 3) then
                y = y + 1
            elseif (r = 4) then
                z = z + 1
            end if
        end if
    loop
next

My problem is that it only considers r = 0. I've tried ubound(N) instead. I've also tried replacing the for (r = 0) loop with five separate loops for v, w, x, y and z. I've tried several other methods and different formatting too, but it still didn't work.


Solution

  • After the r = 0 case, when the inner loop has reached searchname.AtEndOfStream and you increment to the next value or r, searchname is still at the end of the stream. Therefore, the do loop only runs for the first case of the for loop. Consider this alternative:

    do until searchname.AtEndOfStream
        lineData = lcase(searchname.ReadLine())
        for r = 0 to 4
            if instr(lineData,N(r))>0 then
                if (r = 0) then
                    v = v + 1
                elseif (r = 1) then
                    w = w + 1
                elseif (r = 2) then
                    x = x + 1
                elseif (r = 3) then
                    y = y + 1
                elseif (r = 4) then
                    z = z + 1
                end if
            end if
        next
    loop
    

    By switching the loops around, you don't reach the end of the stream until you've finished iterating over both.