title: How to add the file names of the file used to import text data
body: <p>I found a Macro that works great for importing data from text files in a specified directory.  </p>
  
  <p>I don’t have any real experience writing in VBA but was wondering if there is a way to take the code below and add the ability to put the name of the file the macro retrieved the data from into a column (<em>like column A</em>).  </p>
  
  <p>I am using this for searching 100+ logs for a specific data and having the ability to import all the data from those logs into excel makes it really easy. Now I just need a way to see which file the data came from. Thanks in advance, I look forward to learning something new.</p>
  
  <p><strong>Macro</strong>:</p>
  
  <pre><code>Sub ReadFilesIntoActiveSheet()
      Dim fso As FileSystemObject
      Dim folder As folder
      Dim file As file
      Dim FileText As TextStream
      Dim TextLine As String
      Dim Items() As String
      Dim i As Long
      Dim cl As Range
  
      ' Get a FileSystem object
      Set fso = New FileSystemObject
  
      ' get the directory you want
      Set folder = fso.GetFolder("My File Path")
  
      ' set the starting point to write the data to
      Set cl = ActiveSheet.Cells(1, 1)
  
      ' Loop thru all files in the folder
      For Each file In folder.Files
          ' Open the file
          Set FileText = file.OpenAsTextStream(ForReading)
  
          ' Read the file one line at a time
          Do While Not FileText.AtEndOfStream
              TextLine = FileText.ReadLine
  
              ' Parse the line into | delimited pieces
              Items = Split(TextLine, "|")
  
              ' Put data on one row in active sheet
              For i = 0 To UBound(Items)
                  cl.Offset(0, i).Value = Items(i)
              Next
  
              ' Move to next row
              Set cl = cl.Offset(1, 0)
          Loop
  
          ' Clean up
          FileText.Close
      Next file
  
      Set FileText = Nothing
      Set file = Nothing
      Set folder = Nothing
      Set fso = Nothing
  End Sub
  </code></pre>