How to create and write to a txt file using VBA
Last Updated :
29 Aug, 2024
This VBA Program reads an Excel Range (Sales Data) and writes to a Text file (Sales.txt). This helps in faster copying of data to a text file as VBA coding enables automated copying. Let us learn how to do it in a few easy steps:
Excel VBA Write Text File
In the realm of Excel VBA, the power to interact with text files unfolds. Text file operations encompass opening, reading, and writing. When we talk about writing a text file, we essentially aim to transform the data residing in an Excel sheet into a text file or a notepad file. This process manifests through two distinct methods: Leveraging the FileSystemObject property within VBA or embracing the Open and Write approach embedded with the VBA framework.
Syntax of Open Text File
Open [File_path], For [Mode], As [File_Number]
File Path: The Path of the file we are trying to open on the computer.
Mode: The Mode is the control we can have over opening text files. We can have three types of control over the text file:
- Input Mode: The term 'Imput Mode' signifies a read-only control over the opened text file. When utilizing this mode, your interaction is restricted solely to reading the file's contents. It's akin to a one-way street, allowing you to extract data from the file without altering or modifying its existing content. This mode is ideal for scenarios where you seek information without any intention of modifying the original data.
- Output Mode: In the realm of "Output Mode", the canvas is yours to paint upon. This mode empowers you to write and create new content within the field. However, a word of cautions is essential: exercising this mode entails overwriting any pre-existing data. This serves as a powerful tool for crafting new narritives within the file, but it demands a vigilant approach to avoid unintended loss of valuable data.
- Append Mode: Contrary to the overwrite nature of the Output Mode,"Append Mode" offers a harmonious coexistence between new and existing data. This mode invites you to add fresh content at the end of the file's current data. Imagine it as seamlessly extending the storyline of an already captivating narrative. The Append Mode's gentle touch ensures that your new data complements the old, offering a balance fusion of information.
File Number: This will count the text file number of all the opened text files. It will recognize the opened file numbers in integer values from 1 to 511. However, assigning the file number is tricky and leads to confusion.
Free File: It returns the unique number for the opened files. This way, we can assign the unique file number without duplicate values.
Write Data to Text Files Using VBA
Excel VBA code to read data from an Excel file (Sales Data - Range "A1:E26"). Need two "For loop" for rows and columns. Write each value with a comma in the text file till the end of columns (write without comma only the last column value). Do the above step until reach the end of the rows.
Sales Data in Excel: 5 columns and 25 rows
Sales DataVBA code to create a text file as below

VBA Code
Variable | Data Type | Comments |
---|
myFileName | String | Output text file (Full path with file name) |
rng | Range | Excel range to read |
cellVal | Variant | Variable to assign each cell value |
row | Integer | Iterate rows |
col | Integer | Iterate columns |
'Variable declarations
Dim myFileName As String, rng As Range, CellVal As Variant, row As Interger, col As Interger
- Initialize variables:
- myFileName: The file name with the full path of the output text file
- rng: Excel range to read data from an excel.'
Full path of the text filemyFileName = "D:\Excel\WriteText\sales.txt"'Data range need to write on text fileSet rng = ActiveSheet.Range("A1:E26")
Open the output text file and assign a variable "#1"
'Open text fileOpen myFileName For Output As #1
'Nested loop to iterate both rows and columns of a given range eg: "A1:E26" [5 columns and 26 rows]
'Number of RowsFor row = 1 To rng.Rows.Count 'Number of Columns For col = 1 To rng.Columns.Count
Assign the value to variable cellVal
cellVal = rng.Cells(row, col).Value
Write cellVal with comma. If the col is equal to the last column of a row. write-only value without the comma.
'write cellVal on text file If col = rng.Columns.Count Then Write #1, cellVal Else Write #1, cellVal, End If
Close both for loops
Next colNext row
Close the file
Close #1
Approach
Step 1: Add a shape (Create Text File) to your worksheet

Step 2: Right-click on ????reate a Text file” and ????ssign Macro..”

Step 3: Select MacroToCreateTextFile

Step 4: Save your excel file as Excel Macro-Enabled Workbook” *.xlsm

Step 5: Click “Create Text file”
Similar Reads
How to Write to a File Using Applet?
In this article, we will learn how to write a file using Applet and grant access to write files using Applet. ApproachThe applet output window contains three fields. Those are the file name field, Text area field, and save button field. File name field: It asks the user to enter the file name to wri
3 min read
How to Create an Unnamed file in Windows?
There is curiosity hidden inside everyone. So when it comes to computers we all try to know why this is happening, what will happen if I run this software, what will happen if I delete some of Windows files and etc. We also sometimes try to make a file without a name in Windows and fail and then, fi
2 min read
How to Create a File in CMD
We all know that one can easily create files using GUI options, but what if you can use a faster way to create files through the command-line interface? This is not a necessary but useful skill for anyone working with Windows. Whether you're automating tasks, working on scripts, or preferring using
5 min read
How to Create Charts in Excel Using Worksheet Data and VBA?
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office pur
6 min read
How to Create an Input Box With Multiple Inputs in Excel Using VBA?
The Input Box is a dialogue box that helps users to take a value and do later computations according to the entered value. The input box is similar to the message box, but the message box is used to display the data while the input box is used to enter the data. By default, a message box displays on
10 min read
How to Create a Batch File in Windows?
A batch file is a straightforward text document in any version of Windows with a set of instructions meant to be run by Windows' command-line interpreter (CMD) by maintaining all the functions. Batch files are a great tool for streamlining internally configured processes, automating tedious jobs, an
5 min read
How to Create a Text File Using the Command Line in Linux
The Linux command line is a powerful tool that allows you to manage your system with precision and speed. One of the most common tasks is creating a text file, which can be achieved using several commands and methods.Here we will learn some quick ways to create a text file from the Linux Command Lin
6 min read
Create Text File Using Nano
Nano is a popular command-line text editor known for its simplicity and ease of use. In this comprehensive guide, we will delve into the process of creating text files using Nano, covering every aspect along with examples and detailed explanations. Creating a New Text File:To create a new text file
3 min read
Bash Scripting - Write Output of Bash Command into Log File
Let there are some situations in which you have to save your output in a file ( generally called log file). Output can be user details ( username, password, Gmail, etc. ), products record ( buying or selling any goods ), or simply any kind of data that you can store in a log file. Let see how to wri
4 min read
Change case of all characters in a .txt file using Python
In this article, we will learn how to change the case of all characters present in a text file using Python. We will use Python methods Python upper() to change all characters to upper case, and Python lower() to change all characters to lower case.For example, If we have text file data.txt as shown
3 min read