简体   繁体   中英

Import all type of files (cvs, xls, txt) to one master excel file from a folder directory

I'm working on a macro that needs to select any folder I want and import every type of file within that folder that's cvs, xls, txt and put them all into 1 workbook (not sheet). So all the tabs imported would be there. Right now the code can take in only 1 type. I tried changing the code below to:

fileName = Dir(directory & "*.csv, *.xls,*.txt")

but nothing happened.

The macro below has a fixed directory path right now but I would like to have a dialog box pop up which allows me to be flexible in selecting any folder I want to import my files from. Here's what I got so far, but please modify it or make a new one that best works.

Sub Input_Sheets()

Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim WrdArray() As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

directory = "C:\Users\ktam\Desktop\New folder\"

'Switch to the preferred type the folders hold. (It cannot hold 2 types)
'fileName = Dir(directory & "*.xl??")
fileName = Dir(directory & "*.csv")

'As long as the file name is found in the folder, import the file.
Do While fileName <> ""
Workbooks.Open (directory & fileName) 'Opens a random file from the folder
    'WrdArray() = Split(fileName, ".")

    For Each sheet In Workbooks(fileName).Worksheets
    'Workbooks(fileName).ActiveSheet.Name = WrdArray(0) '0 Puts in the name of the document

                total = ThisWorkbook.Worksheets.Count
                Workbooks(fileName).Worksheets(sheet.Name).Copy After:=ThisWorkbook.Worksheets(total)
    Next sheet

Workbooks(fileName).Close
fileName = Dir()
Loop

Application.ScreenUpdating = True
Application.DisplayAlerts = True

MsgBox "Complete"

End Sub

I have this code that's really useful for looping within a folder and loading the files into an array based on the file names:

Global sfolder As String

sub file_merger()

file = Dir(folderchooser)

dim trackerfiles(1 to 500) as variant

counter = 1

Do While file <> ""

    if instr(1,file,".xlsx") > 0 or instr(1,file,".csv") > 0 then   


    trackerfiles(counter) = sfolder & "\" & file
    file = Dir()
    counter = counter + 1

    If file = "" Then
        Exit Do
    End If

    End if

Loop


end sub

Function folderchooser() As String

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Select a folder"
    .AllowMultiSelect = False
    .Show
    sfolder = .SelectedItems(1)
End With

folderchooser = sfolder & "\"

End Function

You could use it load into an array and then write your own code to import the files into your workbook (the tricky part is looping through the folder).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM