1

I'd like to define an array like:

sample_array = Array( _
"foo", _
"bar", _
...
"dog", _
"cat" _
)

...in a macro written in VB for Applications (PowerPoint 2010 in this case), but I need to define the array from a text file that would just be formatted like:

foo
bar
...
dog
cat

What is the simplest way to define a text file path and read the values (assume they are always regular ascii strings) directly into an array?

Thanks!

HotDogCannon
  • 2,113
  • 11
  • 34
  • 53

2 Answers2

6
Dim arr() as String
dim i as Integer
i=0
Open "c:\test.txt" For Input As #1 ' Open file for input.
Do While Not EOF(1) ' Loop until end of file.
    Line Input #1, arr(i) ' read next line from file and add text to the array
    i=i+1
    redim preserve arr(i) ' Redim the array for the new element
Loop
Close #1 ' Close file.
kiks73
  • 3,718
  • 3
  • 25
  • 52
  • 1
    Redim can only be used with an array that was originally declared without a fixed size. So you have to Dim arr(), then later Redim arr(0) (to get started), and then can use Redim in the loop. – gwideman Jul 12 '16 at 06:07
  • This code is not structured such that it will answer the question. The question is how to create an array of length matching the number of items in the file. Even if this code was fixed, it would always create a blank item at the end of the array. This script should have the redim line moved above the "line input #1, arr(i)" line. – DAG Dec 13 '18 at 19:33
6

You could load the whole file in at once and split it by newlines as follows

Sub read_whole_file()
    Dim sFile As String, sWhole As String
    Dim v As Variant
    sFile = "C:\mytxtfile.txt"
    Open sFile For Input As #1
    sWhole = Input$(LOF(1), 1)
    Close #1
    v = Split(sWhole, vbNewLine)
End Sub
xificurC
  • 1,168
  • 1
  • 9
  • 17