vba 如何从 Visual Basic for PowerPoint 2010 中的文本文件填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23883676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate an array from text file in Visual Basic for PowerPoint 2010
提问by HotDogCannon
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:
...在用 VB 编写的用于应用程序的宏中(在本例中为 PowerPoint 2010),但我需要从文本文件中定义数组,该文件的格式如下:
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?
定义文本文件路径并将值(假设它们始终是常规的 ascii 字符串)直接读入数组的最简单方法是什么?
Thanks!
谢谢!
回答by kiks73
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.
回答by xificurC
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