将文本文件中的数据读入 VBA 数组 [英] Reading in data from text file into a VBA array

查看:104
本文介绍了将文本文件中的数据读入 VBA 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 VBA 代码:

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

我正在尝试从文件中逐行读取文本(假设sample.txt"是一个常规的 ascii 文件),并将这些数据分配给数组中的连续元素.

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.

当我运行它时,我在数组的第一个值中获取所有数据.

When I run this, I get all my data in the first value of the array.

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

For example, if 'sample.txt' is:

foo
bar
...
dog
cat

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

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

推荐答案

你所拥有的就好;如果所有内容都以 dataArray(0) 结尾,则文件中的行没有使用 CrLf 分隔符,因此 line input 正在抓取所有内容.

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.

相反;

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

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

Assuming the delimiter is VbLf (what it would be coming from a *nix system)

这篇关于将文本文件中的数据读入 VBA 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆