Excel vba работа с текстовыми файлами

Данные функции предназначены для работы с текстовыми файлами из VBA Excel.

Используя эти функции, вы при помощи одной строки кода сможете записать текст из переменной в файл, или наоборот, загрузить содержимое текстового файла в переменную.
Подразумевается, что текстовые файлы имеют формат ANSI (он же ASCII, он же windows-1251)

Чтение текстового файла в переменную:

Function ReadTXTfile(ByVal filename As String) As String
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.OpenTextFile(filename, 1, True): ReadTXTfile = ts.ReadAll: ts.Close
    Set ts = Nothing: Set fso = Nothing
End Function

Запись в текстовый файл из переменной:

Function SaveTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
    On Error Resume Next: Err.Clear
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.CreateTextFile(filename, True)
    ts.Write txt: ts.Close
    SaveTXTfile = Err = 0
    Set ts = Nothing: Set fso = Nothing
End Function

Добавление в текстовый файл из переменной:

Function AddIntoTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
    On Error Resume Next: Err.Clear
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.OpenTextFile(filename, 8, True): ts.Write txt: ts.Close
    Set ts = Nothing: Set fso = Nothing
    AddIntoTXTfile = Err = 0
End Function
  • 107061 просмотр

Не получается применить макрос? Не удаётся изменить код под свои нужды?

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

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

Automating Text Files With VBA Useful?

Text files can be a very fast and simple way to read and store information. I like to use them to save settings for my VBA add-ins or credentials for my macros that need to log into something.

I have seen situations where databases have exported large amounts of data into .txt files instead of Excel files (especially back in the days with Excel 2003).

Below are the main techniques I use to create, modify, extract data, and delete text files.

VBA Commands For Text File

When you are working with text files, there will be some terms used that you probably haven’t seen or used before when writing VBA code.  Let’s walk through these commands as you will see them throughout the VBA macros in this guide.

  • For Output — When you are opening the text file with this command, you are wanting to create or modify the text file. You will not be able to pull anything from the text file while opening with this mode.

  • For Input — When you are opening the text file with this command, you are wanting to extract information from the text file. You will not be able to modify the text file while opening it with this mode.

  • For Append — Add new text to the bottom of your text file content.

  • FreeFile — Is used to supply a file number that is not already in use. This is similar to referencing Workbook(1) vs. Workbook(2). By using FreeFile, the function will automatically return the next available reference number for your text file. 

  • Write — This writes a line of text to the file surrounding it with quotations

  • Print — This writes a line of text to the file without quotes

Create/Save A Text File With VBA Code

In this section, you will learn how to generate a new Text file and write data into it.

The Open function in combination with the For Output command creates a new text file automatically if the provided file path yields no result. The For Output command lets you enter an editing state instead of a read-only state.

After the new text file has been opened, you can utilize the Print function to write data to the text file. Each Print command adds a new line to the file.

Once you are finished writing data into the text file, you can simply Close it to save your changes.

Sub TextFile_Create()
‘PURPOSE: Create A New Text File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Output As TextFile

‘Write some lines of text
  Print #TextFile, «Hello Everyone!»
  Print #TextFile, «I created this file with VBA.»
  Print #TextFile, «Goodbye»

  ‘Save & Close Text File
  Close TextFile

End Sub

Create Text File From Spreadsheet Data

If you would like to write data into a new Text file from your spreadsheet, you can tweak the prior VBA macro code to loop through a range of cells and Print the cell data to the file.

Here’s an example of what you could create:

Sub TextFile_Create()
‘PURPOSE: Create A New Text File And Write Spreadsheet Data to File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim cell As Range

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Output As TextFile

‘Write Spreadsheet Data To File (exclude blank cells)
  For Each cell In Range(«A1:A20»)
    If cell.Value <> «» Then Print #TextFile, cell.Value
  Next cell

  ‘Save & Close Text File
  Close TextFile

End Sub

Extracting All Data From A Text File With VBA Code

If you are just wanting to pull the entirety of a text file’s contents and work with it in your VBA code, you can simply dump all the data into a string variable and then proceed to work with it.

The below VBA macro code will open a specific text file and store all of its contents into a string-based variable called FileContent. It’s then up to you to decide what you want to do next with that information :)

Sub TextFile_PullData()
‘PURPOSE: Send All Data From Text File To A String Variable
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Input As TextFile

‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Report Out Text File Contents
  MsgBox FileContent

‘Close Text File
  Close TextFile

End Sub

Edit/Modify A Text File With VBA Code (With Find/Replace)

If you need to edit the contents of a text file, you can open the file up in the For Input state. This will allow you to change things around and save your modifications.

For the example code in this article, you’ll learn how to use a Find and Replace functionality to replace all instances of the word “Goodbye” with “Cheers”.

We will also talk about adding data to the very end of a text file in a later section of this article.

Sub TextFile_FindReplace()
‘PURPOSE: Modify Contents of a text file using Find/Replace
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file in a Read State
  Open FilePath For Input As TextFile

‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Clost Text File
  Close TextFile

  ‘Find/Replace
  FileContent = Replace(FileContent, «Goodbye», «Cheers»)

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file in a Write State
  Open FilePath For Output As TextFile

  ‘Write New Text data to file
  Print #TextFile, FileContent

‘Close Text File
  Close TextFile

End Sub

Append Data To Your Text File With VBA Code

If you need to add data to the end of an existing text file, you can perform an Append action to the file.

The following VBA macro code shows you how to:

  1. Open a text file

  2. Write 3 lines of new data to the very bottom

  3. Save and close the file

Sub TextFile_Create()
‘PURPOSE: Add More Text To The End Of A Text File
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String

‘What is the file path and name for the new text file?
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile

‘Open the text file
  Open FilePath For Append As TextFile

‘Write some lines of text
  Print #TextFile, «Sincerely,»
  Print #TextFile, «»
  Print #TextFile, «Chris»

  ‘Save & Close Text File
  Close TextFile

End Sub

Deleting A Text File Macro Code

If you would like to automate deleting a text file, you can utilize the Kill command.

Delete A Single Text File With VBA

The following VBA macro code deletes a specific text file from the user’s Desktop.

Sub TextFile_Delete()
‘PURPOSE: Delete a Text File from your computer
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FilePath As String

‘File Path of Text File
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Delete File
  Kill FilePath

End Sub

Delete All Text Files In A Folder

If you are looking to perform file deletions on a larger scale you can write a looping macro that deletes all .txt files within a specified folder.

Sub DeleteTextFilesInFolder()
‘PURPOSE: To loop through and delete all Text files in a folder
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FolderPath As String
Dim TextFile As String
Dim FileExtension As String
Dim Counter As Long

‘Determine Folder Path and File Extension Type
  FolderPath = «C:UserschrisDesktop»
  FileExtension = «*.txt»

‘Target Path with Ending Extention
  TextFile = Dir(FolderPath & FileExtension)

‘Loop through each Excel file in folder
  Do While TextFile <> «»
    Kill FolderPath & TextFile ‘Delete file
    TextFile = Dir ‘Get next file name
    Counter = Counter + 1
  Loop

‘Message Box when tasks are completed
  MsgBox «Text Files Delete: » & Counter

End Sub

VBA To Read A Text File Line By Line

This section will show you how to extract each line or row of data from your text file. This may be helpful if you need to pass the data through some sort of logic test or if you are searching for certain data points within the text file.

Write Each Text File Line To The Spreadsheet

The following VBA macro code reads through each line of a designated text file and writes the entire line to a cell in your spreadsheet (you determine the starting point with the variable StartCell).

Sub AddTextFileToSpreadsheet()
‘PURPOSE: Loop through each row in Text File & Write to Excel
‘SOURCE: www.TheSpreadsheetGuru.com

Dim FilePath As String
Dim TxtLine As String
Dim StartCell As Range
Dim x As Long

‘Text File Path
  FilePath = «C:UserschrisDesktopMyFile.txt»

‘Determine first cell you want data in
  Set StartCell = ActiveSheet.Range(«A1»)

‘Open the text file in a Read State
  Open FilePath For Input As FreeFile

  ‘Loop through each row in Text File and Write to Spreadsheet
  Do Until EOF(1)
    Line Input #1, TxtLine
    StartCell.Offset(x) = TxtLine
    x = x + 1
  Loop

    ‘Close Text File
  Close FreeFile

  End Sub

Write Each Text File Line To An Array Variable

The following VBA macro code reads through each line of a designated text file and writes the entire line to an array variable name LineArray. You can reference any line by writing the row number you are targeting and subtracting 1 (since array values start at 0 instead of 1).

For example, to retrieve the data stored in Row 5 you would write LineArray(5-1) or simply LineArray(4).

Sub TextFileLinesToArray()
‘PURPOSE: Load an Array variable with each line of data text file
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String

‘Text File Path
  FilePath = «C:UserschrisDesktopMyFile.txt»

  ‘Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile

  ‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Close Text File
  Close TextFile

  ‘Separate Out lines of data (vbCrLf = Page Break)
  LineArray() = Split(FileContent, vbCrLf)

  ‘Communicate How Many Lines are in Text File
  MsgBox «There were » & UBound(LineArray) + 1 & » lines of data found in the Text File»

End Sub

Fill Array With Delimited Text File Data With VBA Code

This VBA macro code can read a Text file from a provided path and populate an array variable by splitting the data based on a delimiter (separator).

The Delimiter variable is what determines how to split the data. In the below example a semi-colon is being used. The most common delimiter in text files is a comma character.

Sub DelimitedTextFileToArray()
‘PURPOSE: Load an Array variable with data from a delimited text file
‘SOURCE: www.TheSpreadsheetGuru.com

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

‘Inputs
  Delimiter = «;»
  FilePath = «C:UserschrisDesktopMyFile.txt»
  rw = 0

  ‘Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile

  ‘Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

‘Close Text File
  Close TextFile

  ‘Separate Out lines of data
  LineArray() = Split(FileContent, vbCrLf)

‘Read Data into an Array Variable
  For x = LBound(LineArray) To UBound(LineArray)
    If Len(Trim(LineArray(x))) <> 0 Then
      ‘Split up line of text by delimiter
        TempArray = Split(LineArray(x), Delimiter)

            ‘Determine how many columns are needed
        col = UBound(TempArray)

            ‘Re-Adjust Array boundaries
        ReDim Preserve DataArray(col, rw)

            ‘Load line of data into Array variable
        For y = LBound(TempArray) To UBound(TempArray)
          DataArray(y, rw) = TempArray(y)
        Next y
    End If

        ‘Next line
      rw = rw + 1

      Next x

End Sub

I Hope This Microsoft Excel Article Helped!

Hopefully, I was able to explain how you can use VBA macro coding to manipulate and interact with Text Files for automated solutions. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon! — Chris

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 »

28 Апрель 2011              99027 просмотров

  • CurDir() — функция, которая возвращает путь к каталогу(для указанного диска), в котором по умолчанию будут сохраняться файлы:
        Dim sCurDir As String
        sCurDir = CurDir("D")
  • Dir() — позволяет искать файл или каталог по указанному пути на диске. Пример использования можно посмотреть в статье: Просмотреть все файлы в папке
  • EOF() — при операции записи в файл на диске эта функция вернет True, если вы находитесь в конце файла. Обычно используется при работе с текстовыми файлами — .txt. При сохранении книг Excel лучше использовать стандартные методы: Save и SaveAs.
  • Error() — позволяет вернуть описание ошибки по ее номеру. Генерировать ошибку нужно при помощи метода RaiseError() специального объекта Er.
  • Print — записывает в открытый файл указанный текст. Далее будет приведен пример использования данной функции
  • FreeFile() — позволяет определить номер следующего свободного файла, который можно использовать как номер файла при его открытии методом Open. Предпочтительно применять именно этот метод определения номера файла(вместо статичного #1), чтобы не было неоднозначности обращения к файлам. Ниже приведены примеры применения данной функции при обращении к файлам
  • FileAttr() — позволяет определить, как именно был открыт файл в файловой системе: на чтение, запись, добавление, в двоичном или текстовом режиме и т.п. Применяется для работы с текстовыми файлами, открытыми при помощи Open "C:Text1.txt" For [] As #1
    Открыть файл можно несколькими способами, приведу примеры наиболее распространенных вариантов:

    • Input() — открывает текстовый файл на чтение. Т.е. таким методом можно открыть файл и вытянуть из него данные. Например, чтобы считать информацию из файла C:Text1.txt и вывести ее в окно Immediate можно применить такой код:
          Dim MyChar
          Open "C:Text1.txt" For Input As #1 'Открываем файл функцией Open() на чтение(Input)
          Do While Not EOF(1)  'пока файл не кончился
              ' Получаем по одному символу и добавляем его к предыдущим
              MyChar = MyChar & Input(1, #1)
          Loop
          Close #1 ' Закрываем файл
          'Выводим его содержание в окно Immediate
          '(отобразить Immediate: Ctrl+G в окне редактора VBA)
          Debug.Print MyChar
          'или в MsgBox
          MsgBox MyChar, vbInformation, "www.excel-vba.ru"
    • Ouput() — метод открывает файл для записи. Например, чтобы записать в файл строку, содержащую все ячейки в выделенном диапазоне, можно использовать такой код:
      Sub SelectionToTxt()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Output As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub

      Важно помнить, что при открытии файла таким методом(Output) все предыдущие данные из файла стираются и в файле будет записано только то, что мы записали в текущем сеансе. Если данные необходимо добавить к имеющимся — используется метод Append

    • Append() — метод открывает файл для записи, но в отличии от Output записывает данные в конец файла, а не перезаписывает текущие данные. Например, код добавления выделенных ячеек как одной строки в имеющийся файл будет выглядеть так:
      Sub SelectionToTxt_Add()
          Dim s As String, rc As Range
          Dim ff
          'запоминаем все значения из выделенной строки в строку
          For Each rc In Selection
              If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки
                  s = rc.Value
              Else 'если уже записано - добавляем через TAB
                  s = s & vbTab & rc.Value
              End If
          Next
          ff = FreeFile
          'Открываем текстовый файл
          'если файла нет - он будет создан
          Open "C:Text1.txt" For Append As #ff
          'записываем значение строки в файл
          Print #ff, s
          Close #ff ' Закрываем файл
      End Sub
  • FileDateTime() — позволяет получить информацию о последнем времени обращения к указанному файлу. Если к файлу после создания ни разу не обращались, то это будет время создания файла. Если попытаться обратиться к уже открытой книге/файлу — то будет получено время открытия книги/файла, а не создания или сохранения.
        sFileDateTime = FileDateTime("C:Text1.txt")
  • FileLen() — позволяет определить длину указанного файла в байтах:
        MsgBox FileLen("C:Text1.txt") & " bites", vbInformation, "www.excel-vba.ru"
  • GetAttr() — возможность обратиться к файлу к файловой системе и получить информацию об его атрибутах (скрытый, доступен только для чтения, архивный и т.п.)
  • InputB() — позволяет указывать количество байт, которые надо считать из файла. Альтернатива методу Open в случаях, когда необходимо считывать данные не по конкретным строкам, а именно побайтово.
  • Loc() — от Location, то есть местонахождение — возвращает число, которое определяет текущее место вставки или чтения в открытом файле.
  • Seek() — очень похожа на функцию Loc(), но Seek() возвращает информацию о позиции, с которой будет выполняться следующая операция чтения или вставки.
  • LOF() — length of file — позволяет определить длину открытого файла в байтах.

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

Понравилась статья? Поделить с друзьями:
  • Excel vba работа с текстовым файлом
  • Excel vba работа с объединенными ячейками
  • Excel vba работа с листом
  • Excel vba работа с листами
  • Excel vba работа с именованными диапазонами