我有一个脚本,我将它们放在一起,以便为所选的每个文件导入多个分隔符的文本文件到新工作簿中。除了在新工作簿中正确导入的列之后将所选文本文件中的所有数据粘贴到列中之外,它大约有99%的功能。我不完全确定代码的哪一部分会导致将其粘贴到该特定行。下面是代码的主要部分。任何人都可以确定问题的位置吗?
另外,我只想感谢社区。通过浏览本论坛的其他帖子,我学到了很多东西。
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
For i = LBound(FilesToOpen) To UBound(FilesToOpen)
Set wkb = Workbooks.Open(FilesToOpen(i))
Set wks = wkb.ActiveSheet
With wks.QueryTables.Add(Connection:= _
"TEXT;" & FilesToOpen(i), Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.RefreshStyle = xlInsertDeleteCells
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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
Next i
答案 0 :(得分:0)
您的问题是使用Workbooks.Open
获取新的Workbook
。您实际上打开文本文件的方式与转到File->Open
的方式相同。如果您希望 new Workbook
转储数据,请使用Set wkb = Workbooks.Add()
而不是当前对Workbooks.Open
的调用显式创建数据。您正在查看文件的数据,因为您先打开了文件。
完整代码
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
For i = LBound(FilesToOpen) To UBound(FilesToOpen)
Set wkb = Workbooks.Add()
Set wks = wkb.ActiveSheet
With wks.QueryTables.Add(Connection:= _
"TEXT;" & FilesToOpen(i), Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.RefreshStyle = xlInsertDeleteCells
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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
Next i