Load text from File to array??

  • 14 years ago
    I have been trying to make a function for first, loading some words from a file (one word on each line) and then putting them into a array...

    Can someone help me, pretty please? :P
  • 14 years ago

    Hi,

    Open a std. exe project and set a reference to 'Microsoft Scrpting Runtime'.
    Add a command button and paste the following code.

    To test I have created a file called  names.txt in d:

    Private Sub Command1_Click()
    Dim fso As New FileSystemObject
    Dim ts As TextStream

    Dim arNames() As String
    Dim l As Long
    Dim sNamesInArray As String

    'open text file
    Set ts = fso.OpenTextFile("d:\names.txt")

    Do While Not ts.AtEndOfStream
        'populate array with a line from text file
        ReDim Preserve arNames(l)
        arNames(l) = ts.ReadLine
        l = l + 1
    Loop


    'to test whats in the array
    For l = 0 To UBound(arNames)
        If Len(Trim$(sNamesInArray)) = 0 Then
            sNamesInArray = arNames(l)
        Else
            sNamesInArray = sNamesInArray & "," & arNames(l)
        End If
    Next

    MsgBox "Names in array - " & sNamesInArray

    End Sub

    I hope this helps.

    Cheers
    Prakash.











































  • 14 years ago

    use the ff. code :

    Public Function FileToArray(TextFileName As String) As Variant

      Dim FileCntnr As String
        
      Open TextFileName For Input As #1
      FileCntnr = Input(LOF(1), 1)
      FileToArray = Split(FileCntnr, vbCrLf)
      Close #1




    End Function

     

    to use this :

    Dim MyArray() As String

    MyArray = FileToArray("C:\Sample.txt")

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“My definition of an expert in any field is a person who knows enough about what's really going on to be scared.” - P. J. Plauger