我目前正在考虑将多个.txt文件合并为一个文件。问题是一些.txt文件具有相同的名称,但位于不同的文件夹中。有相当多,我将不得不这样做几次。
到目前为止,我有一个允许我合并.txt文件的代码,但是它被设置为合并不同名称的文件。如何更改代码以合并同名文件?
Sub CombineTextFiles()
Dim lFile As Long
Dim sFile As String
Dim vNewFile As Variant
Dim sPath As String
Dim sTxt As String
Dim sLine As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show Then
sPath = .SelectedItems(1)
If Right(sPath, 1) <> Application.PathSeparator Then
sPath = sPath & Application.PathSeparator
End If
Else
'Path cancelled, exit
Exit Sub
End If
End With
vNewFile = Application.GetSaveAsFilename("CombinedFile.txt", "Text files (*.txt), *.txt", , "Please enter the combined filename.")
If TypeName(vNewFile) = "Boolean" Then Exit Sub
sFile = Dir(sPath & "*.txt")
Do While Len(sFile) > 0
lFile = FreeFile
Open CStr(sFile) For Input As #lFile
Do Until EOF(lFile)
Line Input #1, sLine
sTxt = sTxt & vbNewLine & sLine
Loop
Close lFile
sFile = Dir()
Loop
lFile = FreeFile
Open CStr(vNewFile) For Output As #lFile
Print #lFile, sTxt
Close lFile
End Sub
发布于 2021-12-03 19:40:09
一种选择是首先使用命令提示符: dir "file path 1“/s >> "filepath2\output.txt”将扫描您的主文件夹,包括子文件夹(/s),并将所有文件名和路径写出到输出文本文件。然后从输出文件中复制。选择要合并并放置在excel列或文本文件中的文件。将其用作要合并的文件的输入列表,而不是使用对话框选取器。
https://stackoverflow.com/questions/70216361
复制相似问题