I’m trying to parse a text document using VBA and return the path given in the text file. For example, the text file would look like:
*Blah blah instructions
*Blah blah instructions on line 2
G:\Folder...data.xls
D:\AnotherFolder...moredata.xls
I want the VBA to load 1 line at a time, and if it starts with a *
then move to the next line (similar to that line being commented). For the lines with a file path, I want to write that path to cell, say A2
for the first path, B2
for the next, etc.
The main things I was hoping to have answered were:
- What is the best/simple way to read through a text file using VBA?
- How can I do that line by line?
John Smith
7,1636 gold badges48 silver badges61 bronze badges
asked Jul 17, 2012 at 18:33
0
for the most basic read of a text file, use open
example:
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Open "Filename" For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine ' read in data 1 line at a time
' decide what to do with dataline,
' depending on what processing you need to do for each case
Wend
#Author note — Please stop adding in close #FileNum
— it’s addressed in the comments, and it’s not needed as an improvement to this answer
answered Jul 17, 2012 at 18:48
SeanCSeanC
15.6k5 gold badges45 silver badges65 bronze badges
7
I find the FileSystemObject with a TxtStream the easiest way to read files
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)
Then with this txtStream
object you have all sorts of tools which intellisense picks up (unlike using the FreeFile()
method) so there is less guesswork. Plus you don’ have to assign a FreeFile and hope it is actually still free since when you assigned it.
You can read a file like:
Do While Not txtStream.AtEndOfStream
txtStream.ReadLine
Loop
txtStream.Close
NOTE: This requires a reference to Microsoft Scripting Runtime.
Robino
4,4092 gold badges36 silver badges40 bronze badges
answered Jul 17, 2012 at 19:59
BradBrad
11.9k4 gold badges44 silver badges70 bronze badges
2
For completeness; working with the data loaded into memory;
dim hf As integer: hf = freefile
dim lines() as string, i as long
open "c:blabla.bla" for input as #hf
lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf
for i = 0 to ubound(lines)
debug.? "Line"; i; "="; lines(i)
next
answered Jul 18, 2012 at 13:06
Alex K.Alex K.
170k30 gold badges263 silver badges286 bronze badges
2
You Can use this code to read line by line in text file and You could also check about the first character is «*» then you can leave that..
Public Sub Test()
Dim ReadData as String
Open "C:satheeshmyfilefile.txt" For Input As #1
Do Until EOF(1)
Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
If Not Left(ReadData, 1) = "*" then
'' you can write the variable ReadData into the database or file
End If
Loop
Close #1
End Sub
GJK
36.8k8 gold badges57 silver badges74 bronze badges
answered Dec 26, 2012 at 17:09
satheesh kumarsatheesh kumar
1391 gold badge2 silver badges8 bronze badges
The below is my code from reading text file to excel file.
Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:UsersTarunReddyNuthulaDesktopsample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
For j = LBound(lineitems) To UBound(lineitems)
ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
Next j
i = i + 1
Loop
Close #1
End Sub
answered Nov 14, 2019 at 7:39
Tarun ReddyTarun Reddy
1,9432 gold badges10 silver badges6 bronze badges
2
Чтение и запись в файл, открытый с помощью оператора 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.
В нынешнее время использование текстовых файлов для обмена данными или хранения данных становится редкостью, но тем не менее, все еще встречается. Приведу два варианта чтения текстового файла из VBA. Каждый способ может быть полезен в своей ситуации.
Способ 1. Открытие (чтение) текстового файла целиком
Можно открыть текстовый файл без учета каких-либо разделителей, сплошным текстом:
Set objExcel = New Excel.Application Set wb = objExcel.Workbooks.Open("имя_файла")
либо, если используются разделители колонок, можно их задействовать:
Открытие текстового файла с разделителем Tab:
Set objExcel = New Excel.Application Set wb = objExcel.Workbooks wb.OpenText Filename:="имя_файла", DataType:=xlDelimited, Tab:=True
Открытие текстового файла с разделителем ; (точка с запятой):
Set objExcel = New Excel.Application Set wb = objExcel.Workbooks wb.OpenText Filename:="имя_файла", DataType:=xlDelimited, Other:=True, OtherChar:=";"
В параметрах можно так же добавить Origin:=xlMSDOS, если текстовый файл в DOS-кодировке.
После открытия файла, его можно пройти как обычные ячейки Excel-кого листа.
Способ 2. Чтение текстового файла построчно
Здесь используется классический вариант чтения как в большинстве языков программирования: открытие файла, цикл чтения построчно, закрытие файла.
f = FreeFile Open "имя_файла" For Input As #f Do While Not EOF(f) Line Input #f, s ' что-нибудь делаем с полученной строкой s Loop Close f
В первой строке определяем число, представляющее следующий номер файла, доступный для использования оператором Open. Затем открываем файл, после чего делаем цикл в котором происходит построчное чтение.
VBA Program to read a Text file line by line (Sales Data) and places on a worksheet.
Sales Data in Text File: 5 Fields [ Product, Qtr 1, Qtr 2, Qtr 3 and Qtr 4 ] and 25 Records (Incl. header)
Sales data
VBA code will read a text file and places on worksheet cells as below
VBA Code:
- Declaring variables:
Variables | Data Type | Comments |
---|---|---|
line | String | Read text file line by line |
Filename | String | Input file name (Full path) |
i | Integer | Iterator |
valueArr() | String | split the sentence by comma and store it in an array variable of type String |
'Variable declarations Dim line As String, Filename As String, i As Integer, valuesArr() As String
- Initialize “Filename” variable with full path and filename
'Text file fullPath Filename = "D:ExcelReadTextFilesales.txt" 'update your full file path i = 1
- Open input file to read text
'Open file Open Filename For Input As #2
- Read input file line by line
'Read line by line - text file While Not EOF(2) Line Input #2, line
- Split by comma and store it in valueArr(). In our example, each line has 5 values concatenated with comma.
'split the line by comma separated, assigned in an array valuesArr() = Split(line, ",")
- Add text to respective cells from valuesArr(). Read each item in an array by it’s index value
Cells(i, "A").Value = valuesArr(0) Cells(i, "B").Value = valuesArr(1) Cells(i, "C").Value = valuesArr(2) Cells(i, "D").Value = valuesArr(3) Cells(i, "E").Value = valuesArr(4)
- Increment counter i, to move next line.
i = i + 1
- Close while loop
Wend
- Close file
'Close file Close #2
Approach:
Step 1: Open Excel.
Step 2: Add a shape (Read Text File) to your worksheet .
Step 3: Right-click on “Read Text file” and “Assign Macro..”
Step 4: Select ReadTextFileLineByLine Macro
Step 5: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm
Step 6: Click “Read Text file”
Step 7: Adjust column width in your excel file.
Return to VBA Code Examples
This tutorial will demonstrate how to read content from text files and paste it into worksheets with VBA.
Read Text File Content into Worksheet
The simplest way of reading a text file’s content is to copy it into a worksheet’s cell.
Sub FSOPasteTextFileContent()
Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FileToRead = FSO.OpenTextFile("C:TestTestFile.txt", ForReading) 'add here the path of your text file
TextString = FileToRead.ReadAll
FileToRead.Close
ThisWorkbook.Sheets(1).Range("A1").Value = TextString 'you can specify the worksheet and cell where to paste the text file’s content
End Sub
The above code uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library. See here for more information.
Without using FileSystemObject you can paste your text file’s content with the below code. If your text file contains line separator, it will be pasted line by line.
Sub PasteTextFileContent ()
Dim wbExcel As Workbook, wbText As Workbook
Dim wsExcel As Worksheet
Set wbExcel = ThisWorkbook 'specify here which Excel file the text file’s content is to be pasted into
Set wsExcel = wbExcel.Sheets(1) 'specify here which worksheet to use
Set wbText = Workbooks.Open("C:TestTestFile.txt") 'add here the path of your text file
wbText.Sheets(1).Cells.Copy wsExcel.Cells
wbText.Close SaveChanges:=False
End Sub
Read Text File Content Line by Line, Column by Column
Your text file may have several rows and several elements listed in the rows separated by comma, semicolon, tab, space, etc.. In order to read and paste the text file’s content correctly, you may need this code below:
Sub PasteTextFileContentWithSeparators()
Dim StrLine As String
Dim FSO As New FileSystemObject
Dim TSO as Object
Dim StrLineElements As Variant
Dim Index As Long
Dim i As Long
Dim Delimiter as String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TSO = FSO.OpenTextFile("C:TestTestFile.txt")
Delimiter=", " 'the delimiter that is used in your text file
Index = 1
Do While TSO.AtEndOfStream = False
StrLine = TSO.ReadLine
StrLineElements = Split(StrLine, Delimiter)
For i = LBound(StrLineElements) To UBound(StrLineElements)
Cells(Index, i + 1).Value = StrLineElements(i) 'this code will start pasting the text file’s content from the active worksheet’s A1 (Cell(1,1)) cell
Next i
Index = Index + 1
Loop
TSO.Close
End Sub
The delimiter that is used in your text file can be comma (“,”), comma with space (“, “), semicolon (“;”), semicolon with space (“; “), space (“ “), tab (change then Delimiter = vbTab) or in rare cases any other character.
Read Text Files into Arrays
If you need to read your text file’s content into an array and paste is line by line, column by column into your worksheet, you will need this code below:
Sub ReadDelimitedTextFileIntoArray()
Dim Delimiter As String
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As String
Dim TempArray() As String
Dim rw As Long, col As Long
Delimiter = vbTab 'the delimiter that is used in your text file
FilePath = "C:TestTestFileTab.txt"
rw = 1
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
Close TextFile
LineArray() = Split(FileContent, vbNewLine) 'change vbNewLine to vbCrLf or vbLf depending on the line separator that is used in your text file
For x = LBound(LineArray) To UBound(LineArray)
If Len(Trim(LineArray(x))) <> 0 Then
TempArray = Split(LineArray(x), Delimiter)
col = UBound(TempArray)
ReDim Preserve DataArray(col, rw)
For y = LBound(TempArray) To UBound(TempArray)
DataArray(y, rw) = TempArray(y)
Cells(x + 1, y + 1).Value = DataArray(y, rw) 'this code will start pasting the text file’s content from the active worksheet’s A1 (Cell(1,1)) cell
Next y
End If
rw = rw + 1
Next x
End Sub
Line separators in your text file can be carriage return and linefeed combination (Chr(13)+Chr(10)) or linefeed (Chr(10)). Use vbCrLf or vbLf, accordingly. If you are not sure, use vbNewLine for indicating the line separator.
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!
Learn More!