' Based on code by Suat Mehmet Ozgur of Istanbul, Turkey.
' Suat develops applications in Excel, Access, and Visual Basic
' found at:
' http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Excel/Q_27980851.html
Option Explicit
Sub ReadTxtLines()
Dim sht As Worksheet
Dim fso As Object
Dim fil As Object
Dim txt As Object
Dim strtxt As String
' choose which file to open
Const fName As String = "EoDFile.csv"
'Const fName As String = "EoDFile.working.csv"
'Working on the relevant sheet
Set sht = Sheets(fName)
'Clear data in the sheet
sht.UsedRange.ClearContents
'File system object that we need to manage files
Set fso = CreateObject("Scripting.FileSystemObject")
'File that we like to open and read
Set fil = fso.GetFile("C:\Users\Trevor\Downloads\" & fName)
'Opening file as a TextStream
Set txt = fil.OpenAsTextStream(1)
'Reading file include into a string variable at once
strtxt = txt.ReadAll
'Close textstream and free the file. We don’t need it anymore.
txt.Close
'Find the first placement of new line char
Dim lSep As Long, chrSep
lSep = InStr(1, strtxt, vbCrLf)
If lSep = 0 Then
chrSep = vbLf
Else
chrSep = vbCrLf
End If
Dim lineText
lineText = Split(strtxt, chrSep)
Application.ScreenUpdating = False
With sht
' output the data
.Range("A1").Resize(UBound(lineText) + 1, 1) = Application.Transpose(lineText)
' split the data with Text to Columns
.Range("A1").Resize(UBound(lineText) + 1, 1) _
.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array _
(Array(1, 1), Array(2, 1), Array(3, 1), _
Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1), Array(8, 1), Array(9, 1), _
Array(10, 1), Array(11, 1), Array(12, 1), _
Array(13, 1), Array(14, 1)), _
TrailingMinusNumbers:=True
' autofit the column width
.Range("A3").CurrentRegion.EntireColumn.AutoFit
End With
Application.ScreenUpdating = True
' It will be already released by the ending of this procedure but
' as a good habit, set the object as nothing.
Set fso = Nothing
End Sub
Bookmarks