Results 1 to 2 of 2

Thread: Reading a textfile to a listbox

  1. #1

    Thread Starter
    Member
    Join Date
    May 2003
    Posts
    52

    Reading a textfile to a listbox

    Hi All,
    I have an excel macro which includes a form with two listboxes.

    I wish to load the contents of a 1.txt in the ListBox1 and the contents of file 2.txt into the ListBox2.

    I have been using the code as given below for the purpose... which works on one machine but seems to be giving some problems in another machine. Both the machines have the same version of Excel... maybe something to do with the issue of VB Runtime File upgrades...?

    Can someone tell me of some good code which is stable enough to work on all versions of Excel.. irrespective of the VB files in the machine!

    thanks,
    Lonely



    VB Code:
    1. Dim IsFileThere As String
    2. Dim tempString As String
    3. gFileName = "C:\Folder1\1.txt"
    4. gFileName2 = "C:\Folder1\2.txt"
    5. ' first, see if file exists, and prevent error if it doesn't
    6. ' Dir is a VB function that returns the full path to a file
    7. ' If file doesn't exist, Dir returns a blank, ie. ""
    8. IsFileThere = Dir(gFileName)
    9. If IsFileThere = "" Then
    10. ' just exit this sub, don't cause trouble
    11. Exit Sub
    12. End If
    13. ' now clear the list, or the list will keep growing
    14. ' it willl Append the txt file to the existing list
    15. listbox1.Clear
    16. ' OK, since the file does exist, read it in
    17. Open gFileName For Input As 1
    18. While Not EOF(1)
    19. ' tempString just holds one line at a time
    20. Line Input #1, tempString
    21. listbox1.AddItem RTrim(tempString)
    22. Wend
    23. Close 1
    24. Open gFileName2 For Input As 1
    25. While Not EOF(1)
    26. ' note that tempString just holds one line at a time
    27. Line Input #1, tempString
    28. ListBox2.AddItem RTrim(tempString)
    29. Wend
    30. Close 1
    I Was Born Lonely, Lived Lonely .... And Will Die Lonely!!

  2. #2
    Fanatic Member WorkHorse's Avatar
    Join Date
    Jul 2002
    Location
    Where you live.
    Posts
    591
    It doesn't appear you are clearing ListBox2 before adding items.

    The different versions of VBA are very similar. I don't know of any differences in any of the controls or language that you are using.

    What types of problems are you having?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width