Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading entire text file using vba

Tags:

excel

vba

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.

like image 766
Sanket Avatar asked Dec 05 '13 02:12

Sanket


People also ask

How do I view entire text in Excel?

Display all contents with Wrap Text function In Excel, the Wrap Text function will keep the column width and adjust the row height to display all contents in each cell. Select the cells that you want to display all contents, and click Home > Wrap Text. Then the selected cells will be expanded to show all contents.

What is LOF VBA?

LOF(filenumber) The required filenumber argument is an Integer containing a valid file number. Note. Use the FileLen function to obtain the length of a file that is not open.


2 Answers

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
like image 74
Fidel Avatar answered Sep 26 '22 09:09

Fidel


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:\temp\test.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:\temp\test.txt", 1)
strIn = objTF.readall
X = Split(strIn, vbNewLine)
[h12].Resize(UBound(X) + 1, 1) = Application.Transpose(X)
objTF.Close

End Sub
like image 42
brettdj Avatar answered Sep 26 '22 09:09

brettdj