我可以将多个文本文件导入到一个Excel表单中吗?

我有一个文件夹与多个文本文件,我每天添加一个文本文件。 所有的文本文件都是相同的格式和pipe道分隔。

是否有可能创buildExcel的代码,将自动从多个文本文件导入到一个工作表的数据?

我发现一些代码将导入该文件夹中的所有文本文件,但仅当我将其全部更改为逗号分隔第一。 另外,如果我将文件添加到文件夹,我无法更新它。

任何帮助将不胜感激!

通常处理文件的一个好方法就是“FileSystemObject”。 为了在VBA中可用,你需要添加一个引用:

(selectTools \ References菜单,在References对话框中select'Microsoft Scripting Runtime')

下面的代码示例将读取文件夹中的所有文件,一次一行读取其内容,将每行分割为| 分隔的位,并将这些位写入从单元格A1开始的活动工作表,每行一行。

Sub ReadFilesIntoActiveSheet() Dim fso As FileSystemObject Dim folder As folder Dim file As file Dim FileText As TextStream Dim TextLine As String Dim Items() As String Dim i As Long Dim cl As Range ' Get a FileSystem object Set fso = New FileSystemObject ' get the directory you want Set folder = fso.GetFolder("D:\YourDirectory\") ' set the starting point to write the data to Set cl = ActiveSheet.Cells(1, 1) ' Loop thru all files in the folder For Each file In folder.Files ' Open the file Set FileText = file.OpenAsTextStream(ForReading) ' Read the file one line at a time Do While Not FileText.AtEndOfStream TextLine = FileText.ReadLine ' Parse the line into | delimited pieces Items = Split(TextLine, "|") ' Put data on one row in active sheet For i = 0 To UBound(Items) cl.Offset(0, i).Value = Items(i) Next ' Move to next row Set cl = cl.Offset(1, 0) Loop ' Clean up FileText.Close Next file Set FileText = Nothing Set file = Nothing Set folder = Nothing Set fso = Nothing End Sub 

该子是故意简化,保持清晰(我希望),将需要工作,使健壮(例如添加error handling)

听起来好像运行一个脚本来遍历目录中的所有文件,创build一个由所有文件的内容组成的新文件作为新行,并将其保存为csv。 就像是:

 import os basedir='c://your_root_dir' dest_csv="<path to wherever you want to save final csv>.csv" dest_list=[] for root, subs, files in os.walk(basedir): for f in files: thisfile=open(basedir+f) contents=thisfile.readlines() dest_list.append(contents) #all that would create a list containing the contents of all the files in the directory #now we'll write it as a csv f_csv=open(dest_csv,'w') for i in range(len(dest_list)): f_csv.write(dest_list[i]) f_csv.close() 

你可以在某个地方保存一个脚本并运行它,然后在excel中打开生成的csv。 这假设你想从每个文件中获取特定目录中的数据,并且你需要的所有文件都在一个目录中。

您可以使用Schema.ini( http://msdn.microsoft.com/en-us/library/ms709353 ( VS.85 ) .aspx ),Jet驱动程序和联合查询,运气好。