Writing data from text file to Excel cells

There are quite a few methods for writing data from a text file to Excel. The main are the following:

  • Through a Query Table
  • Through opening the text file and
    • Reading and writing line by line
    • Reading the text file, writing it to an array and writing from the array

Writing data from text file to Excel through a Query Table.

Writing the file through a query table has one advantage – it provides the possibility to update the data from the Excel interface. This is useful, as far as the end users should not go to the scary #VBA once the text file is changed:

In the code below, the file from which the data is taken is on the Desktop. It is named file.txt:

Writing data from text file to Excel. Reading and writing line by line.

This is a rather simple method, and the loop is supposed to be slow. The slowness comes from the fact, that the writing to the Excel file is written line by line. Up to a few hundred lines, the speed should be ok. For more, try to write it all at once, with the next method.

Writing data from text file to Excel. Reading the text file, writing it to an array and writing from the array.

This method is pretty much like the previous one, but with some advanced VBA features. Through this, the writing of the Notepad data to Excel is done on one single step. As you are probably aware, writing everything at once is quite faster than writing line by line. The advanced features that are used are:

  • Get
  • Space() Function
  • Write array to a range with 1 line - Range("D1").Resize(UBound(myArray()) + 1) = Application.Transpose(myArray)

Cheers! 🙂

Tagged with: , , , , ,