Write in excel file vba

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.

I want to write the c codes which are going to be printed in that .txt file.

What is the command to create a .txt file using VBA, and how do I write to it

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Jul 16, 2012 at 11:20

danny's user avatar

2

To elaborate on Ben’s answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:tempMyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

answered Apr 5, 2018 at 14:16

Marcus Mangelsdorf's user avatar

3

an easy way with out much redundancy.

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim Fileout As Object
    Set Fileout = fso.CreateTextFile("C:your_pathvba.txt", True, True)
    Fileout.Write "your string goes here"
    Fileout.Close

answered Feb 23, 2016 at 17:01

pelos's user avatar

pelospelos

1,6743 gold badges24 silver badges32 bronze badges

2

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:A-Level Computing2017!PPESaveFileSaveData.txt"))
    Console.ReadLine()

End Sub()

BDL's user avatar

BDL

20.7k19 gold badges52 silver badges52 bronze badges

answered Feb 10, 2017 at 13:16

Zack Brightman's user avatar

5

vba write file

write file vbaContinuing on the topic of working with files using VBA. Text/binary files are common ways of storing data as opposed to databases or regular Excel files.

Looking at various resources I missed a single resource which would demonstrate the various methods for PROPERLY writing files in VBA. It is important to remember that you shouldn’t write all fills using the same approach. Be aware of the structure of the file. If you want performance – always select the right approach.

Approach #1: The Write function (strings in quotes)

Writing strings of data to text files with quotes:

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:test.txt"
fileNo = FreeFile 'Get first free file number  
textData ="Hello World!"

Open fileName For Output As #fileNo  'Open file for overwriting! Replace Output with Append to append
Write #fileNo, textData
Close #fileNo

This approach will result in the following output:

"Hello, World!"

Notice the “” quotes. Writing further strings will result in appending further strings wrapped in double quotes which might not be a satisfactory approach. Look down to the Print function to avoid these quotes.

To Append to the text file instead of overwriting replace For Output with For Append in the Open fileName For Output As #fileNo

Approach #2: The Print function (dumping strings without quotes)

Writing strings of data to text files without quotes:

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:test.txt"
fileNo = FreeFile 'Get first free file number  
    
Open fileName For Output As #fileNo 'Open file for overwriting! Replace Output with Append to append
Print #fileNo, textData
Close #fileNo

This approach will result in the following output:

Hello, World!

This time there are no quotes in the file. In most case you will want to use the Print function instead of the Write function

Writing binary files in VBA

Dim fileName As String, fileNo As Integer, testVar As Integer
fileName = "C:test.bin"
testVar = 4
fileNo = FreeFile
Open fileName For Binary Lock Read Write As #fileNo
Put #fileNo, , testVar
Close #fileNo

With Binary files often you will be using objects which are not of fixed byte length like Integers. For example you would want to save Strings. In such cases use the VBA Type object data type.

Below a simple example using the Type data type to save an object with an Integer and String.

Type TestType
    intVar As Integer
    strVar As String
End Type

Sub WriteBinary()
  Dim fileName As String, fileNo As Integer, testVar As TestType
  fileName = "C:test.bin"
  testVar.intVar = 4
  testVar.strVar = "Hello!"
  fileNo = FreeFile
  Open fileName For Binary Lock Read Write As #fileNo
  Put #fileNo, , testVar
  Close #fileNo
End Sub

Writing CSV files in VBA

If you want to save your worksheet as CSV you can always resort to the Text file section. However, this is an ineffective approach. If you want to save your current worksheet as a semicolon delimited file (‘;’) you can use the Workbook.SaveAs function like below.

PathName = "C:test.csv"
'Assuming you want to export your current Worksheet
ActiveSheet.Move 'Move the Worksheet to a new Workbook
ActiveWorkbook.SaveAs Filename:=PathName, FileFormat:=xlCSV, CreateBackup:=False

In case you want to instead copy your worksheet simply replace Move for Copy:

PathName = "C:test.csv"
'Assuming you want to export your current Worksheet
ActiveSheet.Copy 'Copy the Worksheet to a new Workbook
ActiveWorkbook.SaveAs Filename:=PathName, FileFormat:=xlCSV, CreateBackup:=False

Functions needed to write files in VBA

Function Description
FreeFile Get next free file number available for the Open statement / FileOpen function. Using this function is important especially when operating on multiple files simultaneously.
More info here.
BOF(fileNumber) Returns true if you are at the beginning of the file described by the file number.
More info here.
EOF(fileNumber) Returns true if you have reached the end of the file described by the file number. More info here.
Loc(fileNumber) Returns the current read/write position within an open file. More info here.
LOF(fileNumber) Returns the size in bytes of the file represented by the file number. More info here.

Write file VBA summary

Writing files in VBA is not hard and usually takes just a couple of lines of code. It makes sense however to do it write and be aware of certain traps like not omitting the use of the FreeFile function or knowing the difference between Print and Write.

This VBA Program reads an Excel Range (Sales Data) and write to a Text file (Sales.txt)

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 rows. 

Sales Data in Excel: 5 columns and 25 rows

Sales Data

VBA code to create a text file as below

VBA Code:

  • Declaring Variables :  
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 Integer, col As Integer
  • 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 file
myFileName = "D:ExcelWriteTextsales.txt"
'Data range need to write on text file
Set rng = ActiveSheet.Range("A1:E26")

Open the output text file and assign a variable “#1”

'Open text file
Open 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 Rows
For 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 col
Next row

Close the file

Close #1

Approach:

Step 1: Add a shape (Create Text File) to your worksheet 

Step 2: Right-click on “Create a Text file” and “Assign Macro..”

Step 3: Select MacroToCreateTextFile

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

Step 5: Click “Create Text file

Text files are one of the simplest, lightest file types. This is the reason it is highly used in programming to store a lot of configuration-related data, logs and so many other necessary data which is used by programs more frequently.
If you browse your Program files folder in windows almost every program will have some text files for storing some configurations or logs etc. stored in it.

Did you Know?

XML Files are also text files. The only difference is that XML files are more structured than Text files. This is the reason XMLs are widely used for communication.
In this article I am going to teach you in detail – How to deal with Text Files in Excel VBA. As explained above, Text files are very useful while developing any tool or add-in in Excel where you want to store some configuration data – in order to run your program or add-in. Using Excel file to store such data will make the program very slow.

I don’t need to explain much – about why a Text file would be a better option, rather you will find it by yourself at the end of this article.

So let’s start then in a logical order… Opening a file… reading a file… writing into a file.. etc.

Topics covered in this Article

In this article, the following topics are covered. Click on the below links to directly jump to that section

  1. Excel VBA to Open a Text File

  2. Excel VBA to create a NEW Text File

  3. VBA to write a Text file using Write Statement

  4. VBA to write a Text file using Print Statement

  5. VBA to Append to a Text File

  5. What is FreeFile () function ?

How to read a file, will be covered in the next article.

Excel VBA Code to Open a Text File

Following is the code Syntax to open a Text file:

Open [file Path] For [mode] As [#FileNumber]

With the Above code Syntax, as you can see, there are 3 parameters. [file Path] [mode] and [#FileNumber]

So, lets discuss about these three parameters – who are they and what role do they play in opening the text file:

What is File Name

This is the path of the Text file which is going to be opened.

What is Mode in Open Text File VBA Code

As the name suggests, its the control which you want to specify before opening it. There are mainly 3 types of controls or modes possible – Input, Output and Append.
Lets discuss one by one these 3 modes

Input Mode

This mode is used for READ ONLY control. It means, if you open a Text file in Input mode, then you can not write anything in it. All you can do is – read all the content inside the text file. Therefore you can say.. this a read only mode.

Output Mode

If your text file is open in this mode, then you can write content in it. But what is important here to note is : In this mode, your existing file gets overwritten. This means, if there are content already in there in the text file then it will be replaced by the new data which you are trying to save. Therefore, be careful while choosing the mode of the file while opening it.
Now you must be thinking – Then how to append content in an existing text file without overwriting it. Therefore the next mode – Append Mode.

Append Mode

As the name suggests, this mode allow you to append the new content at the end of the text file. It does not overwrite the existing content in the text file.
So now we have an idea about all these 3 modes. It will be more clear when we use them in the below examples.

Now Let’s learn about our second parameter – #FileNumber

#FileNumber

When Text files are opened then windows recognize them by a unique integer value. Valid range of Integers for this parameter is between 1 to 511.
As I mentioned above, it should be a unique integer, it is challenging for you to give a fixed number here in case you are dealing with multiple text files. To overcome this challenge you can use a function called FreeFile()

What is FreeFile() Function?

FreeFile() function returns a unique integer value which represents the file number of the file you opened. This way always a unique (or a FREE File Number – which is not used already) file-Number is assigned automatically by this function.

Now you know about  – How to open a Text file. Let’s see some examples and learn how to use it.

Sample VBA Code to Open a Text File


Sub OpenTextFile()
Dim sFilePath As String
Dim fileNumber As Integer
' Full path of the textFile which you want
' to open.
sFilePath = "C:UsersVishwaDesktopLEM.txt"

' Assign a unique file numner
fileNumber = FreeFile
' Below statement will open the
' above text file in output mode
Open sFilePath For Output As #fileNumber
End Sub

VBA code to create a new TextFile

If the file name provided in the File Path provided while writing Open statement, like above, does not exists, then Open statement, automatically creates a TextFile with the same name in the same directory.
Thus, using the same Open statement, you can create a new TextFile as well. You don’t have to use a different statement to create a new file.

Here is a sample code

Read the commented lines written inside the code. I have tried explaining them there as well.


Sub createANewtextFile()
Dim sFilePath As String
Dim fileNumber As Integer

' In the above path C:UsersVishwaDesktop - exists
' But on the desktop - LEM.txt file does not exist
sFilePath = "C:UsersVishwaDesktopLEM.txt"

' Assign a unique file numner
fileNumber = FreeFile

' in this case, below statement, will
' create a new file with name LEM.txt
' as soon as below statement gets executed
' And also, it is open to write something
Open sFilePath For Output As #fileNumber

End Sub

Note: Only File Name should not exists in order to create a new file. Directories or folders specified must exists. If not, file Not Found Error will be thrown.[/fusion_text]

VBA Code to Write content in to Text File

[fusion_text]Basically there are two statements using which you can write content in to a text file in excel VBA : Write or Print[/fusion_text][title size=”1″ content_align=”left” style_type=”none” sep_color=”” margin_top=”” margin_bottom=”” class=”” id=””]VBA to write in to Text Files using Write statement[/title][fusion_text]As I mentioned above, one can write in to text files using two statements Write or Print. First lets have a look on – how to write content in to a text file using Write statement.[/fusion_text]
Write #<fileNumber>, InputData 1, InputData 2, ….
[title size=”2″ content_align=”left” style_type=”none” sep_color=”” margin_top=”” margin_bottom=”” class=”” id=””]Where:[/title][fusion_text]

File Number : This is a nemeric value which represents the File. This must be a unique number assigned to each open text files. Text files are identified by these unique numbers assigned to them while opening them. refer the Open File statement to know more about FileNumber

Input Data1, 2, 3, …:
This is the data which you want to write in the Textfile. You can write many different kind of data in each line. Each of these data will be written in textfile in a single line separated by comma.
Important to note:
Based on the type of the data which you put in InputData 1, 2 etc. Write statement does some common changes while putting them in to TextFile.

If the data is Date Type:  Then date value is closed within hash sign. Date – 2010-10-13 will be written in TextFile as #2010-10-13#

String type data:  They are stored in double quotes. For example : Input Data – Vishwamitra Mishra will be stored as “Vishwamitra Mishra”.

Integer, Double, Long etc :  They will be written as they are. There is not formatting done before they are written in text file.

Example:

Let’s take an example. Export the following table in excel to a Text file using Write statement.

Create Text File in Excel VBA

From the above excel cells, I will start reading one by one every column values of each row and write them in Text File.

VBA Code – To Write Text File – using Write Statement


Sub WriteTextFileUsingWriteStatement()

Dim sFilePath As String
Dim iRow As Integer

Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date

iRow = 2
sFilePath = "C:UsersVishwaDesktopLEM.txt"

' unique file number to access the file uniquely
fileNumber = FreeFile

' to check if file name LEM.txt exists
' if not, end the program
If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End

' Open the TextFile in Output mode
' in order to write in something
Open sFilePath For Output As #fileNumber

' Loop to read one by one every
' non empty row and write them
' in the text file
Do
With Sheets("Orders")
OrderDate = .Cells(iRow, 1).Value
OrderPriority = .Cells(iRow, 2).Value
OrderQuantity = .Cells(iRow, 3).Value
Discount = .Cells(iRow, 4).Value
ShipMode = .Cells(iRow, 5).Value
CustomerName = .Cells(iRow, 6).Value
ShipDate = .Cells(iRow, 7).Value
End With
' Now write these data in text file in next line
Write #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate

' go to the next row in Excel sheet
iRow = iRow + 1
Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)

' Close the file once all data
' is written in text file
Close #fileNumber
End Sub

Result : after Running the above code

After running the above code, Your text file will look something like this:
VBA Code to write Text File
Now you can see, as explained above, dates are put under Hash marks (#) and string data is put under double quotes (” “).

Important points to note in above code:

1. I have used Dir$ function to check if TextFile already exists. Why I am thinking it is important to mention is because, if you do not put this check and by mistake your file name is not correct, then Open File statement will create a new TextFile in the same location with your provided name and write the content in that new file.
Note: Open file statement will create a new file only if directory exists. If directory itself does not exists, then Open File statement will through an error – Path Not found.
It will not create a directory in that case.

2. Instead of using a fixed number like #1, #2 etc. for FileNumber, I have used the function FreeFile() which always finds an available fileNumber which can be assigned to a textFile. It is always a good practise to use this function rather using a hardcoded File Number. This becomes very important when your program start dealing with multiple text files.

3. To read every line from Excel and write it in textFile, I have used Do..While loop with Until keyword for condition. You can read more about do.. while loop and Until keyword here.

4. Last but not the least – do not forget the Close the file by using the same fileNumber by using the simple statement Close #FileNumber as you can see in the above code.

How to write TextFile using Print Statement

Syntax remains exactly same as Write statement. Main difference between Write and Print statement is in the formatting of the Output in TextFile. You will see in detail. Let’s start with the Syntax:

Syntax of Print statement:

Print #<FileNumber>, InputData1, InputData2, ….

Where:

File Number : This is a numeric value which represents the File. It is exactly same as explained above in Write Statement.

Input Data 1, 2, 3, …:
This is the data which you want to write in the Textfile. You can write many different kind of data in each line. Each of these data will be written in textfile in a Proper formatting with proper spacing. TextFile which you get from Print statement is well formatted for printing purposes. That means spaces between columns are adjusted based on the values in those columns. You will see in the example below.

Important to note:

Unlike Write statement, this does not change any of the formatting of the data for Date or String type. It just put them as they are.
Values of difference columns are not separated by Comma. Rather they are separated by space(s) depending on how many spaces required to make the textfile in a printable format.

Example: To write Text File using PRINT Statement

Let’s take the same example as above. Now we will export the same table from excel to a Text file using Print statement.

Here is the code


Sub WriteTextFileUsingPrintStatement()

Dim sFilePath As String
Dim iRow As Integer

Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date

iRow = 2
sFilePath = "C:UsersVishwaDesktopLEM.txt"

' unique file number to access the file uniquely
fileNumber = FreeFile

' to check if file name LEM.txt exists
' if not, end the program
If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End

' Open the TextFile in Output mode
' in order to write in something
Open sFilePath For Output As #fileNumber

' Loop to read one by one every
' non empty row and write them
' in the text file
Do
With Sheets("Orders")
OrderDate = .Cells(iRow, 1).Value
OrderPriority = .Cells(iRow, 2).Value
OrderQuantity = .Cells(iRow, 3).Value
Discount = .Cells(iRow, 4).Value
ShipMode = .Cells(iRow, 5).Value
CustomerName = .Cells(iRow, 6).Value
ShipDate = .Cells(iRow, 7).Value
End With
' Now write these data in text file in next line
Print #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate

' go to the next row in Excel sheet
iRow = iRow + 1
Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)

' Close the file once all data
' is written in text file
Close #fileNumber
End Sub

Result : after Running the above code

After running the above code, Your text file will look something like this:
Text File - Using Print Statement

Now you can see, as explained above:

1. None of the data are formatted. They are, in fact, put as they are in Excel cells.
2. Spaces between columns are adjusted based on the data in each columns.

Important to know…

There is another – in fact important – difference between Write and Print statement. That you will realize while reading above two TextFiles –
1. Written using Write Statement
2. Written using Print Statement. This is a hint for now. It will be explained in detail in the next article, where we will be talking all about reading a TextFile.

[/fusion_text][fusion_text]In all the above examples of writing to a text box, I have used the File Open mode as Output. This means, every time you run the code, all the content of the text file will be replaced with the new one. Therefore, let’s take an example, of how can we append to the existing content in a text file using write or print statement.

VBA Code to Append to Text File

The whole trick lies in to the mode you open your text file during your VBA program. Why I say that, because you do not need to change anything else in the Write or Print statements in order to append and not to replace. Isn’t it simple? So the complete VBA code remains same as it is there for replacing the whole content – except changing the open mode – from Output to Append. What these modes are They are explained in the beginning of the article.


Sub AppendToTextFile()

Dim sFilePath As String
Dim iRow As Integer

Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date

    iRow = 2
    sFilePath = "C:UsersVishwaDesktopLEM.txt"
    
    ' unique file number to access the file uniquely
    fileNumber = FreeFile
    
    ' to check if file name LEM.txt exists
    ' if not, end the program
    If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
    
    ' Open the TextFile in Append mode
    ' in order to write in something
    Open sFilePath For Append As #fileNumber
    
    ' Loop to read one by one every
    ' non empty row and write them
    ' in the text file
    Do
    With Sheets("Orders")
        OrderDate = .Cells(iRow, 1).Value
        OrderPriority = .Cells(iRow, 2).Value
        OrderQuantity = .Cells(iRow, 3).Value
        Discount = .Cells(iRow, 4).Value
        ShipMode = .Cells(iRow, 5).Value
        CustomerName = .Cells(iRow, 6).Value
        ShipDate = .Cells(iRow, 7).Value
    End With
    ' Now write these data in text file in next line
    Write #fileNumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate
    
    ' go to the next row in Excel sheet
    iRow = iRow + 1
    Loop Until IsEmpty(Sheets("Orders").Cells(iRow, 1).Value)
    
    ' Close the file once all data
    ' is written in text file
    Close #fileNumber
End Sub

Note: All the new information gets appended at the end of the text file (from the first blank line)
Did you like this article? Then share it with your friends… spread knowledge…”
Learn All about interacting with Text Files in Excel VBA like opening, creating, writing, reading etc. from Text Files using Excel VBA code”

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 codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more, 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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Write Text File (wallstreetmojo.com)

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 dataFile Copy is an inbuilt VBA function that is used to copy a file from one location to another. To use this function, we must specify the current file path as well as the destination file path. read more 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 [File Path], For [Mode], As [File Number]

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.

You can download this VBA Write Text File Template here – VBA Write Text File Template

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 String

End Sub

VBA Write Text Example 1-1

Step 2: Determine File Number

To determine which file number we refer to, declare one more variable as IntegerIn VBA, an integer is a data type that may be assigned to any variable and used to hold integer values. In VBA, the bracket for the maximum number of integer variables that can be kept is similar to that in other languages. Using the DIM statement, any variable can be defined as an integer variable.read more.

Code:

Sub TextFile_Example1()

  Dim Path As String
  Dim FileNumber As Integer

End Sub

VBA Write Text Example 1-2

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 requirement

End Sub

VBA Write Text Example 1-3

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 = FreeFile

End Sub

VBA Write Text Example 1-4

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.

Example 1-5


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 = FreeFile

Open Path For Output As FileNumber

    Print #FileNumber, "Welcome"
    Print #FileNumber, "to"
    Print #FileNumber, "VBA"

End Sub

Example 1-6

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 = FreeFile

Open Path For Output As FileNumber

   Print #FileNumber, "Welcome"
   Print #FileNumber, "to"
   Print #FileNumber, "VBA"

   Close FileNumber

End Sub

Example 1-7

Now, run the code manually or through the shortcut excel keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5. It will write the mentioned content in the mentioned text file.

VBA Write Text Example 1-8

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 Example 1

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 Integer

End Sub

VBA Write Text Example 2

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

VBA Write Text Example 2-1

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

VBA Write Text Example 2-2

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

VBA Write Text Example 2-3

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

VBA Write Text Example 2-4

Step 6: Now, open the loop to loop through the row (For next loop in VBAAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more)

VBA Write Text Example 2-5

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

VBA Write Text Example 2-6

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.

Example 2-7

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

Example 2-8

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.

Example 2-9

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, vbNormalFocus

End Sub

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

VBA Write Text Example 2-10

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

In this Article

  • Write to a Text File
    • Write to New Text File
    • Write to Existing Text File
    • Append to Text File
    • WriteLine Method
    • Write Method
    • WriteBlankLines
    • Data Range to Text File
    • Array to Text File

This tutorial will demonstrate how to write to text files using VBA.

Write to a Text File

The below codes use the FileSystemObject (learn more). In order to use it, you will need to set a reference to the VB script run-time library.

Write to New Text File

With the CreateTextFile method of FileSystemObject you can create and then add content to a text file:

Sub FSOCreateAndWriteToTextFile() 
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FileToCreate = FSO.CreateTextFile("C:TestTestFile.txt")

    FileToCreate.Write "test line"
    FileToCreate.Close

End Sub

Please note that content will not be enclosed by quotes.

Write to Existing Text File

To write to an existing text file you can use the OpenTextFile method of FileSystemObject with ForWriting mode.

Sub FSOWriteToTextFile() 
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FileToWrite = FSO.OpenTextFile("C:TestTestFile.txt", ForWriting)

    FileToWrite.Write "test line"
    FileToWrite.Close

End Sub

Please note that you do not necessarily need FileSystemObject to write to an existing text file. The above example is shown in another way in this code below (see other example in the Data Range to Text File section):

Sub WriteToTextFile()
    Dim FileName As String
    FileName = "C:TestTestFile.txt"

    Open FileName For Output As #1
    Print #1, "test line"
    Close #1

End Sub

Please note that using Write command instead of Print will result in having the added content enclosed by quotes. Having both commands in your macro

Write #1, "test line #1"
Print #1, "test line #2"

will result in a text file like this:

text in quotes

Append to Text File

By changing the mode in the above code to ForAppending, a line can be added to the end of the text file:

Set FileToWrite = FSO.OpenTextFile("C:TestTestFile.txt", ForAppending)

WriteLine Method

This method appends the input string as a separate line to the existing content.

Write Method

The input string is appended on the same line as the existing content.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

WriteBlankLines

This method takes the number of blank lines to be written to the text file as a parameter.

This code below illustrates the difference between the different write methods:

Sub WriteMethods()
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FileToWrite = FSO.OpenTextFile("C:TestTestFile.txt", ForAppending)

    FileToWrite.Write "test line #1 "
    FileToWrite.Write "test line #2"
    FileToWrite.WriteBlankLines (3)
    FileToWrite.WriteLine "test line #3"
    FileToWrite.WriteLine "test line #4"
    FileToWrite.Close

End Sub

And the result:write methods

Data Range to Text File

If you want to output a data range from your worksheet to a text file, you can use this code:

Sub OutputToTextFile()
    Dim FileName As String, LineText As String
    Dim MyRange As Range, i, j
    
    FileName = "C:TestTestFile.txt" 'you can specify here the text file name you want to create
    
    Open FileName For Output As #1
    
    Set MyRange = Range("data") 'it assumes you have a data range named “data” on your worksheet
    For i = 1 To MyRange.Rows.Count
        For j = 1 To MyRange.Columns.Count
            LineText = IIf(j = 1, "", LineText & ",") & MyRange.Cells(i, j) 'the text file creating will have a comma separator
        Next j
        Print #1, LineText 'using Write command instead of Print will result in having your data in quotes in the output text file
    Next i

    Close #1

End Sub

Array to Text File

You can also save your array of data into a text file like this:

Sub SaveArrayToTextFile()
    Dim MyArray As Variant
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")

    MyArray = Array(Array("00", "01"), Array("10", "11"), Array("20", "21"))

    Set FileToCreate = FSO.CreateTextFile("C:TestTestFile.txt")

    For n = 0 To UBound(MyArray)
        FileToCreate.WriteLine MyArray(n)(0) & "," & MyArray(n)(1)
    Next
    
    FileToCreate.Close

End Sub

In this article I will explain how you can create a text file and how write data to a text file in overwrite and append modes. 

You can download the file and code related to this article here.

Create a text file using the file system object:

You can create a text file using the file system object using the code below.

Sub CreateTextFile()
    Dim fs As Object
    Dim stream As Object

    Set fs = CreateObject("Scripting.FileSystemObject")
    On Error GoTo fileexists
        Set stream = fs.CreateTextFile("e:TextFile.txt", False, True)

fileexists:
        If Err.Number = 58 Then
            MsgBox "File already Exists"
		 'Your code here
        Else
            stream.Write ("No new line character inserted")
            stream.WriteLine ("This will take the cursor to next line.")
            stream.Close
        End If
    On Error GoTo 0
End Sub

The CreateTextFile  function takes 3 arguments.

  1. First is the name of the file along with the complete path
  2. Overwrite – Second (optional) argument indicates if an existing file can be overwritten. The value is True if the file can be overwritten; False if it can’t be overwritten. Default is false
  3. Unicode – Third (optional) argument indicates whether the file is created as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it’s created as an ASCII file. Default is ASCII.

As we have specified overwritten as false, an error will be thrown if the file already exists (Error number 58). So, we are using error handling to check for this condition.

We can use the Write and WriteLine function to write to the file. As you can guess, the WriteLine function will take the cursor to the next line, while the Write function will not. –


Example 1, Write One Line of Data to Text File:

The example below creates a text file at the location “D:Temp” under the name “Test.txt” and writes the value in cell A1 in the first line of the text file:

Sub Example1()
Open "D:TempTest.txt" For Output As #1
Write #1, Cells(1, 1)
Close #1
End Sub

The first line checks if the file “D:TempTest.txt” exists. If it doesn’t it will create a file named “Test.txt” at the location ” D:Temp”. If it does exist it will overwrite the file.

Open "D:TempTest.txt" For Output As #1

In our example the file does not exist, therefore a new file is created:

Excel VBA, Writing to Text Files, Example 1, New File

It has 3 parts:

“D:TempTest.txt”: Specifies the full path of the file.

Output: Specifies that this file is for writing to. This is opposed to the value Input used in the article Excel VBA, Reading Text Files

#1: This could be any number between #1 and #511. Whatever number is chosen here should be used in the rest of the program to reference this file.

The next line prints the data in cell A1 to the first line of the text file:

Write #1, Cells(1, 1)

The content of cell A1 can be seen below:

Excel VBA, Writing to Text Files, Example 1, Cell A1

The last line of code closes the file that has the reference #1:

Close #1

Had we chosen another number when opening the file, we would have had to choose the same number here when closing it. For example lets say we decide to user the number #4. We would have to user the #4 throughout the code:

Sub Example1()
Open "D:TempTest.txt" For Output As #4
Write #4, Cells(1, 1);
Close #4
End Sub
End Sub

The code above will yield the same result as our original code.

Always remember to close the file at the end of your code. Closing the file does the following:

  • Saves the data written to the file.
  • Allows other programs to modify the file.
  • If the file is not closed, you will not be able to reopen it using another number index.

Final Result:

Excel VBA, Writing to Text Files, Example 1, Final Result


Example 2, Write Multiple Lines of Data to Text File:

The example below creates a text file at the location “D:Temp” under the name “Test.txt” and writes all the data in column A to it:

Sub Example2()
Dim flag As Boolean
Dim i As Integer
'open the file for writing
Open "D:TempTest.txt" For Output As #4
flag = True
i = 1
'keeps going until the end of the file is reacheed
While flag = True
    'check if the current cell has data in it
    If Cells(i, 1) <> "" Then
        'write the data to the file
        Write #4, Cells(i, 1)
        'go to next cell
        i = i + 1
    Else
        'if the last row has been reached exit the loop
        flag = False
    End If
Wend
'close the file
Close #4
End Sub

The following data was written in column A:

Excel VBA, Write to Text File, Example 21

Result:

Excel VBA, Write to Text File, Result


Example 3, Save File Dialog:

In the example below the user will initially be asked to choose the location for the output text file using a save file dialog. A text file will then be created and the data in column A will be printed to the text file. For more information about save file dialogs please see the following links:

  • VBA Save File Dialog, FileDialog(msoFileDialogSaveAs)
  • Excel VBA, Save File Dialog, GetSaveAsFilename

Sub Example3()
Dim flag As Boolean
Dim i As Integer
Dim strPath As String
strPath = Application.GetSaveAsFilename(FileFilter:= _
"Text Files (*.txt), *.txt", Title:="Save Location")
If strPath <> "False" Then
    'open the file for writing
    Open strPath For Output As #4

       flag = True
    i = 1

       'keeps going until the end of the file is reacheed
    While flag = True
        'check if the current cell has data in it
        If Cells(i, 1) <> "" Then
        'write the data to the file
           Write #4, Cells(i, 1)
           'go to next cell
           i = i + 1
        Else
           'if the last row has been reached exit the loop
            flag = False
        End If
    Wend
    'close the file
    Close #4
End If
End Sub

The highlighted code creates a save file dialog and asks the user to select a location to save the file:

VBA, Write To Text File, Save File Dialog

The final result is similar to the previous examples.

Sub Example4()
Dim flag As Boolean
Dim i As Integer
Dim strPath As String
On Error GoTo lblError:
strPath = Application.GetSaveAsFilename(FileFilter:= _
"Text Files (*.txt), *.txt", Title:="Save Location")
If strPath <> "False" Then
    'open the file for writing
    Open strPath     For Output As #4
    flag = True
    i = 1
    'keeps going until the end of the file is reached
    While flag = True
        'check if the current cell has data in it
        If Cells(i, 1) <> "" Then
           'write the data to the file
           Write #4, Cells(i, 1)
           'go to next cell
           i = i + 1
        Else
           'if the last row has been reached exit the loop
           flag = False
        End If
    Wend
    'close the file
    Close #4
End If
Exit Sub
lblError:
Err.Clear

End Sub

Example 5, Use print function in append mode:

The examples covered so far rewrite the existing file. Now let us look at how to open a file in append mode. Here we will be using the print function to write to the file. The difference being, the text will not be inserted within double quotes.

Sub AppendFile()
    Dim strFile_Path As String
    Dim rangeToWrite As range

    strFile_Path = "e:TextFile.txt"

On Error GoTo cleanup
    Open strFile_Path For Append As #1

    Set rangeToWrite = range("A1:A10")

    For Each cell In rangeToWrite
        Print #1, cell.Value
    Next cell

    Close #1 

Cleanup:
    Close #1 

End Sub 

“Open file for Append” will first check if the file exists. If the file does not exist, a new one will be created. Else, the file will be opened in append mode.

We use the Print function to write the text from the Excel file to the text file. We have selected a single to column from Excel. You can easily modify the range to include multiple columns.

This is how the Excel and the text files look after executing the code.

excel file after executing append code

If you run the code again, the text file will look like this:

text file after append

You can download the file and code related to this article here.

See also:

  • Excel VBA, Reading Text Files
  • VBA, Modify Existing Text File
  • VBA Save File Dialog, FileDialog(msoFileDialogSaveAs)
  • Excel VBA, Save File Dialog, GetSaveAsFilename
  • VBA, Check if Text File is Open
  • VBA Append Data to Text File

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Skip to content

VBA write to a text file Excel

Home » VBA » VBA write to a text file Excel

VBA write to a text file Excel Macros Examples for writing to text files using VBA in MS Office Word, PowerPoint, Access, Excel 2003, 2007, 2010, 2013 and VBScript.

This Example VBA Program and function will help you to know how to write a string to text file using Excel VBA.

Writing to a text file Using VBA

Here is the Procedure, Example VBA Syntax and Example VBA Macro code for writing to text file. This will help you to know how to write to a text file using VBA.

VBA write to a text file: Procedure

We will first open the text file for writing as output file with a file number. Then we will write to the file using Write command and File Number.

VBA write to a text file: Syntax

Here is the VBA code and syntax for writing to a text file Using VBA.

strFile_Path = "Your file Path"
Open strFile_Path For Output As #1
Write  #1, “You can write your required text here”

VBA write to a text file: Example Macro Code

Following is the sample Excel Macro to write to a text file using Excel VBA.

Sub VBA_Print_to_a_text_file()
    Dim strFile_Path As String
    strFile_Path = "C:temptest.txt" ‘Change as per your test folder path
    Open strFile_Path For Output As #1
    Write #1, "This is my sample text"
    Close #1
End Sub 

Instructions to run the VBA Macro code to write to a text file

Please follow the below steps to execute the VBA code to write to a text file using Excel VBA Editor.

    Step 1: Open any Excel workbook [ To Open MS Excel: Go to Start menu, All programs and select Excel from MS Office OR You can simply type excel in the run command (Press Windows+ r key to open run dialog)]

  • Step 2: Press Alt+F11 to open the VBA Editor [You can also open the VBE from the Developer Tab in the Excel ribbon]
  • Step 3: Insert a code module [Go to insert menu in the VBE and then press Module OR Simply press the Alt+i then m to insert code module]
  • Step 4: Copy the above Example Macro code and paste in the code module which have inserted in the above step
  • Step 5: Change the folder path as per your testing folder structure
  • Step 6: Now press the F5 to Run and Execute the Macro.
  • You can press the F8 to debug the macro line by line and see the result immediately.

Once you are done with the macro execution, now you can observe that a text file in the test folder. And the text file in the folder is updated with the data which you have mentioned.

VBA write to a text file – Macro Explained

Here is the detailed explanation of the Excel macro to write to a text file using VBA.

  • Starting the program and sub procedure to write VBA code to write to a text file.
  • Declaring the strFile_Path variable as String Data Type to store the text file path.
  • Assigning the File path to the variable strFile_Path.
  • Opening the text file for Output with FileNumber as 1.
  • Writing to the sample text to the File using FileNumber and Write Command.
  • Closing the File using FileNumber.
  • Ending the Sub procedure to write VBA Code to write to a text file.

Here is the commented macro code for writing to text file using VBA.

‘Starting the program and sub procedure to write VBA code to write the data to a text file.
Sub VBA_write_to_a_text_file()

‘Declaring the strFile_Path variable as String Data Type to store the text file path.
Dim strFile_Path As String

‘Assigning the File path to the variable strFile_Path.
strFile_Path = “C:temptest.txt”

‘Opening the text file for Output with FileNumber as 1.
Open strFile_Path For Output As #1

‘Writing to the sample text to the File using FileNumber and Write Command.
Write #1, “This is my sample text”

‘Closing the File using FileNumber.
Close #1
End Sub
‘Ending the Sub procedure to write VBA Code to write to text file.

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • Writing to a text file Using VBA
    • VBA write to a text file: Procedure
    • VBA write to a text file: Syntax
    • VBA write to a text file: Example Macro Code
      • Instructions to run the VBA Macro code to write to a text file
    • VBA write to a text file – Macro Explained

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Чтение и запись в файл, открытый с помощью оператора Open. Операторы Input, Line Input, Write и функция EOF. Примеры использования в VBA Excel.

Операторы чтения и записи в файл

Оператор Input #

Оператор Input # считывает данные из открытого файла с последовательным доступом и присваивает эти данные переменным.

Оператор Input # используется только с файлами, открытыми в режиме Input или Binary. При прочтении стандартные строковые или числовые значения присваиваются переменным без изменения.

Синтаксис оператора Input #:

Input #Номер_файла, Переменные

Компоненты оператора Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменные – обязательный параметр, представляющий из себя список переменных, разделенных запятой, которым присваиваются значения, считанные из файла.

Особенности применения оператора Input #:

  • Элементы данных в файле должны быть указаны в том же порядке, что и переменные в списке Переменные, и соответствовать им по типу данных. Если переменная числовая, а данные текстовые, этой переменной будет присвоено нулевое значение.
  • Если при чтении данных достигнут конец файла, чтение прерывается и возникает ошибка. Для ее предупреждения в коде VBA Excel используется функция EOF.
  • Чтобы данные из файла могли быть правильно прочитаны и записаны в переменные с помощью оператора Input #, они должны быть записаны в файл с помощью оператора Write #. Он обеспечивает правильное разделение каждого из полей (элементов) данных.

Оператор Line Input #

Оператор Line Input # считывает одну строку из открытого файла с последовательным доступом и присваивает ее значение строковой переменной.

Оператор Line Input # считывает из файла по одному символу до тех пор, пока не встретится символ возврата каретки (Chr(13)) или последовательность символа возврата каретки и перевода строки (Chr (13) + Chr(10)).

Синтаксис оператора Line Input #:

Line Input #Номер_файла, Переменная

Компоненты оператора Line Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменная – обязательный параметр, представляющий из себя имя переменной, объявленной как String или Variant, которой присваивается строка, считанная из файла.

Оператор Write #

Оператор Write # записывает данные в файл с последовательным доступом.

Синтаксис оператора Write #:

Write #Номер_файла, [Данные]

Компоненты оператора Write #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Данные – необязательный параметр, представляющий из себя одно или несколько числовых или строковых выражений, разделенных запятой, которые нужно записать в файл.

Особенности применения оператора Write #:

  • Данные, записанные с помощью оператора Write #, считываются из файла с помощью оператора Input #.
  • Если опустить параметр Данные и добавить запятую после Номер_файла, в файл будет добавлена пустая строка.
  • Несколько выражений в списке Данные могут быть разделены точкой с запятой или запятой.
  • Числовые данные всегда записываются с точкой в качестве разделителя целой и дробной части.
  • Оператор Write # вставляет запятые между элементами и прямые парные кавычки вокруг строк при их записи в файл.
  • После записи в файл последнего символа из параметра Данные оператор Write # вставляет символы возврата каретки и перевода строки (Chr (13) + Chr(10)).

Функция EOF

Функция EOF возвращает логическое значение True, когда достигнут конец файла, открытого для последовательного (Input) или произвольного (Random) доступа.

Синтаксис функции EOF:

Номер_файла – это номер, присвоенный файлу при открытии с помощью оператора Open.

Функция EOF используется для предупреждения ошибок, вызываемых попытками выполнить чтение после конца файла. Она возвращает значение False, пока не будет достигнут конец файла.

Примеры чтения и записи в файл

Пример 1
Открытие (или создание, если он не существует) текстового файла для чтения и записи и запись в него одной строки, состоящей из двух текстовых и одного числового значений. Файл с именем myFile1.txt будет создан в той же папке, где расположен файл Excel с кодом VBA.

Sub Test1()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile1.txt» For Output As ff

‘Записываем в файл одну строку

Write #ff, «Дает корова молоко!», _

«Куда идет король?», 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile1.txt»)

End Sub

Строки и число можно предварительно присвоить переменным, объявленным с соответствующими типами данных, и использовать их для записи данных в файл (в строках кода с оператором Write #, как в этом и следующем примерах).

Пример 2
Открытие (или создание, если он не существует) файла без расширения для чтения и записи и запись в него трех строк: двух текстовых и одной в числовом формате. Файл с именем myFile2 будет создан в той же папке, где расположен файл Excel с кодом VBA.

Так как у файла нет расширения, Windows выведет диалоговое окно для выбора открывающей его программы. Выберите любой текстовый редактор или интернет-браузер.

Sub Test2()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile2» For Output As ff

‘Записываем в файл три строки

Write #ff, «Дает корова молоко!»

Write #ff, «Куда идет король?»

Write #ff, 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile2»)

End Sub

Пример 3
Считываем строку, разделенную на отдельные элементы, из файла myFile1.txt и записываем в три переменные, по типу данных соответствующие элементам.

Sub Test3()

Dim ff As Integer, str1 As String, _

str2 As String, num1 As Single

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile1.txt для чтения

Open ThisWorkbook.Path & «myFile1.txt» For Input As ff

‘Считываем строку из файла и записываем в переменные

Input #ff, str1, str2, num1

Close ff

‘Смотрим, что записалось в переменные

MsgBox «str1 = « & str1 & vbNewLine _

& «str2 = « & str2 & vbNewLine _

& «num1 = « & num1

End Sub

Попробуйте заменить в этом примере строку Input #ff, str1, str2, num1 сначала на строку Input #ff, str1, затем на строку Line Input #ff, str1, чтобы наглядно увидеть разницу между операторами Input # и Line Input #.

В следующих примерах (4 и 5) замена оператора Input # на Line Input # не приведет ни к каким изменениям, так как данные в строках файла myFile2 не разделены на элементы (поля).

Пример 4
Считываем поочередно три строки из файла myFile2 и записываем в три элемента массива, объявленного как Variant, так как в этот файл ранее были записаны две строки с текстом и одна с числом.

Sub Test4()

Dim ff As Integer, a(2) As Variant, i As Byte

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   For i = 0 To 2

      Input #ff, a(i)

   Next

Close ff

‘Смотрим, что записалось в элементы массива

MsgBox «a(0) = « & a(0) & vbNewLine _

& «a(1) = « & a(1) & vbNewLine _

& «a(2) = « & a(2)

End Sub

Пример 5
Считываем с помощью цикла Do While… Loop все строки из файла myFile2 и записываем построчно в переменную, объявленную как String (число из третьей строки запишется как текст). Для остановки цикла при достижении конца файла используем функцию EOF.

Sub Test5()

Dim ff As Integer, a As Variant, b As String

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   Do While Not EOF(ff)

      Input #ff, a

      b = b & a & vbNewLine

   Loop

Close ff

‘Смотрим, что записалось в переменную

MsgBox b

End Sub


Предыдущая часть темы об открытии файла для ввода и вывода информации опубликована в статье: Оператор Open (синтаксис, параметры). Смотрите также связанную статью: Функция FreeFile.

Смотрите, как создавать и открывать текстовые файлы с помощью методов CreateTextFile и OpenTextFile. Чтение файла, запись и добавление информации с помощью объекта TextStream.


Понравилась статья? Поделить с друзьями:
  • Write one word in each gap french
  • Write if function in excel
  • Write one word in each gap exercises
  • Write from vba to excel
  • Write one word in each gap defining the age