【发布时间】:2021-09-23 04:20:08
【问题描述】:
这里是新手。
所以我有十几个类似这样的 TXT/DTA 文件,我想将它们并排堆叠。 我希望每个文件都附加到右侧,合并成一个大文件
我对 VBA 了解不多,我环顾四周并合并了一些代码,这些代码似乎适用于 xlsx 文件,但不适用于我所拥有的 DTA 文件。该代码要求一个文件夹并逐个循环文件。
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
'---Open the first file only
Workbooks.Open (MyFile)
Workbooks(MyFile).Worksheets("Sheet1").Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Workbooks("CV Combined.xlsm").Worksheets("Sheet1").Range("A1")
Workbooks(MyFile).Close SaveChanges:=False
MyFile = Dir
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(fileName:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Workbooks.Open (MyFile)
Workbooks(MyFile).Worksheets("Sheet1").Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Workbooks("CV Combined.xlsm").Worksheets("Sheet1").Range("A1").End(xlToRight).Offset(0, 1)
Workbooks(MyFile).Close SaveChanges:=False
wbk.Close SaveChanges:=True
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
任何帮助将不胜感激。
【问题讨论】:
-
“并排”应该是什么意思?您想将下一个文件内容添加到现有范围的右侧还是文件末尾?那么,DTA 扩展名可能意味着很多东西……你能用记事本/写字板打开这样的 DTA 文件,你能看到你在图片中向我们展示的内容吗?那些文件
Tab是分隔的吗?它们是否在 Excel 中正确打开,按列拆分? -
并排意味着我希望它们附加到每个文件的右侧(即并行)。我可以使用 Power Query 垂直附加它们。是的,图片来自记事本。是的,Excel 会正确打开按列拆分的文件,但我想为其他批次自动执行该过程。是的,文件是
Tab分隔的。 -
我是否应该了解该特定文件夹中的所有文件都是 DTA 类型的,还是也有 TXT 文件?
-
扩展名是 DTA。但我在网上看到它基本上是一个TXT文件。也许这过于简单化了。