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

Writing items from a list box to a text file in C drive

Status
Not open for further replies.

domt

Programmer
Mar 13, 2001
115
0
0
US
I have a list box (List3) with several items in it.
I want to store them in a text file on my C drive.
The following does not work.

fnum = FreeFile()
Open "C:\Stores.txt" For Output As #fnum
For Ct1 = 0 To List3.ListCount - 1
Write #fnum, List3.List(Ct1)
Next
Close fnum

Can anyone tell me what's wrong?
Any help will be appreciated.

Doug
 
Seems to work for me. Are you sure the listbox has data in it before you try to export? What exactly does not work?

Code:
Private Sub Command1_Click()
    fnum = FreeFile()
    Open "C:\Stores.txt" For Output As #fnum
    For Ct1 = 0 To List3.ListCount - 1
      Write #fnum, List3.List(Ct1)
    Next
    Close fnum
End Sub

Private Sub Form_Load()
    With List3
        .AddItem "Apple"
        .AddItem "Orange"
        .AddItem "Pear"
    End With
End Sub

Swi
 
Hey Swi
It works!
But I'll be darned why the same code didn't work before.
I copied your code and pasted it in, but it was identical to mine????
Now if you could help me in another part of the operation.
When the program starts, I would like for the Load page to automaticaly read from the Stores file on C and populate list3 with the Stores file contents. However, the first time the program is used, there would be no Stores file to read and the program hangs up. What code can I use to avoid this.
Thanks very much for your interest and help.
Doug
 
Doug,

You make want to look into the FileSystemObject. It has a lot of the functionality built into it that you are looking for.

Code:
Option Explicit
' Create a reference for Microsoft Scripting Runtim
Dim fso As FileSystemObject
Dim InStream As TextStream
Const FileName = "C:\Stores.txt"

Private Sub Form_Load()
    Set fso = New FileSystemObject
    If fso.FileExists(FileName) Then
        If fso.GetFile(FileName).Size > 0 Then
            Set InStream = fso.OpenTextFile(FileName, ForReading)
            Do
                List3.AddItem InStream.ReadLine
            Loop Until InStream.AtEndOfStream
            InStream.Close
            Set InStream = Nothing
        Else
            MsgBox "Stores file exists but has no contents!", vbInformation
        End If
    Else
        MsgBox "Stores file does not exist!", vbInformation
    End If
    Set fso = Nothing
End Sub

Swi
 
Swi
Works like a charm!
Thanks so much for the education and help.
Doug
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top