Search code examples
csvvb6

How to read and write comma delimited text values to file in VB 6.0


Okay let's say I have sample text file that includes some comma delimited values like so:

-1,0,3,0,5,4,6,7,8,9

And I want to make a program in VB 6.0 that opens that file, read the values and store them in variables which are displayed in text boxes like so (example):

Name: [ Value -1 ]
Nationality: [ Value 0 ]
Experience: [ Value 3 ]

and so on ..

So when I chance these values in the program text boxes and hit save file - it saves the file with the new values. Is that simple. Thank you guys !


Solution

  • (Note: this answer is assuming that the text file only contains one line.)

    First, you will need to read the text file:

    Dim rawData as string
    
    Dim sFileText as String
    Dim FileNo as Integer
    FileNo = FreeFile
    Open "C:\test.txt" For Input As #FileNo 'you should change the file path
    Line Input #FileNo, sFileText 'read the whole line
    rawData = sFileText 'store the first line of the text file in 'rawData'
    Close #FileNo
    

    Next, you need to split the rawData by the commas:

    Dim data() as string 'an array that will hold each value
    data = Split(rawData, ",") 'split 'rawData' with a comma as delimiter
    

    Now the first value is stored in data(0), second in data(1), etc.

    As far as the 'save file' button, you can do something like:

    Dim newData as String
    newData = data(0) & "," & data(1) & "," & data(2) 'etc.
    

    Then write it to a file.