Vba excel считать текст

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!
vba save as

Learn More!

В нынешнее время использование текстовых файлов для обмена данными или хранения данных становится редкостью, но тем не менее, все еще встречается. Приведу два варианта чтения текстового файла из 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. Затем открываем файл, после чего делаем цикл в котором происходит построчное чтение.

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.

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.

Чтение и запись в файл, открытый с помощью оператора 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 excel считать значения с ячеек
  • Vba excel счетчик цикла
  • Vba excel счетчик строк
  • Vba excel сцепить ячейки в excel
  • Vba excel суммирование диапазона ячеек