Reading in data from text file into a VBA array

て烟熏妆下的殇ゞ 提交于 2019-12-06 07:05:38

问题


I have the following VBA code:

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

...that I'm trying to use 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. When I run this however, I get all my data in the first value of the array. Can someone help me with what I'm doing wrong?

For example, if 'sample.txt' is:

foo
bar
...
dog
cat

...I want each one of these words in a consecutive array element in VBA.

Thanks!


回答1:


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.

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)



来源:https://stackoverflow.com/questions/23887066/reading-in-data-from-text-file-into-a-vba-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!