How to Save Each Non-Empty Cell of an Excel File as a Separate .txt File

Abstract: Automate exporting each non-empty Excel cell to a separate .txt file using VBA, avoiding manual work and empty files.

Created: 2026-10-10 by
To save each non-empty cell of an Excel file as a separate .txt file, you must use a VBA macro because native Excel features do not support this specific granular export. The script iterates through the used range, checks for content, and writes each value to its own text file named by its address or index. This approach ensures that only cells with data are processed, preventing empty files from cluttering your directory.

Understanding the Limitation of Native Export

Excel offers several ways to export data, such as saving the entire workbook as a CSV or using the "Save As" feature for various formats. However, there is no built-in menu option or ribbon command that allows you to split individual cells into separate files automatically. If you try to manually copy and paste each cell into a new document, the process becomes incredibly tedious and error-prone, especially with large datasets containing hundreds or thousands of entries.

Furthermore, standard export tools treat rows and columns as structured blocks. They do not recognize the need to isolate single data points into independent artifacts. Therefore, automating this task requires leveraging Excel’s Visual Basic for Applications (VBA) engine. By writing a simple script, you can instruct Excel to loop through every cell in a specified range, evaluate if it contains data, and then perform the file creation operation instantly.

Preparing Your Environment

Before running any code, ensure your workbook is saved in a format that supports macros, specifically .xlsm (Excel Macro-Enabled Workbook). If you are working with a standard .xlsx file, the macro will be lost upon closing the document. Additionally, you need to enable the Developer tab in the Excel ribbon if it is not already visible. You can do this by right-clicking the ribbon, selecting "Customize the Ribbon," and checking the box for "Developer."

Decide where you want the output text files to be saved. It is best practice to create a dedicated folder on your computer for these exports. Note down the full path to this folder, as you will need to input it into the VBA script. For example, a path might look like C:\Users\YourName\Documents\ExcelExports\. Ensure the path ends with a backslash (\) to properly concatenate filenames.

Writing the VBA Macro

Open your Excel workbook and press Alt + F11 to open the VBA Editor. In the editor, go to Insert > Module to create a new module. Paste the following code into the module window. This script defines a subroutine that loops through all non-empty cells in the active sheet's used range.

Sub SaveCellsAsTxt()
    Dim ws As Worksheet
    Dim cell As Range
    Dim filePath As String
    Dim fileName As String
    Dim fileNum As Integer
    
    ' Set the worksheet to the active sheet
    Set ws = ActiveSheet
    
    ' Define the output folder path (ensure trailing backslash)
    filePath = "C:\Your\Target\Folder\"
    
    ' Loop through each cell in the used range
    For Each cell In ws.UsedRange
        ' Check if the cell is not empty
        If Not IsEmpty(cell.Value) Then
            ' Create a filename based on the cell address (e.g., A1.txt)
            fileName = filePath & cell.Address(False, False) & ".txt"
            
            ' Open the file for output
            fileNum = FreeFile
            Open fileName For Output As #fileNum
            
            ' Write the cell value to the file
            Print #fileNum, cell.Value
            
            ' Close the file
            Close #fileNum
        End If
    Next cell
    
    MsgBox "Export complete! Check your target folder.", vbInformation
End Sub

You must modify the filePath variable in the code to match your desired destination folder. The cell.Address(False, False) function generates names like A1, B5, etc., ensuring each file has a unique identifier. The FreeFile function assigns the next available file number, which prevents conflicts when opening multiple files sequentially.

Executing and Verifying the Export

Close the VBA Editor and return to your Excel sheet. Press Alt + F8 to open the Macro dialog box. Select SaveCellsAsTxt and click Run. Excel may prompt you to confirm the execution of macros; allow it to proceed. The script will iterate through your data at high speed. Once finished, a message box will appear confirming the completion of the task.

Navigate to your target folder to verify the results. You should see a collection of .txt files, each named after the corresponding cell address in Excel. Open a few randomly to ensure the content matches the original cell values. If you encounter issues, check that the file path is correct and that you have write permissions for that directory. This method is efficient and scalable, handling large ranges without manual intervention.

Handling Special Cases and Data Types

While the basic script works for most text and numeric data, you may encounter edge cases. For instance, if a cell contains a formula, the macro exports the calculated result, not the formula itself. If you need to handle errors gracefully, such as when a cell contains an array or complex object, you might need to add error handling using On Error Resume Next within the loop. However, for standard data entry, the provided code is robust.

If you wish to customize the filename further, perhaps including row and column headers, you can modify the fileName assignment line. For example, you could append the value of a header cell to the filename. This requires additional logic to reference other cells relative to the current loop iteration. For most users, the address-based naming convention is sufficient and easy to trace back to the source spreadsheet.

Related Resources

If you need to adjust how characters are encoded during export, refer to How to Change Excel Character Set?. For more advanced data retrieval techniques before exporting, consider reading Return First Column Header of Instance of String.

Frequently Asked Questions

Can I save cells from multiple sheets at once?

No, the provided macro targets only the ActiveSheet. To process multiple sheets, you would need to wrap the logic in a loop that iterates through each Worksheet in the Worksheets collection. You would also need to ensure filenames are unique across sheets to avoid overwriting.

What happens if a cell contains special characters?

The Print statement handles most standard special characters correctly. However, if a cell contains binary data or unsupported Unicode characters, you might encounter encoding issues. In such cases, consider converting the data to a string format explicitly before writing it to the file.

Is it possible to include the formula instead of the value?

The default script exports the displayed value. To export the formula, change cell.Value to cell.Formula in the code. Be aware that this will include the leading equals sign and may produce longer filenames or unreadable text if the formula is complex.

Why does my macro run slowly on large datasets?

Opening and closing thousands of files individually is inherently slow due to disk I/O operations. To speed up the process, you can optimize the code by turning off screen updating and automatic calculation using Application.ScreenUpdating = False at the start of the macro. This reduces overhead but does not eliminate the physical limitation of creating many small files.

How do I delete the generated files later?

There is no built-in cleanup feature in this macro. You must manually delete the files from the target folder. Alternatively, you can extend the VBA script to include a deletion step, iterating through the folder and removing files older than a certain date or simply clearing the directory before generating new ones.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More