+ Reply to Thread
Results 1 to 7 of 7

looping macro for all files in a specified folder

Hybrid View

  1. #1
    Registered User
    Join Date
    10-18-2013
    Location
    Troy, MI
    MS-Off Ver
    Excel 2007
    Posts
    12

    looping macro for all files in a specified folder

    Good Morning All,
    Still a little new to the excel vba programming but was hoping that someone could assist me in a macro I wish to create. I have a folder containing n number of data files all of the same format and wish to create a macro that will loop through all of the files in the folder and apply the macro listed below.
    I have set up the macro below to run through one data file that has been selected by the user and now wish to apply it to all files in said folder. I know there is a loop option but can anyone explain to me how to do this?
    Thanks so much,

    Mel




    Sub Import_PCH_File()
    '
    ' Import_PCH_File Macro
    ' Importing PCH File to run Stiffness_Macro
    '
    
    Dim Input_File As Variant
    Dim Input_File_Name As String
    
    Input_File = Application.GetOpenFilename(Title:="Choose your file", _
    FileFilter:="All Files (*.*), *.*")
    Input_File_Name = CStr(Input_File)
    If Right(Input_File_Name, 1) <> "\" Then Input_File_Name = Input_File_Name & "\"
    
        With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;" & Input_File, _
            Destination:=Range("$A$1"))
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlFixedWidth
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
            .TextFileFixedColumnWidths = Array(16, 2, 20, 16, 20)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
        Sheets("Limits").Select
        Calculate
        Sheets("Extracted_Data").Select
        Calculate
        Sheets("Stiffness_Calculator").Select
        Calculate
        Sheets("Stiffness_Plots").Select
        Calculate
        Sheets("LL_Results").Select
        Calculate
        Sheets("UL_Results").Select
        Calculate
        ActiveWorkbook.SaveAs Filename:=Left(Input_File_Name, InStrRev(Input_File_Name, ".")) & "xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    End Sub

  2. #2
    Forum Expert
    Join Date
    04-22-2013
    Location
    .
    MS-Off Ver
    .
    Posts
    4,418

    Re: looping macro for all files in a specified folder

    Function Import_PCH_File(Input_File As String)
    Input_File_Name = CStr(Input_File)
    If Right(Input_File_Name, 1) <> "\" Then Input_File_Name = Input_File_Name & "\"
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Input_File, _
        Destination:=Range("$A$1"))
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(16, 2, 20, 16, 20)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Application.CalculateFull
    ActiveWorkbook.SaveAs Filename:=Left(Input_File_Name, InStrRev(Input_File_Name, ".")) & "xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    End Function
    Sub Import_Many_Files()
    Dim Input_File, Input_File_Name
    Input_File = Dir("C:\ExamplePath\*.xls")
    Do Until Dir = ""
        Call Import_PCH_File(Input_File)
        Input_File = Dir
    Loop
    End Sub

  3. #3
    Registered User
    Join Date
    10-18-2013
    Location
    Troy, MI
    MS-Off Ver
    Excel 2007
    Posts
    12

    Re: looping macro for all files in a specified folder

    Thank you so much for your quick reply. I am getting a byRef argument type mismatch for the Input_File in the Call Import_PCH_File
    How can I address this?

    Thank you!!!!!!!

  4. #4
    Registered User
    Join Date
    10-18-2013
    Location
    Troy, MI
    MS-Off Ver
    Excel 2007
    Posts
    12

    Re: looping macro for all files in a specified folder

    Yudlugar,
    Thanks for the code. I delcared the variables as string and then applied what Carl Willems was talking about above so that the path would be set accordingly. I am receiving an error of "1004 excel cannot find the text file to refresh this external data range".
    Any reason to why this might be?
    Last edited by Robo25; 11-11-2013 at 03:01 PM.

  5. #5
    Registered User
    Join Date
    06-24-2013
    Location
    Turnhout, Belgium
    MS-Off Ver
    Excel 2010
    Posts
    6

    Re: looping macro for all files in a specified folder

    Hi,
    file handling is done by the FileSytemObject class. This is contained in the reference "Microsoft Scripting Runtime" that you'll want to your project (Tools - References). Once you have that you can easily loop through the files:
    Option Explicit
    Sub LoopFiles()
        Dim fs As New FileSystemObject
        Dim FolderName As String
        Dim theFile As File
        Dim fldr As FileDialog
        
        Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
        With fldr
            .Title = "Select a Folder"
            .AllowMultiSelect = False
            If .Show = -1 Then
                FolderName = .SelectedItems(1)
            Else
                Exit Sub
            End If
        End With
        For Each theFile In fs.GetFolder(FolderName).Files
            'do your stuff
        Next theFile
    End Sub

  6. #6
    Registered User
    Join Date
    10-18-2013
    Location
    Troy, MI
    MS-Off Ver
    Excel 2007
    Posts
    12

    Re: looping macro for all files in a specified folder

    Thank you for your quick response. I will look more into this file system

  7. #7
    Forum Expert
    Join Date
    04-22-2013
    Location
    .
    MS-Off Ver
    .
    Posts
    4,418

    Re: looping macro for all files in a specified folder

    You can't combine my solution with Carl's.

    Using Filesystemobject to loop through the files will return each file as an object (file object to be precise). The function I gave you requried the file as a string. I gave you the macro at the bottom that uses VBA's dir() function which loops through files in a folder but returns the files as a string. This is the one you need to use, or you need to change use the .path/.name properties of the file to get the filename as string. That will address your byref mismatch issue.

    In essence the two methods for doing this are:
    dim fil as string
    fil = dir("C:\example path\*.xls") 'returns file as a string
    do until dir="" 'loops until all files in folder have been done
       'code to run on fil
       fil = dir 'finds next file
    loop
    or
    dim fso as object, fil as object, fol as object
    set fso = createobject("scripting.filesystemobject")
    set fol = fso.getfolder("C:\example folder\")
    for each fil in fol.files
      'code to run on fil, might need to test for file extension type...
    next
    Note: the second method is similar to what Carl did but with late binding so it does not need the reference to the filesystemobject.

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. Looping through a folder of files in VBA
    By lizzo in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-13-2013, 05:29 PM
  2. looping through files in a folder
    By bored in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 08-28-2012, 02:20 AM
  3. Looping through files in a folder
    By pdb78 in forum Excel General
    Replies: 4
    Last Post: 01-27-2012, 12:16 PM
  4. Looping a macro over all files in a folder for a file conversion
    By hippie_dream in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 03-10-2011, 12:11 PM
  5. Looping through files in a folder
    By prepotency in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 07-13-2005, 11:23 AM

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