'How to merge multiple .txt files with the same name into one file?

I'm looking to merge multiple .txt files into one file.

Some of the .txt files have the same name but are in different folders. There are a lot of them, and I will have to do this several times.

I have code to merge .txt files with different names.

How can I merge same name files?

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


Solution 1:[1]

One option may be to use command prompt first: dir "file path 1" /s >> "filepath2\output.txt" will scan your main folder, including sub folders (/s) and write out all file names and paths to the output text file. Then copy from the output file. select the files that you want to merge and place in either an excel column or text file. Use this as the input list of files that you want to merge instead of using dialog picker.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ASW22