如何从Visual Basic for PowerPoint 2010中的文本文件填充数组

时间:2014-05-27 07:41:16

标签: vba powerpoint-vba powerpoint-2010

我想定义一个类似的数组:

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

...在VB for Applications(本例中为PowerPoint 2010)中编写的宏中,但我需要从一个文本文件中定义数组,该文件的格式如下:

foo
bar
...
dog
cat

定义文本文件路径并将值(假设它们总是常规的ascii字符串)直接读入数组的最简单方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:5)

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.

答案 1 :(得分:5)

您可以立即加载整个文件,然后按换行符拆分,如下所示

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