Excel vba open file for reading

You can VBA Read file binary or text data using a couple of different approaches in Excel. VBA provides you a set of native statements like Open to open and ready files. However in this article aside from showing you these native approaches to reading files using Excel Macros you can read CSV files and other structured data schemas using Jet.OLEDB driver, Microsoft Queries or also the FileSystemObject.

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 reading files in VBA.

It is important to remember that you shouldn’t read all files using the same approach. Be aware of the structure of the file. If it is a structured CSV use the ADODB connection, if you need to read only a couple of rows read the file row by row or by chunks, else read the whole file. If you want performance – always select the right approach.

Reading text files in VBA

VBA Read text files (line by line)

To read an entire text file line by line use the code below.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number  
    
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
   Line Input #fileNo, textRow
   textData = textData & textRow
Loop
Close #fileNo

VBA Read text files (read whole file)

To read an entire text file in one go (not line by line) use the code below.a

Dim fileName As String, textData As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number   
 
Open fileName For Input As #fileNo
textData = Input$(LOF(fileNo), fileNo)
Close #fileNo

VBA Read specific number of lines from a text file

In cases when you want to read specific lines from a text file you can adapt the line by line read code as below. It allows you to read a certain number of lines (noLines) from a text file from a specific start line number (sLine). If you set noLines to 0 it will read all lines till end of the file.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
Dim lineCounter as Long, sLine as Long, noLines as Long

fileName = "C:text.txt"

sLine = 20 'number of the first line you want to read
noLines = 100 'number of lines you want to read

fileNo = FreeFile 
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
  Line Input #fileNo, textRow
  If lineCount >= sLine and ((noLines > 0 and lineCount < noLines + sLine) or noLines = 0) then
    textData = textData &amp; textRow
  End If
  lineCount = lineCount + 1   
Loop
Close #fileNo

Reading CSV files in VBA

Reading CSV files (read whole file and process each row)

Reading a text file line by line into a string:

'Assuming file looks like this. File path: C:test.csv
'"Col1", "Col2", "Col3"
'1     , 2     , 3

directory = "C:"
fileName = "test.csv" 'Assuming test.csv is in C: directory
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
strSQL = "SELECT * FROM " & fileName 
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst
Do
   col1 = rs("Col1")
   col2 = rs("Col2")
   col3 = rs("Col3")
   rs.MoveNext
Loop Until rs.EOF

Reading CSV files (whole file to Worksheet)

Read whole file to an Excel Worksheet:

Dim ws as Worksheet, destRng as Range, fileName as String
fileName = "C:text.txt"
Set destRng = Range("A1")
Set ws = ActiveSheet
With ws.QueryTables.Add(Connection:= "TEXT;" & fileName & "", Destination:=destRng)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 852
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    'Select your delimiter - selected below for Comma
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileTrailingMinusNumbers = True
    'This will refresh the query
End With

To refresh the CSV upload (in case the CSV was updated) simply run:

  
ws.QueryTables.Refresh BackgroundQuery:=False

Reading binary files in VBA

Dim fileName As String, fileNo As Integer, intVar As Integer
fileName = "C:text.bin"
fileNo = FreeFile

Open fileName For Binary Lock Read As #fileNo
Get #fileNo, , intVar
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 read Strings from binary files together with other data types. In such cases use the Type object data type when writing to a file. Learn more here.
Below a simple example of reading a file to which a Type data type was saved to, including an Integer and String.

Type TestType
    intVar As Integer
    strVar As String
End Type

Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = "C:test.bin"

    fileNo = FreeFile
    Open fileName For Binary Lock Read As #fileNo
    Get #fileNo, , testVar
    Debug.Print testVar.intVar 'Print the Integer
    Debug.Print testVar.strVar 'Print the String
    Close #fileNo
End Sub

Reading XML files in VBA

XML files are basically text files which follow the XML taxonomy. You can try to read and process XML files similarly as text files shown above. However, given you will probably want to extract specific XML tag or attribute information I suggest reading my dedicated article below.

Functions needed to read files in VBA

Function Description
Open [path_to_file] For [Mode] [Access] [Lock] As [long_variable] Opens the file for read/write and returns the # file number (needs to be type of long) into long_variable
More info here. Parameters below:

  • Mode – Append, Binary, Input, Output, or Random
  • Access optional. Read, Write, or Read Write
  • Lock optional. Shared, Lock Read, Lock Write, and Lock Read Write.
Close Closes the file using the # file number.
More info here.
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.

Above functions allow native upload of file data. However for more complicated scenario you will probably go for the FileSystemObject.

VBA Read File Summary

Reading files in VBA is not hard and requires just a few lines of code usually. It is, however, important to use the appropriate approach to read a file in VBA. Not all files need to be read line-by-line which is usually inefficient. Equally so you need not always read the entire file if you just need the first few / last rows. Working with XML files is also not a challenge if you read through my post on how to work with XML files.

Want to Write to files instead?

If you are looking to write to files instead using VBA, read my article on how to write to files using VBA.

Чтение и запись в файл, открытый с помощью оператора 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.


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”


Text files are a common source for storing and transporting information.

This topic will address access, key functions and ways to import and export this data with VBA.


VBA Open

To perform tasks with a text file in VBA you must first access it. We will do this through instruction Open.

Open requires parameters for:

  • O pathname (directory or folder, and drive)
  • O mode of access (Append, Binary, Input, Output, or Random)
  • A filenumber of access (represented by a unique number per file)
    Open PathName For Mode As #FileNumber.

Each of these parameters will be detailed below.


File’s Path

You can assign the path name in two ways:

    PathName = "C:testdatabase.txt" 'Directly through folders path

    PathName = Application.GetOpenFilename() 'Through a dialog box selecting the file

The first form is used when the path does not change constantly. The second gives freedom, at each execution, to choose a different path.

Both of these forms will result in PathName associated with a String of the file location.


Mode

The mode must be one of the following commands:

Output — Used to write Excel content to the text file

Input — Used to read the file

Append — Used to add content to a file

Binary — Used to read and write data in a byte format

Random — Used to place characters of defined size

The focus of this tutorial will be only on: Input (import) and Output (export).


File Number

Each open file must contain a numbering, a number between 1 and 511 preceded by a hashtag #. Normally the numbering starts at #1 and follows successively #2…

Use the FreeFile statement to get the next available file number. If none is in use, FreeFile() will return 1.


Testing Open Instruction

The following code will access the file you selected with Application.GetOpenFilename()

Sub OpenTeste()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:..."

    Dim FileNumber As Integer

    FileNumber  = FreeFile() 'Assigns the first available file number (E.g.: #1)

    Open PathName For Input As #FileNumber

    Close #FileNumber  'Closes the file (the number in FileNumber can be reused)
End Sub

Despite access, no information was imported or exported. To carry out these actions, we will need the help of the functions Input and Output respectively.


Import Text File

To import content from a text file into Excel we will use an example file called «database.txt» and the function Input:

Database TXT

Sub SimpleImport()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:...database.txt"

    Dim FileNumber As Integer

    Open PathName For Input As #1 'File will be associated with the #1

    FirstCharacter = Input(1, #1) 'Collect 1 character from file # 1
    SecondCharacter = Input(1, #1) 'Collect 1 more character, this being the next one (the 2nd in this case)

    MsgBox FirstCharacter
    MsgBox SecondCharacter

    Close #1 'Close the file (number #1 to be reused)
End Sub

MsgBox A

MsgBox q

To collect all the characters at once we can use the LOF function:

Sub LOFimport()

    Dim PathName As String

    PathName = Application.GetOpenFilename()
    'Opens the dialog box to select the file

    'Notice that PathName will be a path String E.g. "C:...database.txt"

    Dim FileNumber As Integer

    Open PathName For Input As #1 'File will be associated with the #1

    MsgBox LOF(1)  'Total number of characters in file # 1

    Allcharacters = Input(LOF(1), #1) 'Collect all characters from file # 1

    MsgBox Allcharacters

    Close #1 'Close the file (number #1 to be reused)
End Sub

LOF returns the number of bytes of the file opened with Open. Because this is a text file, each byte is one character. Thus, the number of bytes will equal the number of characters.

To import the data into spreadsheet we can use the following code:

Sub TextImport ()
    Dim PathName As String
    Dim FileNumber As Integer
    Dim Textdata As String
    Dim BreakingLine as Variant
    Dim Lastline as Integer
    Dim Firstline as Integer

    'Opens the dialog box to select the file
    PathName = Application.GetOpenFilename()
    'Or enter a path with PathName = "C:FILE_LOCATIONdatabase.txt"

    FileNumber = FreeFile() 'Assigns the first available file number (E.g.: #1)

    Open PathName For Input As #FileNumber 'Open file in read mode

    'Copy the contents to Worksheet ---
    Textdata = Input(LOF(FileNumber), FileNumber) 'Loads all file contents into variable
    BreakingLine = Split(Textdata, vbCrLf) 'Creates a vector with each line of the file 
    Lastline = UBound(BreakingLine) 'Determines the last line of the vector
    Firstline = LBound(BreakingLine) 'Determines the first line of the vector
    'Transpose the vectors into the worksheet
    Range("A1").Resize((Lastline) - (Firstline) + 1).Value = Application.Transpose(BreakingLine)
    '----------------------------------
    Close #FileNumber 'Closes the file (the number in FileNumber can be reused)
End Sub

vbCrLf is a non-visible character CrLf indicates a line break in the file.


Main Functions Related to Open

Function Description
FreeFile Returns the next available number for the Open statement. Important when working with multiple files.
BOF Returns True if it is at the beginning of the defined #filenumber.
EOF Returns True if it has finished reading the defined #filenumber.
LOF Returns the size in bytes of the defined #filenumber.
Loc Returns the current read and write position for the Open.

BOF and EOF assist in building Loops when you want to work character by character, or line by line.

Character per character

    'Collect one by one
    Characters = Input(1, #1) 'Collect 1 character from file # 1
    Characters = Characters & Input(1, #1) 'Collect 1 more character, this being the next
    Characters = Characters & Input(1, #1) 'Collect 1 more character, this being the next
    '...

Loop with EOF support

    'Loop with EOF support
    Characters = ""
    Do While Not EOF(1)
        Characters = Characters & Input(1, #1)
    Loop

Loop with BOF support

    'Loop with BOF support
    Do While BOF(1)
        Characters = Characters & Input(1, #1)
    Loop

Export Text File

To export worksheet content to a text file:

Sub TextExport()

    Dim LastRow As Long
    Dim LastColumn As Long
    Dim NewFile As String
    Dim FileNumber As Integer
    Dim CellData As Variant

    FileNumber = FreeFile ' Assigns the first available file number (E.g.: #1)

    'Determines the last row of the worksheet with data
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Determines the last column of the worksheet with data
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    NewFile = "C:TestExport.txt" 'Use an existing folder

    'Exports the data from the worksheet to the created file
    Open NewFile For Output As #FileNumber 
    For i = 1 To LastRow
        For j = 1 To LastColumn
            If j = LastColumn Then
                CellData = CellData & Cells(i, j).Value
            Else
                CellData = CellData & Cells(i, j).Value & " "
            End If
        Next j
        Print #FileNumber, CellData
        CellData = ""
    Next i
    Close #FileNumber 'Saves and closes the text file with the data
End Sub

An error will occur if the folder you are saving the file does not already exist.


CSV File

A .csv file (Comma Separated Values) is, as the name suggests, a text file in which the items in each row are separated by commas, delimiting what should go in each column.

CSV Example

It is a very common type of file, and since each line refers several times to multiple columns, it may require a treatment with loops and functions, such as BOF and EOF.


Import CSV File

For ease of import, the Line Input instruction (which works line by line), rather than just Input (which works character by character).

Sub OpenTextToCSV()
    Dim PathName As String
    Dim FileNumber As Integer
    Dim FileRow As String
    Dim RowItem As Variant
    Dim LastRow As Long

    'Opens the dialog box to select the file
    PathName = Application.GetOpenFilename()
    'Or enter a path Ex: PathName = "C:testdatabase.txt"

    FileNumber = FreeFile ' Assigns the first available file number (Ex: #1)

    Open PathName For Input As #FileNumber 'Opens the file in read mode

    Do Until EOF(FileNumber)
        Line Input #FileNumber, FileRow
            RowItem = Split(FileRow, ", ")
            i = i + 1
            LastRow = UBound(RowItem)
            For j = 1 To LastRow + 1
                Cells(i, j).Value = RowItem(j - 1)
            Next
    Loop

    Close #FileNumber
End Sub

Export CSV File

Similar to exporting text, however mandatory the use of «, « in the separation of elements.

Sub SaveTextToCSV()

    Dim LastRow As Long
    Dim LastColumn As Long
    Dim NewFile As String
    Dim FileNumber As Integer
    Dim CellData As Variant

    FileNumber = FreeFile ' Assigns the first available file number (Ex: #1)

    'Determines the last row of the worksheet with data
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Determines the last column of the worksheet with data
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    NewFile = "C:TestExport.csv" 'Use an existing folder

    'Exports the data from the worksheet to the created file
    Open NewFile For Output As #FileNumber
        For i = 1 To LastRow
            For j = 1 To LastColumn
                If j = LastColumn Then
                    CellData = CellData & Cells(i, j).Value
                Else
                    CellData = CellData & Cells(i, j).Value & ", "
                End If
            Next j
            Print #FileNumber, CellData
            CellData = ""
        Next i
    Close #FileNumber 'Saves and closes the text file with the data
End Sub

An error will occur if the folder you are saving the file does not already exist.



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Handling other files in VBA macros

As a programmer, you’re likely to come across many situations where other files need to be opened for reading, writing, or appending data. A macro can help you easily handle these files, and the Open method is your ticket.

Examples of real-life scenarios for file handling

Here are some applications where you can put this method to use:

  1. Team members updating their work status in SharePoint.
  2. Updating HP Quality Center through an add-in or an Excel macro.
  3. A schoolteacher marking the list of absentees in an Excel sheet and using an add-in (macro) that automatically fills in the attendance for all students in the class.
  4. Maintaining a skillset database for students and pulling this data from several workbooks whenever there is a need, like a competition or a tournament.
  5. Companies creating and send quotes by just filling out a form. Templates can also be used along with macros for this.

The VBA Open File method

VBA offers simple method to open and work on files. This permits a user to either read or write — or do both — after opening the file.

Syntax:

Open <path name> For <mode> [Access access] [lock]

Explaining the above parameters:

  1. <path name> : A mandatory field. It is the name of the file along with details of its extension, drive and directory.
  2. <mode> : This is a mandatory field. It can be any of the five options below:
    1. Append
    2. Binary
    3. Output
    4. Input
    5. Random – This is the default mode.
  3. Access :  This is an optional parameter. It lists out the operations that are allowed on the open file. It can be any one of the following:
    1. Read
    2. Write
    3. Read and write
  4. Lock : This is also an optional parameter. It can have any of the values below that are restricted on the opened file:
    1. Shared
    2. Lock read
    3. Lock write
    4. Lock read-write

Note: Tags within square brackets are optional. Here the access and lock tags are optional.

Examples of opening files using VBA

Example 1: Just open a file

This is a simple program which simply opens an Excel file.

Sub open_file_demo()

' declare variable
Dim pathname

' assign a value
pathname = "C:UsersLAKSHMI RAMAKRISHNANDownloadsProject 1.xlsx"

' now open the file using the open statement
Workbooks.Open pathname

End Sub

Example 2: Open an Excel workbook in “read only” mode and try to write to it

Sub open_file_demo()

' declare variables
Dim pathname
Dim wb As Workbook

' assign a value
pathname = "C:UsersLAKSHMI RAMAKRISHNANDownloadsProject 1.xlsx"

' now open the file using the open statement and assign it to the wb object so that it can be used in the code further.
Set wb = Workbooks.Open(Filename:=pathname, ReadOnly:=True)

' Try writing after opening the file in "read only mode". This should throw an error.
wb.Sheets(0).Cells(1, 1).Value = "Try writing"

End Sub

Example 3: Open a text file and read its contents using the Open function and file number

Sub TextFile_PullData()

' declare variables

Dim int_txtfile As Integer
Dim str_file_Path As String
Dim str_File_Content As String

' Assign the file path to the variable
  str_file_Path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Find the next available file number to be used by the fileopen function
  int_txtfile = FreeFile

' Open the said text file using the function
  Open str_file_Path For Input As int_txtfile

' The content of the file is stored in a variable
  str_File_Content = Input(LOF(int_txtfile), int_txtfile)

' Print the file content using the variable in which it is stored
  Debug.Print str_File_Content

' Close the opened text file
  Close int_txtfile

End Sub

Use file number to open and read a text file

Example 4: Read and then write content to a text file

In this example, we first open a text file in read mode and copy its content to a variable. Then we modify its content and open the same text file using write mode. Finally we write the modified content to the file.

Sub txt_file_FindReplace()

Dim txt_file As Integer
Dim file_path As String
Dim file_content As String

' Assign the file path to the variable
  file_path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Determine the next available file number to be used by the FileOpen function
  txt_file = FreeFile

'  The text file is opened in read-only mode
  Open file_path For Input As txt_file

' Store the content of the file in a variable
  file_content = Input(LOF(txt_file), txt_file)

' Close the opened Text File
  Close txt_file
  
' Find and replace some text
  file_content = Replace(file_content, "It", "This file")

' Determine the next available file number to be used by the FileOpen function
  txt_file = FreeFile

' Open the text file in a Write State
  Open file_path For Output As txt_file
  
' Write the modified content to the file
  Print #txt_file, file_content

' Close the opened Text File
  Close txt_file

End Sub

Read in content then write the text to a text file after opening

Example 5: Append data to a text file

In this example, we will add additional text to the end of an existing text file that already has some data.

Sub txt_file_append()

' declare variables

Dim int_txtfile As Integer
Dim str_file_Path As String
Dim str_File_Content As String

' Assign the file path to the variable
  str_file_Path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Find the next available file number to be used by the fileopen function
  int_txtfile = FreeFile

' Open the said text file using the function
  Open str_file_Path For Append As int_txtfile

' Write content to the end of the file
  Print #int_txtfile, "This is additional content"
  Print #int_txtfile, "Warm Regards"
  Print #int_txtfile, "Laksmi Ramakrishnan"

' Close the opened text file
  Close int_txtfile

End Sub

Open and add additional text to the end of a file.

Conclusion

Though there are many ways to open files with different extensions using VBA, in this article we have tried to focus on the most straightforward or simple methods of doing so.

The “open” mode in this openfile method plays a vital role here. If we try to append or write to a file that is opened using read mode, an error is thrown, halting the program’s run. So you can think of read mode as providing “data security” to the original file that is opened.

Понравилась статья? Поделить с друзьями:
  • Excel vba listbox filter
  • Excel vba for integer
  • Excel vba open all excel files
  • Excel vba listbox count
  • Excel vba for index