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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Do Loop and If statement not working

Status
Not open for further replies.

NTesla

Programmer
Jul 19, 2002
146
US
Can someone please explain to me two things from the code below and how to fix the problems?

#1 Why would the If statement never be executed?
#2 Why no code past the Loop Statement is executed?

The Problem is that I open this file again later in the program for output, and I get an error that the file is already open. I have tried everything I can think of.

Private Sub Form_Load()
Dim BLNEOF As Boolean

On Error GoTo HandleErrors

BLNEOF = False

Open GSTRFilePath For Input As #1

Do

Input #1, GSTRInspectorName, GSTRInspectorNumber

CBOInspectorName.AddItem GSTRInspectorName
CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber
MsgBox "Not Closed", vbOKOnly, "NOT CLOSED" 'Trubleshooting Purposes
If EOF(1) = True Then
BLNEOF = True
MsgBox "Closed", vbOKOnly, "CLOSED" 'Trubleshooting Purposes
End If

Loop While BLNEOF = False

MsgBox "Closed", vbOKOnly, "CLOSED" 'Trubleshooting Purposes
Close

Form_Load_Exit:
Exit Sub

HandleErrors:

Select Case Err.Number

Case 53, 76 'File or path not found

Resume Form_Load_Exit 'Exit the procedure

Case 71 'Disk not ready

GINTResponse = MsgBox("Disk not ready. Retry?", _
vbRetryCancel + vbQuestion, "Disk Error")

If GINTResponse = vbRetry Then
Resume 'Try again
Else
End 'Exit Program
End If

'Case Else 'All other errors should cancel execution
' Err.Raise Err

End Select
End Sub
 

Hi NTesla:

Try moving the code from Form_Load() to Form_Activate().

Best to study up on the lifetime of a VB form. (I need to as well.) Some things cannot be done in Form_Load(). I don't know whether this is the case with your code.

Cassie
 
I tried to the move as sugested and it did not work.
 
Hi NTesla:

I copied your code to my machine and ran it. There was no problem, other than the addition of a few lines:

(1)
Code:
    CBOInspectorName.ListIndex = 0
as the next line after the Loop While statement.


(2)
Code:
    intFileNumber = FreeFile
(Replaced the filenumber 1 in your listings, all places, with intFileNumber.)

(3)
I also tidied the code up by doing variable declarations:
Code:
    Dim BLNEOF As Boolean
    Dim intFileNumber As Integer
    Dim GSTRInspectorName As String
    Dim GSTRInspectorNumber As String
    Dim GINTResponse As Integer

My test data file included two lines:
Code:
NTesla, 1
Cassie2002, 2

The program ran with no problems.

-------

I am a bit of a neat freak when it comes to programming. That is why I insist on things like Option Explicit, variable declarations, naming conventions and the use of safe filenumbers (using FreeFile).

Cassie
 
First of all, I was at the time of posting this on my notebook, now I'm on my desktop. I ran it one time where everything work right. (Well everything being discussed here). Know it won't work right on my desktop. I'm only using the working module edition, not a full blown version so to speak [thumbsdown](Got it in a text book). Could that have something to do with it.[wink]

Second, I knew about the Freefile statement but never used it. Mainly because I was unfamilier with it. If I have several files open and only want to close 2 or 3 or even 1 how would this be accomplished with out closeing all files.[3eyes]

Also, I guess every one has their own method to their maddness so to speak. What I do is For every variable I put three letter intials, for the kind of varible it is, I.E. BLN for Boolean, INT for Integer, CUR for Currency etc. then one letter intials before those to let me know (or Remind me) weather the are just for a sub (no letter) M (Module) or G (Global). Any way The variables With MXXX would have been Dimed at the very begining of the Form Module, and Global I have a separte module for, these will also be used though out the program. Just want to let you know this, not that it is important, to the problem at hand.:)
 
In answer to one of your questions - to close a single file just use Close #n where n is the file number to close.

I agree in theory the code should work, the file open error is due to the close staement not being executed. So the problem must be an error that is ignored by your error handler select case routine probably in one of these lines.
Open GSTRFilePath For Input As #1
Input #1, GSTRInspectorName, GSTRInspectorNumber
CBOInspectorName.AddItem GSTRInspectorName
CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber

Maybe try commenting out the 'on error goto errorhandler' and see what happens.


Hope this helps

 

Hi NTesla:

Here is the code that I ran on my machine successfully, if it of any help:
Code:
Option Explicit

Private Sub Form_Load()
    Dim BLNEOF As Boolean
    Dim intFileNumber As Integer
    Dim GSTRInspectorName As String
    Dim GSTRInspectorNumber As String
    Dim GINTResponse As Integer

    On Error GoTo HandleErrors

    BLNEOF = False
    intFileNumber = FreeFile
    Open "c:\test1.txt" For Input As #intFileNumber

    Do
    
        Input #intFileNumber, GSTRInspectorName, GSTRInspectorNumber
    
        CBOInspectorName.AddItem GSTRInspectorName
        CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber
        MsgBox "Not Closed", vbOKOnly, "NOT CLOSED" 'Trubleshooting Purposes
        If EOF(intFileNumber) = True Then
            BLNEOF = True
            MsgBox "Closed", vbOKOnly, "CLOSED" 'Trubleshooting Purposes
        End If

    Loop While BLNEOF = False
    CBOInspectorName.ListIndex = 0
    MsgBox "Closed", vbOKOnly, "CLOSED" 'Trubleshooting Purposes
    Close #intFileNumber

Form_Load_Exit:
    Exit Sub
    
HandleErrors:

    Select Case Err.Number

        Case 53, 76                      'File or path not found
            Resume Form_Load_Exit   'Exit the procedure

        Case 71                         'Disk not ready
            GINTResponse = MsgBox("Disk not ready. Retry?", _
            vbRetryCancel + vbQuestion, "Disk Error")

            If GINTResponse = vbRetry Then
                Resume                  'Try again
            Else
                End       'Exit Program
            End If

        Case Else               'All other errors should cancel execution
            Err.Raise Err

    End Select
End Sub

Cassie
 
NTesla,
have you tried to set breakpoint inside error handler?

I think there could be error you didn't catch.
(like, un-matched pair of data. You try to read two values - but it found only one - hence error).
(BTW somehow you have 'case else' part remmed out in error handler?)

So it's (probably) also error in data file - that's while program works in one place but not in the other (different data).

BTW probably you should move 'close' to Form_Load_Exit label as well.

Hope this can help.
 
Just got a chance to work on the problem again. I have commented out the error handler as recommended and know I get a type mismatch on the following line.

CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber

It will read in all the data fine until it gets to the last entry in the file before I get the error. I don't see the error. I even copied the same line from what Cassie has above and compaired them they are exactly alike. Maybe it just needs a fresh pair of eys. I have not made any code changes from what is above in my orginal post.

Thanks for all the help
 
Hi NTesla:

The algorithm that you chosen to implement is very sensitive to the structure of the data file. Too many or too few carriage-returns/line-feeds after the last line will cause the generate errors.

The data file that I used contains the following
NTesla, 1<CRLF>
Cassie2002, 2<CRLF>

where <CRLF> represents the carriage-return/line-feed at the end of each line.

If that last <CRLF> is missing or if there an additional <CRLF> after it, then the program is likely to generate errors.

My preferred way is as follows:
Code:
    Do
        Line Input#intFileNumber, strTemp
        if Len(Trim(strTemp)) > 0 then
            intComma = Instr(1, strTemp, &quot;,&quot;)
            If intComma > 0 then
                On Error Goto SkipBadLine
                GSTRInspectorName = Left(strTemp, intComma - 1)
                
                GSTRInspectorNumber = CInt(Trim(Mid(strTemp, intComma + 1)))
                CBOInspectorName.AddItem GSTRInspectorName
                CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber
SkipBadLine:
                On Error Goto 0
                If EOF(intFileNumber) = True Then BLNEOF = True
            End If
        End If
    Loop While Not BLNEOF

This code (not tested) incorporates error checking to prevent the problem of too many or too few <CRLF> at the end of the data file and some of the problems of ill-formatted lines in the data file.

Hope this helps.

Cassie
 
It might help, however their are a few commands I dont recognize. Such as Trim and Instr. What are the purpose of these two commands.

Do I understand it right that this would read both the Name and Number in to on variable and then split them into seperate variables?

Also does the Left and Mid work different in Visual Basic. I know in Qbasice Left is the first 4 Char from the left, Right is the first 4 char from the right
 

Hi NTesla:

Trim: removes &quot;whitespace&quot; (tabs, spaces, etc) from the ends of strings.

Instr: Searches one string, from a given position, for the first occurrence of a second string.

The Line Input command will read in the entire line, including the name, comma, and number. The subsequent code then splits the line into the name and number.

Left(strTemp, I): Returns the first I chars of strTemp

Mid(strTemp, intStart, intEnd): returns the characters from strTemp, starting at intStart and ending at intEnd.

Cassie
 
GSTRInspectorNumber = CInt(Trim(Mid(STRTemp, INTComma + 1)))

I'm now getting a Type Mismatch at this line. Up to this point it sees to work fine so far. But I have never used these commands so I have no Idea what the problem can be. I copied your code from you post. I also commented mine out
 
I also just know noticed that the error message does not accure untile the thired entry in the file, their are four (for now), also the CBOInspectorNumber = &quot;&quot; all the time, No matter what the file entry it is currently reading in.

Cassie I really appreciate you help. If I can get this part of my program working I'd be greetful.
 

Hi NTesla:

Can you post your data file (or at most the first ten lines)? With your data file I may be able to work up the code further. No garauntees.

Cassie
 
&quot;John Doe&quot;,&quot;987654321&quot;
&quot;Dan Smith&quot;,&quot;123456789&quot;
&quot;Nikola Tesla&quot;,&quot;188618561&quot;
&quot;Thomas Edison&quot;,&quot;000000000&quot;
&quot;Ben Franklin&quot;,&quot;999999999&quot;
&quot;George Westinghouse&quot;,&quot;357951852&quot;

I also made an error in my last post. It is actually the Secondentry in the file I get the error.
 

Hi NTesla:

Sorry about the slip-up. I had assume that the numbers were below the limit for integers (32767), whereas your data file shows them to be beyond integers. So, I altered the INTComma to LNGComma and changed the CInt to Clng. Another feature of your data file is that each item is in quotes; so, I added a line to remove the quotes from the inputted line. The updated code, which ran with your data file, is listed below (I altered the Open command to put the data file in my C:\ directory.)
Code:
Option Explicit

Private Sub Form_Load()
    Dim BLNEOF As Boolean
    Dim intFileNumber As Integer
    Dim GSTRInspectorName As String
    Dim GSTRInspectorNumber As String
    Dim GINTResponse As Integer
    Dim LNGComma As Long                    ' <--
    Dim STRTemp As String                   ' <--

    On Error GoTo HandleErrors

    BLNEOF = False
    intFileNumber = FreeFile
    Open &quot;c:\test1.txt&quot; For Input As #intFileNumber  ' <--

    Do
        Line Input #intFileNumber, STRTemp
        STRTemp = Replace(STRTemp, Chr(34), &quot;&quot;)       ' <--
        If Len(Trim(STRTemp)) > 0 Then
            LNGComma = InStr(1, STRTemp, &quot;,&quot;)         ' <--
            If LNGComma > 0 Then
                On Error GoTo SkipBadLine
                GSTRInspectorName = Left(STRTemp, LNGComma - 1)
                
                GSTRInspectorNumber = CLng(Trim(Mid(STRTemp, LNGComma + 1)))       ' <--
                CBOInspectorName.AddItem GSTRInspectorName
                CBOInspectorName.ItemData(CBOInspectorName.NewIndex) = GSTRInspectorNumber
SkipBadLine:
                On Error GoTo 0
                If EOF(intFileNumber) = True Then BLNEOF = True
            End If
        Else
            BLNEOF = True
        End If
    Loop While Not BLNEOF
    
    
    CBOInspectorName.ListIndex = 0
    MsgBox &quot;Closed&quot;, vbOKOnly, &quot;CLOSED&quot; 'Trubleshooting Purposes
    Close #intFileNumber

Form_Load_Exit:
    Exit Sub
    
HandleErrors:

    Select Case Err.Number

        Case 53, 76                      'File or path not found
            Resume Form_Load_Exit   'Exit the procedure

        Case 71                         'Disk not ready
            GINTResponse = MsgBox(&quot;Disk not ready. Retry?&quot;, _
            vbRetryCancel + vbQuestion, &quot;Disk Error&quot;)

            If GINTResponse = vbRetry Then
                Resume                  'Try again
            Else
                End       'Exit Program
            End If

        Case Else               'All other errors should cancel execution
            Err.Raise Err

    End Select
End Sub

Cassie
 


Oops, forgot to mention that I added two other lines:
Code:
    Else
        BLNEof = True

to the
Code:
If Len(Trim(STRTemp)) > 0 Then
statement.

Cassie
 
Another thing (my mind's on holiday today!) is to add:
Code:
    Err.Clear
between the
Code:
SkipBadLine:
and
Code:
On Error Goto 0
statements.

Cassie
 
Thanks Cassie.

I am at work right now and unfortuntly I forget my disk and USB Disk drive at home. But I appreciate your help!!

The Err.Clear with Clear am I guessing that Clears any errors.

It was not your fault the INT and LNG error I should have told you that the Inspector Numbers were 9 digits long . That may have been my problem I don't remember what I had.

I can't wait to get home and try this. I have trying to fix this off and one for what seems for ever.

One last thing (for this post anyway) if I get this working properly can this code with a few modifications be used to delete entries

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top