Search code examples
pythonexcelvbatext

How to save all worksheets in Excel workbook as one text file?


I have an Excell workbook with multiple worksheets. I want to export the text of all worksheets to one text file. I've seen multiple solutions (primarily using VBA - example below) to export each worksheet as its own text file, but have yet to find a solution to export all worksheets as one text file. Any ideas as to how to accomplish this using VBA (or perhaps Python)?

Sub ExportSheetsToText()
Dim xWs As Worksheet
Dim xTextFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Copy
    xTextFile = CurDir & "\" & xWs.Name & ".txt"
    Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
    Application.ActiveWorkbook.Saved = True
    Application.ActiveWorkbook.Close
Next
End Sub

Solution

  • After you generate those text files, you can easily merge many text files into one using the Windows Command Prompt. Suppose for instance that all your file name have some pattern in their names. i.e. *.txt but I recommend you give them some additional pattern in their name, such as temp_something.txt:

    xTextFile = CurDir & "\temp_" & xWs.Name & ".txt"
    

    Then you merge them into one text file ine the command prompt like this:

    type temp_*.txt >> mergedFile.txt
    

    or

    copy temp_*.txt mergedFile.txt
    

    If you want to fully automate the operation inside the VBA routine, you can integrate the command inside it, like so:

    For Each xWs In Application.ActiveWorkbook.Worksheets
        xWs.Copy
        xTextFile = CurDir & "\temp_" & xWs.Name & ".txt"
        Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
        Application.ActiveWorkbook.Saved = True
        Application.ActiveWorkbook.Close
    Next
    
    Dim shl As Object: Set shl = CreateObject("WScript.shell")
    shl.CurrentDirectory = CurDir
    shl.Run "cmd /C copy temp_*.txt " & ThisWorkbook.name & ".txt" ' merge the temporary text files
    
    shl.Run "cmd /C del temp_*.txt" ' clean up the temporary text files
    

    At the end you get a text file with the same name of you workbook plus the extension .txt.