【发布时间】:2013-07-27 08:04:06
【问题描述】:
我一直在尝试将多个大型文本文件导入到同一工作簿中的多个电子表格中。感谢这个网站上的其他帖子,我拼凑了一些似乎可以完成这项工作的 VBA 代码。唯一的问题是,由于文本文件中的数据没有标记,因此很难将它们区分开来进行分析。因此,我想在导入过程中用相应的文本文件标记每个电子表格。我使用的代码如下。
谢谢!
Sub ImportManyTXTs()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("I:\test\*.txt")
Do While strFile <> vbNullString
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "I:\test\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileFixedColumnWidths = Array(7, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub
编辑:设法弄清楚。刚刚在 End With 之后添加了 ws.Name = strFile。似乎工作得很好。
【问题讨论】:
-
确保遵循有效工作表名称的规则:Your Sheet Names are Killing My Formulas
-
哈哈。是的。那不是问题。设法弄清楚了。刚刚在 End With 之后添加了 ws.Name = strFile。似乎工作得很好。
-
我建议您输入您的答案作为问题的答案,并使用复选标记将其标记为已回答。是的,您可以提供自己的答案。