VBA Write Text File | Write Excel Data to Text Files using VBA Code (2024)

Excel VBA Write Text File

In VBA, we can open or read or write a text file. To write a text file means the data we have in an Excel sheet, and we want it to be a text file or a notepad file. Therefore, there are two methods: the FileSystemObject property of VBA and the Open and Write method in VBA.

In most corporate companies, once finalizing the report, they look to upload the report to the database. They use the "Text Files" format to update the database to upload to the database. We usually copy the data from Excel and paste it into a text file. We rely on text files because they are very easy to work with because of their lightweight and simpler ways. By using VBA coding, we can automate the task of copying data from an Excel file to a text file. This article will show you how to copy or write data from an Excel file to a text file using VBA code.

Table of contents
  • Excel VBA Write Text File
    • How to Write Data to Text Files using VBA?
      • Syntax of Open Text File
      • Example #1
        • Step 1: Declare Variable
        • Step 2: Determine File Number
        • Step 3: Assign File Path
        • Step 4: Assign Free File Function
        • Step 5: Open Text File
        • Step 6: Use the Print/Write Method
        • Step 7: Save and Close Text File
      • Example #2
    • Recommended Articles
VBA Write Text File | Write Excel Data to Text Files using VBA Code (1)

How to Write Data to Text Files using VBA?

Writing data from Excel to text is complex and requires very good knowledge of VBA coding. Follow the below steps to write the VBA code to copy data from Excel to a text file.

Before we show you how to write the code, let me explain how to open the text file using an open statement.

Syntax of Open Text File

Open , For , As 

File Path: The path of the file we are trying to open on the computer.

Mode: Mode is the control we can have over opening text files. We can have three types of control over the text file.

  • Input Mode: This suggests "Read-only" control of the opening text file. If we use "Input Mode," we cannot do anything with the file. Instead, we can just read the contents of the text file.
  • Output Mode: We can write the content on this option. We need to remember that it will overwrite all the existing data. So, we must be wary of the possible loss of old data.
  • Append Mode: This mode is completely the opposite of the Output Mode. Using this method, we can write the new data at the end of the existing data in the file.

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. For this, we can use the free File function.

Free File returns the unique number for the opened files. This way, we can assign the unique file number without duplicate values.

Example #1

Follow the below steps to write the code to create a new text file.

Assume you already have a text file named "Hello.txt" in your computer storage, and we will show you how to write the data in it.

Step 1: Declare Variable

Declare the variable to hold the file path as String.

Code:

Sub TextFile_Example1() Dim Path As StringEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (2)
Step 2: Determine File Number

To determine which file number we refer to, declare one more variable as Integer.

Code:

Sub TextFile_Example1() Dim Path As String Dim FileNumber As IntegerEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (3)
Step 3: Assign File Path

Now, assign the file path with a name for the Path variable.

Code:

Sub TextFile_Example1() Dim Path As String Dim FileNumber As Integer Path = "D:Excel FilesVBA FileHello.txt" 'Change the path as per your requirementEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (4)
Step 4: Assign Free File Function

Now, assign the function "Free File" to store unique file numbers for the File Number variable.

Code:

Sub TextFile_Example1() Dim Path As String Dim FileNumber As Integer Path = "D:Excel FilesVBA FileHello.txt" 'Change the path as per your requirement FileNumber = FreeFileEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (5)
Step 5: Open Text File

Now, we need to open the text file to work with it. As we have explained, we need to use the OPEN statement to open the text file.

See Also
type

VBA Write Text File | Write Excel Data to Text Files using VBA Code (6)

Step 6: Use the Print/Write Method

Once the file opens, we need to write something in it. We need either the "Write" or "Print" method to write in the text file.

Code:

Sub TextFile_Example1() Dim Path As String Dim FileNumber As Integer Path = "D:Excel FilesVBA FileHello.txt" 'Change the path as per your requirement FileNumber = FreeFileOpen Path For Output As FileNumber Print #FileNumber, "Welcome" Print #FileNumber, "to" Print #FileNumber, "VBA"End Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (7)

First, we need to mention the file number (here, we have assigned the file through the "FileNumber" variable), then we need to add the content we want to add to a text file.

Step 7: Save and Close Text File

Once we write the content in a text file, we need to save and close the text file.

Code:

Sub TextFile_Example1() Dim Path As String Dim FileNumber As Integer Path = "D:Excel FilesVBA FileHello.txt" 'Change the path as per your requirement FileNumber = FreeFileOpen Path For Output As FileNumber Print #FileNumber, "Welcome" Print #FileNumber, "to" Print #FileNumber, "VBA" Close FileNumberEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (8)

Now, run the code manually or through the shortcut excel key F5. It will write the mentioned content in the mentioned text file.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (9)

Example #2

Now, we will see how to write the data of the Excel sheet into a text file.

For this example, we have created simple data in Excel like below.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (10)

Step 1: With the continuation of the old example, define two more variables as Integer to find the last row and last column.

Code:

Sub TextFile_Example2() Dim Path As String Dim FileNumber As Integer Dim LR As Integer Dim LC As IntegerEnd Sub
VBA Write Text File | Write Excel Data to Text Files using VBA Code (11)

Step 2: Find the last used row and column in the worksheet.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (12)

Step 3: Now, assign the file path and file number.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (13)

Step 4: Use the OPEN statement to open the text file.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (14)

Step 5: We need to loop through rows and columns, so declare two more variables as Integer.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (15)

Step 6: Now, open the loop to loop through the row (For next loop in VBA)

VBA Write Text File | Write Excel Data to Text Files using VBA Code (16)

Step 7: To loop through columns, open one more loop inside the existing loop.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (17)

Step 8: We need to write the same data line until it reaches the last column. So for this, apply the IF statement in VBA.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (18)

Step 9: Now, save and close the text file.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (19)

This code will write the details to a text file, but to open the text file after writing, we need to use the below code.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (20)

Code:

Sub TextFile_Example2() Dim Path As String Dim FileNumber As Integer Dim LR As Integer Dim LC As Integer Dim k As Integer Dim i As Integer LR = Worksheets("Text").Cells(Rows.Count, 1).End(xlUp).Row LC = Worksheets("Text").Cells(1, Columns.Count).End(xlToLeft).Column Path = "D:Excel FilesVBA FileHello.txt" FileNumber = FreeFile Open Path For Output As FileNumber For k = 1 To LR For i = 1 To LC If i <> LC Then Print #FileNumber, Cells(i, k), Else Print #FileNumber, Cells(i, k) End If Next i Next k Close FileNumber Shell "notepad.exe " & Path, vbNormalFocusEnd Sub

So, run the code using the F5 key or manually. Then, it will copy the data below.

VBA Write Text File | Write Excel Data to Text Files using VBA Code (21)

Recommended Articles

This article is a guide to VBA Write Text File. Here, we learn how to copy/write data from a worksheet to a text file with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: -

  • VBA Wait
  • VBA FileDialog
  • InStr VBA Function
VBA Write Text File | Write Excel Data to Text Files using VBA Code (2024)
Top Articles
Is the American Express Black Card Really Worth It? | The Motley Fool
10 disadvantages of microservices you'll need to overcome | TheServerSide
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6230

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.