I’m trying to read a text file using vba. I tried the below code
Open "C:tester.txt" For Input As #1
Worksheets("UI").Range("H12").Value = Input$(LOF(1), 1)
Close #1
When I run this I’m getting an error.
Run-time error ’62’. Input past end of file.
The content of text file is:
Unable to open COM10. Make sure it is connected
Plus other stuff
And more stuff
way more stuff
Thanks in advance for help.
brettdj
54.6k16 gold badges113 silver badges176 bronze badges
asked Dec 5, 2013 at 2:43
5
Rather than loop cell by cell, you can read the entire file into a variant array, then dump it in a single shot.
Change the path from C:temptest.txt
to suit.
Sub Qantas_Delay()
Dim objFSO As Object
Dim objTF As Object
Dim strIn 'As String
Dim X
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile("C:temptest.txt", 1)
strIn = objTF.readall
X = Split(strIn, vbNewLine)
[h12].Resize(UBound(X) + 1, 1) = Application.Transpose(X)
objTF.Close
End Sub
ChaimG
6,8244 gold badges35 silver badges46 bronze badges
answered Dec 5, 2013 at 3:54
brettdjbrettdj
54.6k16 gold badges113 silver badges176 bronze badges
3
The following code will loop through each line in the text document and print these from range H12
and downward in the UI-sheet.
Sub ImportFromText()
Open "C:tester.txt" For Input As #1
r = 0
Do Until EOF(1)
Line Input #1, Data
Worksheets("UI").Range("H12").Offset(r, 0) = Data
r = r + 1
Loop
Close #1
End Sub
answered Dec 5, 2013 at 3:33
NetlohNetloh
4,3184 gold badges25 silver badges38 bronze badges
3
More Slightly modified for those who do not like VBA to have to make up explicit variables and then waste time transfer data to them.. Let With. do the job
Function LoadFileStr$(FN$)
With CreateObject("Scripting.FileSystemObject")
LoadFileStr = .OpenTextFile(FN, 1).readall
End With
End Function
3vts
7581 gold badge15 silver badges25 bronze badges
answered Jul 4, 2017 at 23:07
Harry SHarry S
4616 silver badges5 bronze badges
brettdj’s answer, slightly adjusted
Public Function readFileContents(ByVal fullFilename As String) As String
Dim objFSO As Object
Dim objTF As Object
Dim strIn As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(fullFilename, 1)
strIn = objTF.readall
objTF.Close
readFileContents = strIn
End Function
answered Aug 20, 2016 at 11:05
FidelFidel
6,90911 gold badges53 silver badges79 bronze badges
To read line by line:
Public Sub loadFromFile(fullFilename As String)
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Open fullFilename For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
Debug.Print DataLine
Wend
End Sub
answered Aug 20, 2016 at 11:46
FidelFidel
6,90911 gold badges53 silver badges79 bronze badges
Sub LoadFile() ' load entire file to string
' from Siddharth Rout
' http://stackoverflow.com/questions/20128115/
Dim MyData As String
Open "C:MyFile" For Binary As #1
MyData = Space$(LOF(1)) ' sets buffer to Length Of File
Get #1, , MyData ' fits exactly
Close #1
End Sub
answered Nov 8, 2016 at 22:57
dcromleydcromley
1,3381 gold badge8 silver badges23 bronze badges
1
I think an easier alternative is Data
> From Text
and you can specify how often the data is refreshed in the Properties.
answered Aug 20, 2016 at 11:50
SlaiSlai
21.9k5 gold badges43 silver badges52 bronze badges
Fidel’s answer, over Brettdj’s answer, adjusted for ASCII or Unicode and without magical numbers:
Public Function readFileContents(ByVal fullFilename As String, ByVal asASCII As Boolean) As String
Dim objFSO As Object
Dim objTF As Object
Dim strIn As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(fullFilename, IOMode:=ForReading, format:=IIf(asASCII, TristateFalse, TristateTrue))
strIn = objTF.ReadAll
objTF.Close
readFileContents = strIn
End Function
answered Dec 12, 2019 at 14:49
В нынешнее время использование текстовых файлов для обмена данными или хранения данных становится редкостью, но тем не менее, все еще встречается. Приведу два варианта чтения текстового файла из 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 & 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:
|
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.
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!
Данные функции предназначены для работы с текстовыми файлами из 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
- 107167 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.