Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA: Save a Sheet as a Text File

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can save any worksheet as a plain text file from Excel VBA using the SaveAs method with a text file format, or by writing the sheet's values to a file with Print # or Write # statements. The quickest route is ActiveSheet.SaveAs Filename:="C:\Folder\SheetName.txt", FileFormat:=xlText, which exports the used range of the active sheet as tab-delimited text. This guide shows that method plus a more controlled line-by-line approach, and covers the errors that trip people up.

What You'll Need

  • Excel on Windows or Mac with the Developer tab enabled (File > Options > Customize Ribbon > check Developer, or Excel > Preferences > Ribbon & Toolbar on Mac).
  • A workbook with at least one worksheet containing data.
  • A destination folder you have write permission to, such as your Documents folder or a subfolder you create.
  • Basic familiarity with opening the VBA editor (Alt+F11 on Windows, Option+F11 on Mac) and inserting a module.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11 (Windows) or Option+F11 (Mac). In the Project Explorer, right-click your workbook, choose Insert > Module. A blank code window appears.
  2. Decide which sheet to export. The code below uses the sheet named in the sheetName variable. Change it to match your tab name exactly, including spaces. If you prefer the active sheet, replace Worksheets(sheetName) with ActiveSheet.
  3. Paste the SaveAs method. This is the shortest working version:
    Sub SaveSheetAsText()
        Dim sheetName As String
        Dim fullPath As String
        sheetName = "Sheet1"
        fullPath = "C:\Temp\" & sheetName & ".txt"
        Worksheets(sheetName).Copy
        ActiveWorkbook.SaveAs Filename:=fullPath, FileFormat:=xlText
        ActiveWorkbook.Close SaveChanges:=False
    End Sub
    The Copy step creates a temporary workbook containing only that sheet, so you do not alter your original file. xlText writes tab-delimited text with a .txt extension. If you need comma-separated values, use xlCSV and a .csv extension instead.
  4. Check the path. The folder in fullPath must already exist. VBA will not create missing folders for you. Change C:\Temp\ to a folder you can write to, and keep the trailing backslash. On Mac, use a path like "/Users/yourname/Documents/".
  5. Run the macro. Place the cursor inside the subroutine and press F5, or use Run > Run Sub/UserForm. If Excel asks about overwriting, that means a file with the same name is already there.
  6. Verify the output. Open the .txt file in Notepad (Windows) or TextEdit (Mac). You should see your data with tabs between columns. If you see only one column, your data may not have been tab-delimited on export, or the viewer is collapsing tabs.
  7. Use the line-by-line method when you need control. SaveAs exports the whole used range and adds formatting quirks. For a custom delimiter, specific columns, or no header row, write the file yourself:
    Sub WriteSheetToText()
        Dim ws As Worksheet
        Dim fNum As Integer
        Dim r As Long, c As Long
        Dim line As String
        Set ws = Worksheets("Sheet1")
        fNum = FreeFile
        Open "C:\Temp\output.txt" For Output As #fNum
        For r = 1 To ws.UsedRange.Rows.Count
            line = ""
            For c = 1 To ws.UsedRange.Columns.Count
                If c > 1 Then line = line & "|"
                line = line & CStr(ws.Cells(r, c).Value)
            Next c
            Print #fNum, line
        Next r
        Close #fNum
    End Sub
    This writes pipe-separated lines and gives you full control over what appears. Replace "|" with a comma, tab (Chr(9)), or any delimiter.
  8. Add error handling for production use. Wrap the file operations in On Error GoTo so a locked file or bad path does not leave Excel in a strange state. Close the file number in the error handler before exiting.

Common Mistakes

  • Forgetting the trailing backslash in the folder path. C:\Temp plus a filename becomes C:\TempSheet1.txt, which lands in the root of C: or fails.
  • Using SaveAs on the original workbook. Without the Copy step, SaveAs changes your open workbook into a text file, and you lose the .xlsx association until you save again. Always copy first or use the write-to-file method.
  • Assuming SaveAs respects hidden rows or filters. It exports the used range as-is. To export only visible rows, loop through rows and check EntireRow.Hidden before writing.
  • Expecting numbers to stay formatted. Text export writes the underlying value, so a cell showing 1,234.50 may export as 1234.5. Format the string yourself with Format() if the display matters.
  • Leaving file numbers open. If you use Open without a matching Close, the file stays locked and the next run fails with a permission error.

Tips

  • Use ThisWorkbook.Path to save next to the workbook instead of hard-coding a folder, which makes the macro portable.
  • Build the filename from a date stamp with Format(Now, "yyyymmdd_hhmmss") to avoid overwrite prompts.
  • Set Application.DisplayAlerts = False before SaveAs and restore it afterward to suppress overwrite dialogs, but only when you are sure overwriting is intended.
  • For large sheets, the line-by-line method is slower than SaveAs but uses less memory and avoids creating a temporary workbook.
  • Test with a copy of your workbook first. Macros that save and close workbooks can close more than you expect if the wrong workbook is active.

Troubleshooting

Run-time error 1004: Method 'SaveAs' of object '_Workbook' failed. This usually means the folder does not exist, the file is open in another program, or the filename contains invalid characters. Check the path, close the target file, and remove characters like : * ? " < > | from the name.

The macro runs but no file appears. Confirm the path in fullPath is exactly where you looked, and that you are not running a different subroutine. Add MsgBox fullPath before SaveAs to see the resolved path.

Permission denied. The folder may be read-only or synced by a service that locks files. Try a local folder such as Documents, and close any program that has the file open.

Only part of the sheet exports. SaveAs exports the used range, which may stop short if there are blank rows or columns at the edges. Select the exact range and use Selection.Copy into a new workbook first, or switch to the line-by-line method with explicit row and column bounds.

Mac path issues. Mac Excel uses forward slashes and HFS/APFS paths. If SaveAs fails, use MacScript or the newer AppleScriptTask only if you are comfortable with it; otherwise save to a simple path under your home folder.

Frequently Asked Questions

Can I save just one sheet as a text file without affecting the workbook?

Yes. Copy the sheet to a temporary workbook, run SaveAs on that workbook, then close it without saving. Your original file is untouched.

What is the difference between xlText and xlCSV?

xlText writes tab-delimited text with a .txt extension. xlCSV writes comma-separated values with a .csv extension. Choose based on what the receiving program expects.

Can I export only visible rows or a specific range?

Not with SaveAs directly. Loop through the rows or cells you want and write them with Print #, skipping hidden rows or cells outside your range.

Why does my text file show strange characters?

SaveAs writes in the system's default encoding, which may not be UTF-8. If you need Unicode, write the file yourself with ADODB.Stream set to UTF-8, or open the file in an editor that lets you choose the encoding.

Does this work on Excel for Mac?

Yes, with path differences. Use forward slashes and a folder under your home directory, and note that some Windows-only file APIs are unavailable.

Can I schedule this to run automatically?

You can call the macro from a Workbook_Open event or a button, but scheduling outside Excel requires Windows Task Scheduler or a similar tool to open the workbook and run the macro.