?
Solved

How to read a text file line by line that contains multiple lines in visual basic

Posted on 2007-10-14
13
Medium Priority
?
244 Views
Last Modified: 2010-04-30
Hello fellas, here is the deal:

I have an input text file like this:

"Please enter user name followed by an equal to operator and further followed by Records Management contact name"
AAAAA=BBBBB
CCCC=DDDDD
EEEEE=FFFFF

And my VB code to read the input file is like this:
    Open "C:\file.txt" For Input As #1
    Do Until EOF(1)
    Line Input #2, sUserRecMgtCnt
    iIndex1 = InStr(Trim(sUserRecMgtCnt), "=")
    sUserInput = Mid(Trim(sUserRecMgtCnt), 1, iIndex1 - 1)

I am able to get the first part of the line (until the'=' operator) but I dont understand how I could capture the word past the '=' operator. I tried using the Chr$(13) (and Chr$(10)) for capturing the carriage return and/or new line character, but totally in vain.
So, I would like to know how to capture the second part of the string from '='  operator. Also, the second question is -

While reading the above input file, I have a standard comment in the beginning "Please enter user name followed by...da.da...daaa.daa...daaaa..daaa"

I want this line be ignored while reading  the input. How could I do that?

Thanks for any help offered
Jammer


           
0
Comment
Question by:Jammerules
  • 3
  • 3
  • 2
  • +3
13 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 800 total points
ID: 20074631
something like this:

 Open "C:\file.txt" For Input As #1
 while not EOF(1)
    Line Input #2, sUserRecMgtCnt

    if sUserRecMgtCnt like "*=*" then
      iIndex1 = InStr(Trim(sUserRecMgtCnt), "=")
      sUserInput = Mid(Trim(sUserRecMgtCnt), 1, iIndex1 - 1)
      sValue = Mid(Trim(sUserRecMgtCnt), iIndex1 + 1)
    end if

  wend
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 800 total points
ID: 20074651
Try...

    Dim ff As Integer
    Dim fileName As String
    Dim inputLine As String
    Dim values() As String
    Dim UserName As String
    Dim RecordsContact As String
   
    fileName = "c:\file.txt"
    ff = FreeFile
    Open fileName For Input As #ff
    Line Input #ff, inputLine ' discard the first line
    While Not EOF(ff)
        Line Input #ff, inputLine
        values = Split(inputLine, "=")
        UserName = values(0)
        RecordsContact = values(1)
        Debug.Print "UserName: " & UserName, "RecordsContact: " & RecordsContact
    Wend
    Close #ff
0
 
LVL 76

Assisted Solution

by:GrahamSkan
GrahamSkan earned 400 total points
ID: 20074652
Use the Split finction

Dim Lineparts() as String
'...

If INSTR(sUserRecMgtCnt,"Please enter user name") = 0 Then
    LineParts = Split(sUserRecMgtCnt. =")
    strLeftHalf = LineParts(0)
    strRightHalf = LineParts(1)
End IF
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 20074657
You need to use the SAME file handle number for you operations:

    Open "C:\file.txt" For Input As #1
    Do Until EOF(1)
    Line Input #2, sUserRecMgtCnt

You open it as #1 and use "1" in the loop, but are reading from #2?
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 20076000
good catch, idle_mind !

you should indeed not "hard-code" the file number, but use freefile:


 dim fHandle as integer  
 fHandle = freefile
 Open "C:\file.txt" For Input As #fHandle
 while not EOF(fHandle)
    Line Input #fHandle, sUserRecMgtCnt

    if sUserRecMgtCnt like "*=*" then
      iIndex1 = InStr(Trim(sUserRecMgtCnt), "=")
      sUserInput = Mid(Trim(sUserRecMgtCnt), 1, iIndex1 - 1)
      sValue = Mid(Trim(sUserRecMgtCnt), iIndex1 + 1)
    end if

  wend

 close #fHandle
0
 
LVL 10

Expert Comment

by:peetm
ID: 20076653
I personally would use the FileSystemObject to read past however many lines your comment header is [one then?].  Usually people have some sort of leading delimiter for such things, e.g., like VB has for its own comment type - you use " it seems.

If the file really does look like this ...

"Please enter user name followed by an equal to operator and further followed by Records Management contact name"
AAAAA=BBBBB
CCCC=DDDDD
EEEEE=FFFFF


    Dim fso As New Scripting.FileSystemObject
   
    Dim txs As TextStream
   
    Dim sa() As String
   
    Dim n As Integer
   
    Set txs = fso.OpenTextFile(fileName, ForReading)
   
    txs.SkipLine
   
    sa = Split(Replace(txs.ReadAll, vbCrLf, "="), "=")
   
    For n = 1 To UBound(sa) - 1 Step 2
   
        Debug.Print sa(n)
   
    Next n


Output:

BBBBB
DDDDD
FFFFF


0
 
LVL 10

Expert Comment

by:peetm
ID: 20076657
>>Dim fso As New Scripting.FileSystemObject

Add a reference to 'Microsoft Scripting Runtime' for that, or use:

Dim fso As Object

Set fso = CreateObject("Scripting.FileSystemObject")
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 20076715
@peetm:
just a small remark: your suggestion to replace vbcrlf by =, and the read only every second array item has a potential "flaw":
if some day, a value containing a "=" will be stored, this will break.
altough this is not the case here, this could be "forgotten" when copying the code over to another app... and boum...
0
 
LVL 10

Expert Comment

by:peetm
ID: 20079318
>>@peetm:
just a small remark:

Yes, any delimited source that doesn't adhere to a bnf strict grammar will have similar problems.  One imagines here that '=' appears only in this context.
0
 
LVL 1

Expert Comment

by:LostIt6
ID: 20081013
You seem to have a parsing problem. I think you ned the Mid function built into VB to get what comes after the =. I wrote up a quick example.

To try this code now create a new VB Exe. Add a textbox to the form, make set multiline True and Scrollbars Vertical.

' EXAMPLE
Private Sub Form_Load()
    Dim FF As Long
    Dim mFName As String
    Dim mLine As String
    Dim mKey As String
    Dim mValue As String
    Dim mPos As Long
    mFName = "c:\file.txt"
    FF = FreeFile
    Open mFName For Input As #FF
        Do While Not EOF(FF)
            Input #FF, mLine
            ' Make sure the line contains a key value pair
            mPos = InStr(mLine, "=")
            If mPos > 0 Then
                ' The key is to the left of the =
                mKey = Left(mLine, mPos - 1)
                ' The value is to the right of the =
                mValue = Mid(mLine, mPos + 1)
                ' #######
                ' Add the rest of your code the processes the key and value here
                ' #######
                ' The next three lines just display the pairs in a textbox
                Text1.SelStart = Len(Text1.Text)
                Text1.SelText = mKey & " - " & mValue & vbCrLf
                Text1.SelStart = Len(Text1.Text)
            End If
        Loop
    Close #FF
End Sub
0
 
LVL 1

Expert Comment

by:LostIt6
ID: 20081107
I apoligize, you are using mid... but my Example solution is cound.
I wouldn't use Trim inside of Instr. It can lead to errors in the return value of Instr. Trim your string before you process it.

' Your code modified
    FF = FreeFile
    Open "C:\file.txt" For Input As #FF
    Do Until EOF(FF)
    Input #FF, sUserRecMgtCnt
    sUserRecMgtCnt = Trim(sUserRecMgtCnt)
    iIndex1 = InStr(sUserRecMgtCnt, "=")
    sUserInput = Mid(sUserRecMgtCnt, 1, iIndex1 - 1)
    sValue = Mid(sUserRecMgtCnt, iIndex1 + 1)
0
 

Author Comment

by:Jammerules
ID: 20092978
Hello everybody.

I am extremely sorry for not responding until now. I had been busy with my other stuff and did not have time to test your solutions. Please give me one more day before I post a reply and accept one/multiple solutions. Thanks a bunch again for all the replies. I appreciate each and everybody's time!

Jammer
0
 

Author Comment

by:Jammerules
ID: 20106670
Thanks each and everyone for theri respective answers. Although, I could not award points to everyone with their just fantastic answers, I had to share points between the first three persons who answered as the question arrived!

Y'all are wonderful...keep up the good work!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Suggested Courses
Course of the Month15 days, 16 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question