将文本文件中的数据读入 VBA 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23887066/
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
Reading in data from text file into a VBA array
提问by HotDogCannon
I have the following VBA code:
我有以下 VBA 代码:
Sub read_in_data_from_txt_file()
Dim dataArray() As String
Dim i As Integer
Const strFileName As String = "Z:\sample_text.txt"
Open strFileName For Input As #1
' -------- read from txt file to dataArrayay -------- '
i = 0
Do Until EOF(1)
ReDim Preserve dataArray(i)
Line Input #1, dataArray(i)
i = i + 1
Loop
Close #1
Debug.Print UBound(dataArray())
End Sub
I'm trying to read in text line by line (assume 'sample.txt' is a regular ascii file) from a file and assign this data to consecutive elements in an array.
我正在尝试从文件中逐行读取文本(假设 'sample.txt' 是一个常规的 ascii 文件),并将这些数据分配给数组中的连续元素。
When I run this, I get all my data in the first value of the array.
当我运行它时,我将所有数据都放在数组的第一个值中。
For example, if 'sample.txt' is:
例如,如果“sample.txt”是:
foo
bar
...
dog
cat
I want each one of these words in a consecutive array element.
我希望这些单词中的每一个都在一个连续的数组元素中。
回答by Alex K.
What you have is fine; if everything ends up in dataArray(0)
then the lines in the file are not using a CrLf
delimiter so line input
is grabbing everything.
你所拥有的很好;如果一切都结束了,dataArray(0)
那么文件中的行没有使用CrLf
分隔符,所以line input
正在抓取所有内容。
Instead;
反而;
open strFileName for Input as #1
dataArray = split(input$(LOF(1), #1), vbLf)
close #1
Assuming the delimiter is VbLf
(what it would be coming from a *nix system)
假设分隔符是VbLf
(它将来自 *nix 系统)
回答by Adam Bouras
Here is a clean code on how to use for each loop in VBA
这是关于如何在 VBA 中使用每个循环的干净代码
Function TxtParse(ByVal FileName As String) As String
Dim fs, ts As Object
Dim strdic() As String
Dim oitem As Variant
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(FileName, 1, False, -2)
strdic = Split(ts.ReadAll, vbLf)
For Each oitem In strdic
If InStr(oitem, "YourString") <> 0 Then
Else
If InStr(1, oitem, vbTab) <> 0 Then
Debug.Print "Line number is : "; "'" & Replace(oitem, vbTab, "','") & "'"
Else
Debug.Print "Line number is : "; "'" & Replace(oitem, ",", "','") & "'"
End If
End If
Next
End Function