【发布时间】:2018-06-16 12:10:41
【问题描述】:
我每天都会转储 2 个不同的文本文件(在同一个文件夹中),这些文件每天都会被覆盖。我希望能够将它们导入到带有制表符分隔的活动电子表格中,同时使用 VBA 代码。非常感谢您的帮助!
我使用的是 excel 2016。我在记录时手动导入文本文件 1 的方法给出了这段代码,这就是我希望导入两个文本文件的方式(保留格式):
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Mr D\Music\New folder\B.txt", Destination:=Range("$A$1"))
.CommandType = 0
.Name = "B"
.FieldNames = True
.RowNumbers =enter code here False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
我尝试使用的代码来自此处发布的其他类似问题似乎不起作用:
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("C:\Users\Mr D\Music\")
' 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
【问题讨论】:
-
您需要什么帮助?您的问题没有说明您遇到了什么问题。
-
如果文件名每天都没有变化,您可以创建与它们的数据连接并每天刷新。
-
我想要可以执行此操作的代码。你是对的,我需要数据连接并且希望每天刷新。我在这里查看了类似的问题,并且提到的 vba 代码没有相应地执行它。
-
我已经能够通过激活 Windows 脚本宿主对象模型来消除用户定义的错误。我可以打开 1 个文本文件,但无法同时加载(第二个立即在最后一个空行中)
-
不是在 cmets 中解释您的问题,而是 edit the question 来解释您遇到的问题,并包含您遇到问题的代码。 那么我们可能会为您提供一些帮助。
标签: excel data-import vba