was wondering if anyone has an example vb code to import a text file into excel delimited by spaces - regardless of number of spaces. In the text file there are for example 100k lines and in each line, each word can be separated by one, two or three etc spaces.
the result of the import into excel is that each line from the text file is in each row, and each word from each line separated by spaces are in each column of that row.
I tried to accomplish this by reading each line in the text file and then to parse each word for each line, and put these into a variable and then write it to excel. I think this way takes longer, and I am in the middle of parsing each line. But I think importing the text file into excel delimited by spaces is quicker if this can be done. The reason I use vb instead of vba is because vb can create an executable file which can be run by scheduler. Thanks
Dim reader As New System.IO.StreamReader("C:\test.txt")
Dim allLines As List(Of String) = New List(Of String)
Dim stringreader As String
Dim a As String
stringreader = filereader.ReadLine()
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
stringreader = reader.ReadLine()
MsgBox("The first line of the file is " & stringreader)
Loop
In this example
StreamReader
andExcel
are opened first. Then newWorkbook
and newWorksheet
are added. Finally the text file is read line by line. Each line is split on spaces and written toExcel Worksheet
. After the text file was processed theStream
is closed and theExcel
with the results remains opened. HTHEDIT:
It is possible to use
QueryTables
ofExcel
to import text data. There are some settings to consider, likeTextFileColumnDataTypes
. Here in this example all the columns are set toxlColumnDataType.xlTextFormat
.