+ Reply to Thread
Results 1 to 8 of 8

Macro to Import Multiple TXT Files into workbook - User to select files/directory

Hybrid View

  1. #1
    Registered User
    Join Date
    05-13-2013
    Location
    Brisbane
    MS-Off Ver
    Excel 2013
    Posts
    8

    Macro to Import Multiple TXT Files into workbook - User to select files/directory

    Spent most of today looking but just can't find the answer, hoping someone smarter than me here can help.

    I have uploaded the XLSM file I am working on and an example TXT file.

    What I am trying to do is import a series of these Comma Delimited TXT files from our scanners into a excel worksheet.
    I need the user to be able to select the files or at least the directly where the TXT files located as it will very depending on who is using the workbook.

    After they have selected them I want it to add all the txt file data stacked one on top of each other to the Worksheet called Data.
    I want the data to go in starting from Row 2 so that the header data stays intact

    FYI
    (also sheets are protected but with no password)

    Any help is greatly appreciated.
    Attached Files Attached Files

  2. #2
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    'CSVs To One Sheet (Stacked)
    A macro for importing all CSV files in a folder into a single Excel sheet, each CSV filename will be listed on the sheet next to the data that it came from.

    CSVs to 1 Sheet - Part 1




    Some suggested edits:

    1) update the name of the sheet wsMstr so that it matches your master sheet name
    2) The next line of code has a hardcoded fPATH where it will import all the files found in that folder. Your options are:

    - enter a specific path and require your people to create that folder on their systems and drop the import files into there
    - change that line of code to:
    fPATH = BrowseForFolderShell
    ...and put this separate function into the module, too, to give the macro the ability to prompt for a folder selection:
    Function BrowseForFolderShell() As String
    Dim objShell As Object, objFolder As Object
    
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "Please select a folder", 0, "C:\")      'SpecFolders.CSIDL_FAVORITES
    
    BrowseForFolderShell = CStr(objFolder.items.Item.Path & Application.PathSeparator)
    
    End Function

    3) Edit this line of code since your files are CSV files but have a TXT extension:
    fCSV = Dir(fPath & "*.txt")         'start the CSV file listing
    Last edited by JBeaucaire; 12-26-2019 at 03:38 PM.
    _________________
    Microsoft MVP 2010 - Excel
    Visit: Jerry Beaucaire's Excel Files & Macros

    If you've been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE] your code here [/CODE]

    ?None of us is as good as all of us? - Ray Kroc
    ?Actually, I *am* a rocket scientist.? - JB (little ones count!)

  3. #3
    Registered User
    Join Date
    05-13-2013
    Location
    Brisbane
    MS-Off Ver
    Excel 2013
    Posts
    8

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    Thanks I will try it.
    I did come accross that code but didn't know how to prompt for a directory.
    Also that code does not put the data into the worksheet DATA as I mentioned in my first post.
    I don't want it to import the files and create a new worksheet.
    I want to import them and place them in the DATA worksheet that is already made.

    Can this be done.

    thanks.

  4. #4
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    [QUOTE]
    Quote Originally Posted by saber007 View Post
    I don't want it to import the files and create a new worksheet.
    I want to import them and place them in the DATA worksheet that is already made.

    Can this be done?

    Quote Originally Posted by JBeaucaire
    1) update the name of the sheet wsMstr so that it matches your master sheet name

    Look at the code, the parts marked in red are for you to edit.

  5. #5
    Registered User
    Join Date
    05-13-2013
    Location
    Brisbane
    MS-Off Ver
    Excel 2013
    Posts
    8

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    Hi.
    Thanks for your help again.

    It is very close to working.
    However I have an issue importing the TXT file.
    It is not seeing it as a comma deliminated file and as such is just putting the data into one cell.
    Can you have a look at the below code and let me know what is missing.
    Thanks again.


    Sub ImportTXTsWithReference()
    
    Dim wbTXT   As Workbook
    Dim wsMstr  As Worksheet
    Set wsMstr = ActiveSheet
    If MsgBox("Inport and clear the existing Scanner Data?", vbYesNo, "Clear?") _
        = vbYes Then wsMstr.Range("DataTable").Clear
    
    Dim fPath   As String:      fPath = BrowseForFolderShell    'path to TXT files, include the final \
    Dim fTXT    As String
       
    
    Application.ScreenUpdating = False  'speed up macro
    
    fTXT = Dir(fPath & "*.txt")         'start the TXT file listing
    
        Do While Len(fTXT) > 0
          'open a CSV file
            Set wbTXT = Workbooks.Open(fPath & fTXT)
            
          'insert col A and add CSV name
            Columns(1).Insert xlShiftToRight
            Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
          'copy date into master sheet and close source file
            ActiveSheet.UsedRange.Copy wsMstr.Range("A" & Rows.Count).End(xlUp).Offset(1)
            wbTXT.Close False
          'ready next CSV
            fTXT = Dir
        Loop
     
    Application.ScreenUpdating = True
    End Sub
    
    Function BrowseForFolderShell() As String
    Dim objShell As Object, objFolder As Object
    
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "Please select a folder", 0)      'SpecFolders.CSIDL_FAVORITES
    
    BrowseForFolderShell = CStr(objFolder.items.Item.Path & Application.PathSeparator)
    
    End Function

  6. #6
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    Simplest solution is to have the macro rename the files as .CSV files, is that ok?

        Do While Len(fTXT) > 0
          'temporarily rename the file
            Name fPATH & fTXT As fPATH & Replace(fTXT, ".txt", ".csv")
    
          'open a CSV file
            Set wbTXT = Workbooks.Open(fPATH & fTXT)
          'insert col A and add CSV name
            Columns(1).Insert xlShiftToRight
            Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
          'copy date into master sheet and close source file
            ActiveSheet.UsedRange.Copy wsMstr.Range("A" & Rows.Count).End(xlUp).Offset(1)
            wbTXT.Close False
    
          'put the filename back
            Name fPATH & fTXT As fPATH & Replace(fTXT, ".csv", ".txt")
    
          'ready next CSV
            fTXT = Dir
        Loop
    Last edited by JBeaucaire; 05-13-2013 at 11:23 PM.

  7. #7
    Registered User
    Join Date
    05-13-2013
    Location
    Brisbane
    MS-Off Ver
    Excel 2013
    Posts
    8

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    I put it in but now it is not importing anyting.... I am going nuts.
    What did I miss.

    Sub ImportTXTsWithReference()
    'Author:    Jerry Beaucaire
    'Date:      10/16/2010
    'Summary:   Import all CSV files from a folder into a single sheet
    '           adding a field in column A listing the CSV filenames
    
    
    Dim wbTXT   As Workbook
    Dim wsMstr  As Worksheet
    Set wsMstr = ActiveSheet
    If MsgBox("Inport and clear the existing Scanner Data?", vbYesNo, "Clear?") _
        = vbYes Then wsMstr.Range("DataTable").Clear
    
    Dim fPath   As String:      fPath = BrowseForFolderShell    'path to TXT files, include the final \
    Dim fTXT    As String
       
    
    Application.ScreenUpdating = True  'speed up macro
    
    fTXT = Dir(fPath & "*.csv")        'start the TXT file listing
            
    Do While Len(fTXT) > 0
          'temporarily rename the file
            Name fPath & fTXT As fPath & Replace(fTXT, ".txt", ".csv")
    
          'open a CSV file
            Set wbTXT = Workbooks.Open(fPath & fTXT)
          'insert col A and add CSV name
            Columns(1).Insert xlShiftToRight
            Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
          'copy date into master sheet and close source file
            ActiveSheet.UsedRange.Copy wsMstr.Range("A" & Rows.Count).End(xlUp).Offset(1)
            wbTXT.Close False
    
          'put the filename back
            Name fPath & fTXT As fPath & Replace(fTXT, ".csv", ".txt")
    
          'ready next CSV
            fTXT = Dir
        Loop
        
    Application.ScreenUpdating = True
    End Sub
    
    Function BrowseForFolderShell() As String
    Dim objShell As Object, objFolder As Object
    
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "Please select a folder", 0)      'SpecFolders.CSIDL_FAVORITES
    
    BrowseForFolderShell = CStr(objFolder.items.Item.Path & Application.PathSeparator)
    
    End Function

  8. #8
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Macro to Import Multiple TXT Files into workbook - User to select files/directory

    Set wsMstr = ActiveSheet
    This seems dangerous. Certainly there is a specific sheetname? What is it?


    If MsgBox("Inport and clear the existing Scanner Data?", vbYesNo, "Clear?") _
        = vbYes Then wsMstr.Range("DataTable").Clear
    I cannot locate this named range. Where is it?

    fTXT = Dir(fPath & "*.csv")        'start the TXT file listing
    That may be the problem, right there. Your files are .txt files still at this point, so the filter needs to be .txt, not .csv



    Some other corrections:
    Do While Len(fTXT) > 0
          'temporarily rename the file
            Name fPath & fTXT As fPath & Replace(fTXT, ".txt", ".csv")
    
          'open a CSV file
            Set wbTXT = Workbooks.Open(fPath & Replace(fTXT, ".txt", ".csv"))
    
          'insert col A and add CSV name
            Columns(1).Insert xlShiftToRight
            Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
    
          'copy date into master sheet and close source file
            ActiveSheet.UsedRange.Copy wsMstr.Range("A" & Rows.Count).End(xlUp).Offset(1)
            wbTXT.Close False
    
          'put the filename back
            Name fPath & Replace(fTXT, ".txt", ".csv") As fPath & fTXT
    
          'ready next CSV
            fTXT = Dir
        Loop

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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.6.0 RC 1