+ Reply to Thread
Results 1 to 4 of 4

Thread: .txt import loop

  1. #1
    Registered User
    Join Date
    09-01-2011
    Location
    United States
    MS-Off Ver
    Excel 2007
    Posts
    2

    .txt import loop

    How would I create a loop with Microsoft Visual Basic to import multiple .txt files into excel; creating a seperate worksheet for each .txt file and nameing the worksheet based on the filename? I have hundreds of these .txt files. I would also like to be able to import more of these .txt files into the same workbook in the future.

    Thank You

  2. #2
    Forum Guru Domski's Avatar
    Join Date
    12-14-2009
    MS-Off Ver
    What does it matter?
    Posts
    3,933

    Re: .txt import loop

    Not tested but maybe:

    Sub Import_Text()
    
    Dim strFilePath As String
    Dim strFileName As String
    Dim wsWriteSheet As Worksheet
    
    strFilePath = "C:\Test"
    
    strFileName = Dir(strFilePath & "\*.txt")
    
    Do While strFileName <> ""
        Open strFilePath & "\" & strFileName For Input As #1
        Set wsWriteSheet = Worksheets.Add(after:=Sheets(Sheets.Count))
        With wsWriteSheet
            .Range("A1") = Input(LOF(1), #1)
            .Name = strFileName
        End With
        Close
        strFileName = Dir()
    Loop
    
    End Sub

    Dom
    "May the fleas of a thousand camels infest the crotch of the person who screws up your day and may their arms be too short to scratch..."

    Use code tags when posting your VBA code: [code] Your code here [/code]

    Remember, saying thanks only takes a second or two. Click the little star to give some Rep if you think an answer deserves it.

  3. #3
    Registered User
    Join Date
    09-01-2011
    Location
    United States
    MS-Off Ver
    Excel 2007
    Posts
    2

    Re: .txt import loop

    Thank You I will try it

  4. #4
    Forum Guru snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,151

    Re: .txt import loop

    Each file in a separate worksheet in the same workbook:

     
    Sub tst()
     c00 = "E:\"
     c01 = Dir(c00 & "*.txt")
      
     Do Until c01 = ""
      FileCopy c01, Replace(c01, ".txt", ".csv")
      With GetObject(Replace(c01, ".txt", ".csv"))
       .Sheets(1).Copy , ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
       .Close
      End With
      c01 = Dir
     Loop
    End Sub



+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0