Excel vba чтение текстового файла построчно

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

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:

  1. What is the best/simple way to read through a text file using VBA?
  2. How can I do that line by line?

John Smith's user avatar

John Smith

7,1636 gold badges48 silver badges61 bronze badges

asked Jul 17, 2012 at 18:33

dancran's user avatar

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

SeanC's user avatar

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's user avatar

Robino

4,4092 gold badges36 silver badges40 bronze badges

answered Jul 17, 2012 at 19:59

Brad's user avatar

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.'s user avatar

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's user avatar

GJK

36.8k8 gold badges57 silver badges74 bronze badges

answered Dec 26, 2012 at 17:09

satheesh kumar's user avatar

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

Daniel L. VanDenBosch's user avatar

answered Nov 14, 2019 at 7:39

Tarun Reddy's user avatar

Tarun ReddyTarun Reddy

1,9432 gold badges10 silver badges6 bronze badges

2

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.

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:

  1. What is the best/simple way to read through a text file using VBA?
  2. How can I do that line by line?

John Smith's user avatar

John Smith

7,1636 gold badges48 silver badges61 bronze badges

asked Jul 17, 2012 at 18:33

dancran's user avatar

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

SeanC's user avatar

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's user avatar

Robino

4,4092 gold badges36 silver badges40 bronze badges

answered Jul 17, 2012 at 19:59

Brad's user avatar

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.'s user avatar

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's user avatar

GJK

36.8k8 gold badges57 silver badges74 bronze badges

answered Dec 26, 2012 at 17:09

satheesh kumar's user avatar

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

Daniel L. VanDenBosch's user avatar

answered Nov 14, 2019 at 7:39

Tarun Reddy's user avatar

Tarun ReddyTarun Reddy

1,9432 gold badges10 silver badges6 bronze badges

2

Return to VBA Code Examples

This tutorial will demonstrate how to read a text file into a string in VBA.

We can either read the text file line by line or as an entire file.

Read an Entire Text File into a String

Text in a text file is usually made up of several lines, separated by delimiters. These can be a comma (“,”), a comma with space (“, “), a semicolon (“;”), a  semicolon with space (“; “),  a space (“ “),  a tab (vbTab) or in rare cases any other character such as a tilde (~). The lines are normally separated by a line break (vbCRLF).

The easiest way to read an entire text file in VBA is to run the following code which will place the entire contents of the text file into a string variable.  This procedure uses the VBA Open statement and the VBA FreeFile function.

Sub ReadFile()
  Dim iTxtFile As Integer
  Dim strFile As String
  Dim strFileText As String
  strFile = "C:TestTestFile.txt"
  iTxtFile = FreeFile
  Open strFile For Input As FreeFile
  strFileText = Input(LOF(iTxtFile), iTxtFile)
  Close iTxtFile
End Sub

We can also read a text file in VBA by using the FileSystemObject. In the code below we have used late binding with the File System Object.

Sub ReadTextFile() 
  Dim strText As String 
  Dim FSO  as Object 
  Dim TSO As Object 
  Set FSO = CreateObject("Scripting.FileSystemObject") 
  Set TSO = FSO.OpenTextFile("C:TestTestFile.txt") 
  strText = TSO.ReadAll
  TSO.Close 
  Set TSO = Nothing
  Set FSO = Nothing
End Sub

We can also use early binding in the code and declare the File System Object by creating a reference in our Excel project to the File System Object.

Sub ReadTextFile() 
  Dim strText As String 
  Dim FSO as New FileSystemObject
  Dim TSO As Object 
  Set FSO = CreateObject("Scripting.FileSystemObject") 
  Set TSO = FSO.OpenTextFile("C:TestTestFile.txt") 
  strText = TSO.ReadAll 
  TSO.Close 
  Set TSO = Nothing
  Set FSO = Nothing
End Sub

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!

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