【发布时间】:2011-02-08 19:54:08
【问题描述】:
我有一个包含多个文本文件的文件夹,我每天都会添加一个文本文件。所有文本文件都采用相同的格式并以竖线分隔。
是否可以为 excel 创建代码,自动将多个文本文件中的数据导入到一个工作表中?
我发现了一些可以从文件夹中导入所有文本文件的代码,但前提是我首先将其全部更改为逗号分隔。另外,如果我将文件添加到文件夹中,我无法更新它。
任何帮助将不胜感激!
【问题讨论】:
-
先加入他们并导入结果?
我有一个包含多个文本文件的文件夹,我每天都会添加一个文本文件。所有文本文件都采用相同的格式并以竖线分隔。
是否可以为 excel 创建代码,自动将多个文本文件中的数据导入到一个工作表中?
我发现了一些可以从文件夹中导入所有文本文件的代码,但前提是我首先将其全部更改为逗号分隔。另外,如果我将文件添加到文件夹中,我无法更新它。
任何帮助将不胜感激!
【问题讨论】:
一般来说,处理文件的一个好方法是“FileSystemObject”。要使其在 VBA 中可用,您需要添加对它的引用:
(选择工具\参考菜单。在参考对话框中,选择“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
sub 被刻意简化以保持清晰(我希望),并且需要努力使其健壮(例如添加错误处理)
【讨论】:
听起来运行一个脚本循环遍历目录中的所有文件,创建一个由所有文件内容组成的新文件作为新行,并将其保存为 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 驱动程序和联合查询。
【讨论】: