Excel VBA:处理 CSV 文件数据的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9569780/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:27:21  来源:igfitidea点击:

Excel VBA: Best way to work with data of CSV file

excelvbacsvexcel-vba

提问by tyrex

I am looking for a direct and efficient method to read out csv-files and handily work with the data in Excel/VBA?

我正在寻找一种直接有效的方法来读取 csv 文件并在 Excel/VBA 中轻松处理数据?

The best thing would be: direct access of data by specifying row and column. Can you tell me of your preferred option? Do you know an additional option to the following two?

最好的办法是:通过指定行和列直接访问数据。你能告诉我你最喜欢的选择吗?您知道以下两个选项的附加选项吗?

A:Use Workbooks.Openor Workbooks.OpenTextto open the csv-file as a workbook. Then work with the workbook (compare this thread).

答:使用Workbooks.OpenWorkbooks.OpenText将 csv 文件作为工作簿打开。然后使用工作簿(比较此线程)。

B:Use Open strFilename For Input As #1to write the data into a string. Work with the string (compare this thread).

B:用于Open strFilename For Input As #1将数据写入字符串。使用字符串(比较此线程)。

Thanks a lot!

非常感谢!

==========EDIT=========

==========编辑==========

Let me add what I have learned from your posts so far: The optimal option to do the task depends too much on what you want to do exactly, thus no answer possible. Also, there are the following additional options to read csv files:

让我补充一下到目前为止我从你的帖子中学到的东西:完成任务的最佳选择在很大程度上取决于你想要做什么,因此没有可能的答案。此外,还有以下附加选项可以读取 csv 文件:

C:Use VBScript-type language with ADO (SQL-type statements). I still am figuring out how to create a minimal example that works.

C:使用带有 ADO 的 VBScript 类型语言(SQL 类型语句)。我仍在弄清楚如何创建一个有效的最小示例。

D:Use FileSystemObject, see e.g. this thread

D:使用FileSystemObject,参见例如这个线程

采纳答案by jdh

The fastest and most efficient way to add CSV data to excel is to use Excel's text import wizard. This parses CSV file, giving you several options to format and organize the data. Typically, when programming one's own CSV parser, one will ignore the odd syntax cases, causing rework of the parsing code. Using the excel wizard covers this and gives you some other bonuses (like formatting options). To load csv, (in Excel 2007/2010) from the "data" tab, pick "From Text" to start the "Import Text Wizard". Note the default delimiter is tab, so you'll need to change it to comma (or whatever character) in step 2.

将 CSV 数据添加到 Excel 的最快、最有效的方法是使用 Excel 的文本导入向导。这会解析 CSV 文件,为您提供多种格式化和组织数据的选项。通常,在编写自己的 CSV 解析器时,会忽略奇怪的语法情况,导致解析代码的返工。使用 excel 向导涵盖了这一点,并为您提供了一些其他好处(如格式选项)。要从“数据”选项卡加载 csv(在 Excel 2007/2010 中),请选择“来自文本”以启动“导入文本向导”。请注意,默认分隔符是制表符,因此您需要在步骤 2 中将其更改为逗号(或任何字符)。