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!

I stink @ arrays 1

Status
Not open for further replies.

RonRepp

Technical User
Feb 25, 2005
1,031
0
0
US
Hi all:

I'm trying to add to an array and I keep getting an "Index out of bounds error".

Code:
Set FSO = CreateObject("Scripting.FileSystemObject")
Set F = FSO.OpenTextFile(strFilePathName, 1, False)
i = 0

Do While F.AtEndOfStream <> True
    RetString = F.ReadLine
     Replace RetString, vbCrLf, ""
    FileArray(i) = RetString
Loop
F.Close

Any help will be greatly appreciated.

Ron Repp

If gray hair is a sign of wisdom, then I'm a genius.

My newest novel: Wooden Warriors
 
An array needs to be dimensioned--given a size--before you can access an index inside of it. They start out empty if you declare it like such:

Dim FileArray() as String

Or you can declare it with a fixed size if you know exactly how many indexes you need:

Dim FileArray(10) as String

If you don't know how large you'll need it to be, you declare it empty to start with, and then use ReDim to resize it as you add to it.
I also suggest in your example above to add a reference to the "Microsoft Scripting Runtime" to your project, and ditch the CreateObject statement.

Code:
    Dim FileArray() As String
    Dim fso As Scripting.FileSystemObject
    Dim F As TextStream
    Dim i As Integer
    Dim RetString As String
    
    Set fso = New Scripting.FileSystemObject
    Set F = fso.OpenTextFile(strFilename, 1, False)
    
    i = 0
    Do While Not F.AtEndOfStream
        ReDim Preserve FileArray(i)
        RetString = Replace(F.ReadLine, vbCrLf, "")
        FileArray(i) = RetString
        i = i + 1
    Loop
    F.Close
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top