将数据从文本文件读入VBA数组

时间:2014-05-27 10:28:49

标签: vba powerpoint-vba

我有以下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

...我试图从文件中逐行读取文本(假设' sample.txt'是常规的ascii文件)并将此数据分配给连续的元素在数组中。然而,当我运行它时,我将所有数据都放在数组的第一个值中。有人可以帮我解决我做错的事吗?

例如,如果' sample.txt'是:

foo
bar
...
dog
cat

...我希望这些单词中的每一个都在VBA中的连续数组元素中。

谢谢!

2 个答案:

答案 0 :(得分:6)

你拥有的一切都很好;如果所有内容都以dataArray(0)结尾,那么文件中的行不使用CrLf分隔符,因此line input正在抓取所有内容。

相反;

open strFileName for Input as #1
dataArray = split(input$(LOF(1), #1), vbLf)
close #1

假设分隔符为VbLf(它将来自* nix系统)

答案 1 :(得分:0)

这是有关如何在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