BertB
BertB

Reputation: 118

New array in For Next loop every iteration VBS

I have a section of code which opens each text file in a folder and I want to not only put the file name into an array but also split the text inside the file into an array, something like this:

i = 0
n = 1
For Each File In Folder
    i = i + 1
    Dim UserArray & i()
    Set openedFile = fso.OpenTextFile(File)
    Do Until openedFile.AtEndOfStream 
        Line = openedFile.ReadLine
        ReDim Preserve UserArray & i(n)
        UserArray & i(n) = Line
        n = n + 1
    Loop
    n = 0
Loop

The idea being that each line will later be strComp to another array of lines from a different text file. So each file needs to create a unique array name for its text contents and the number of files in any given folder varies.

The above does not work,any ideas?

Upvotes: 2

Views: 1422

Answers (2)

Erin Halbmaier
Erin Halbmaier

Reputation: 354

You could try an array of arrays. Like so:

Dim Userarray() As Variant
Dim subArray() As String

i = 0
n = 1

For Row = 0 To 4
    i = i + 1
    ReDim subArray(i)
    For Each cell In ActiveSheet.Range(Cells(i, 1), Cells(i, 5))
        ReDim Preserve subArray(n)
        subArray(n) = cell.Value
        n = n + 1
    Next
    ReDim Preserve Userarray(i)
    Userarray(i) = subArray
    n = 0
Next

(I didn't have files, so I was just using a range in Excel). I assume VBA is similar enough to VBScript for this to work...Results in the first row of data as an array in Userarray(1), the second row of data as an array in Userarray(2), etc.

Upvotes: 0

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

There are syntax errors in your code(Line 5,9,10 - fixed by using execute statements which allows you to declare variables dynamically during run time with different names) along with variable spelling mistakes(Line 8).

P.S. I am not making any changes to the logic applied here. Just trying to correct the mistakes.

i = 0
n = 0                                                   'initialised to 0
For Each File In Folder
    i = i + 1
    Execute "Dim UserArray"&i&"()"                      'used execute statement to declare arrays with new names based on the value of i for each file
    Set openedFile = fso.OpenTextFile(File)
    Do Until openedFile.AtEndOfStream 
        Line = openedFile.ReadLine                      'corrected the spelling mistake here
        Execute "ReDim Preserve UserArray"&i&"("&n&")"
        Execute "UserArray"&i&"("&n&")="&Line
        n = n + 1
    Loop
    n = 0
Loop

After this code, you should have UserArray1 for 1st file, UserArray2 for 2nd file and so on...

Upvotes: 2

Related Questions