简体   繁体   English

Excel VBA文本文件到二维数组

[英]Excel VBA Textfile to 2d array

I am new to excel vba.我是 excel vba 的新手。 I want to read a textfile that contains text like this:我想阅读一个包含如下文本的文本文件:

John Smith Engineer Chicago 
Bob Alice Doctor New York 
Jane Smith Teacher St. Louis

So, I want to convert this into a 2D array so if I do print(3,3), it should return 'Teacher'.所以,我想把它转换成一个二维数组,所以如果我打印(3,3),它应该返回“老师”。 I am able to read entire file contents into one string but am having difficulty in converting it to a 2d array like above.我能够将整个文件内容读入一个字符串,但很难将其转换为上述二维数组。 Please advice on how to proceed.请就如何进行提供建议。 Thanks谢谢

unless the text file has some specific structure to it, you're going to struggle a bit.除非文本文件有一些特定的结构,否则你会有点挣扎。 Things that might make it easier are:可能使它更容易的事情是:

  • Does the text file contain line breaks at the end of each line?文本文件是否在每行末尾包含换行符?
  • Are all the names in [FirstName][LastName] format as per your example or might some have more/less words? [FirstName][LastName] 格式的所有名称是否都按照您的示例进行,或者有些名称可能有更多/更少的单词?
  • Does the Occupation always come directly after the name?职业总是直接跟在名字后面吗?
  • Are there a (very) limited number of Occupations?是否有(非常)有限数量的职业?

as mentioned by NautMeg, You have to make some assumptions on the data based on the provided template.正如 NautMeg 所提到的,您必须根据提供的模板对数据做出一些假设。

However we can assume that :但是我们可以假设:

  • a space is the delimiter空格是分隔符
  • The Final column is City, which can contain a space最后一列是城市,它可以包含一个空格
  • there are 4 columns有 4 列
    • First Name
    • Last Name
    • Profession职业
    • City/Location城市/地点

Using this information:使用此信息:

While Not EOF(my_file)
    Line Input #my_file, text_line
    // text_line contains the independent line
    i = i + 1
    // i is the line number
Wend

is how we retrieve each line.是我们检索每一行的方式。

Split ( Expression, [Delimiter], [Limit], [Compare] )

This will give you each item in the list.这将为您提供列表中的每个项目。 For index's < 3 (0 based index), they are unique columns of data and you can handle them however you want.对于索引 < 3(基于 0 的索引),它们是唯一的数据列,您可以根据需要处理它们。 For Index >=3, Join these together into 1 string .对于索引 >=3,将它们连接成 1 个字符串。

Join( SourceArray, [Delimiter] )

You'll likely want to make the delimiter in this case a simple space, since the split function will remove the space.在这种情况下,您可能希望将分隔符设为一个简单的空格,因为 split 函数将删除该空格。

That will allow you to parse the data AS is.这将允许您按原样解析数据。

However, for future reference if you can control the export of the text file, you should try exporting as a CSV file.但是,为了将来参考,如果您可以控制文本文件的导出,您应该尝试导出为 CSV 文件。

Good luck祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM