Reading Text Files in VBA
Reading Text Files in VBA
Reading Text Files in VBA
'split by record-delimiter
vRecords = Split(FileContents, vbCrLf)
'Create overall array to store entire text file's fields and records
' Note that this step is not necessary, just speeds up overall processing time
Visual Basic
1 Dim fileName As String, textData As String, textRow As String, fileNo As Integer
2 fileName = "C:\text.txt"
3 fileNo = FreeFile 'Get first free file number
4
5 Open fileName For Input As #fileNo
6 Do While Not EOF(fileNo)
7 Line Input #fileNo, textRow
8 textData = textData & textRow
9 Loop
10 Close #fileNo
Visual Basic
Visual Basic
1 'Assuming file looks like this. File path: C:\test.csv
2 '"Col1", "Col2", "Col3"
3 '1 , 2 , 3
4
5 directory = "C:\"
6 fileName = "test.csv" 'Assuming test.csv is in C:\ directory
7 Set rs = CreateObject("ADODB.Recordset")
8 strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
9 & "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
10 strSQL = "SELECT * FROM " & fileName
11 rs.Open strSQL, strcon, 3, 3
12 rs.MoveFirst
13 Do
14 col1 = rs("Col1")
15 col2 = rs("Col2")
16 col3 = rs("Col3")
17 rs.MoveNext
18 Loop Until rs.EOF
Visual Basic
Visual Basic
1 ws.QueryTables.Refresh BackgroundQuery:=False
Get next free file number available for the Open statement / FileOpen function. Using
this function is important especially when operating on multiple files simultaneously.
FreeFile More info here.
Returns true if you are at the beginning of the file described by the file number.
BOF(fileNumber) More info here.
Returns true if you have reached the end of the file described by the file number. More
EOF(fileNumber) 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.
Sub WhatFileExtension()
Dim filExt As String
filExt = InputBox("What file extension?")
If filExt = "" Then Exit Sub
If InStr(filExt, "xls") = 0 Then Exit Sub
Workbooks.Open Filename:="C:\Users\Desktop\Excel." & filExt
End Sub