Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Parse text file line by line in VBA

Tags:

excel

vba

I'm trying to parse a text document using VBA and return the path given in the text file. For example, the text file would look like:

*Blah blah instructions *Blah blah instructions on line 2 G:\\Folder\...\data.xls D:\\AnotherFolder\...\moredata.xls 

I want the VBA to load 1 line at a time, and if it starts with a * then move to the next line (similar to that line being commented). For the lines with a file path, I want to write that path to cell, say A2 for the first path, B2 for the next, etc.

The main things I was hoping to have answered were:

  1. What is the best/simple way to read through a text file using VBA?
  2. How can I do that line by line?
like image 554
dancran Avatar asked Jul 17 '12 18:07

dancran


People also ask

How do I read a text file in a macro?

Approach: Step 1: Open Excel. Step 2: Add a shape (Read Text File) to your worksheet . Step 3: Right-click on “Read Text file” and “Assign Macro..”


1 Answers

for the most basic read of a text file, use open

example:

Dim FileNum As Integer Dim DataLine As String  FileNum = FreeFile() Open "Filename" For Input As #FileNum  While Not EOF(FileNum)     Line Input #FileNum, DataLine ' read in data 1 line at a time     ' decide what to do with dataline,      ' depending on what processing you need to do for each case Wend 

#Author note - Please stop adding in close #FileNum - it's addressed in the comments, and it's not needed as an improvement to this answer

like image 173
SeanC Avatar answered Sep 20 '22 22:09

SeanC