File name list in excel


  • — By
    Sumit Bansal

On my first day in my job in a small consulting firm, I was staffed on a short project for three days.

The work was simple.

There were many folders on the network drive and each folder had hundreds of files in it.

I had to follow these three steps:

  1. Select the file and copy its name.
  2. Paste that name in a cell in Excel and hit Enter.
  3. Move to the next file and repeat step 1 & 2.

Sounds simple right?

It was – Simple and a huge waste of time.

What took me three days could have been done in a few minutes if I knew the right techniques.

In this tutorial, I will show you different ways to make this entire process super fast and super easy (with and without VBA).

Limitations of the methods shown in this tutorial: With the techniques shown below, you will only be able to get the names of the files within the main folder. You will not get the names of the files in the sub-folders within the main folder. Here is a way to get names of files from folders and sub-folders using Power Query

Using FILES Function to Get a List of File Names from a Folder

Heard of FILES function before?

Don’t worry if you haven’t.

It is from the childhood days of Excel spreadsheets (a version 4 formula).

While this formula does not work in the worksheet cells, it still works in named ranges. We will use this fact to get the list of file names from a specified folder.

Now, suppose you have a folder with the name – ‘Test Folder‘ on the desktop, and you want to get a list of file names for all the files in this folder.

Here are the steps that will give you the file names from this folder:

  1. In cell A1, enter the folder complete address followed by an asterisk sign (*)
    • For example, if your folder in the C drive, then the address would look like
      C:UsersSumitDesktopTest Folder*Folder address in a cell
    • If you are not sure how to get the folder address, use the following method:
        • In the folder from which you want to get the file names, either create a new Excel Workbook or open an existing workbook in the folder and use the below formula in any cell. This formula will give you the folder address and adds an asterisks sign (*) at the end. Now you can copy-paste (paste as value) this address in any cell (A1 in this example) in the workbook in which you want the file names.
          =REPLACE(CELL("filename"),FIND("[",CELL("filename")),LEN(CELL("filename")),"*")

          [If you have created a new workbook in the folder to use the above formula and get the folder address, you may want to delete it so that it doesn’t feature in the list of files in that folder]

  2. Go to the ‘Formulas’ tab and click on the ‘Define Name’ option.File Names from a Folder in Excel - Define Name
  3. In the New Name dialogue box, use the following details
    • Name: FileNameList (feel free to choose whatever name you like)
    • Scope: Workbook
    • Refers to: =FILES(Sheet1!$A$1)File Names from a Folder in Excel - Define Name Refres to
  4. Now to get the list of files, we will use the named range within an INDEX function. Go to cell A3 (or any cell where you want the list of names to start) and enter the following formula:
    =IFERROR(INDEX(FileNameList,ROW()-2),"")
  5. Drag this down and it will give you a list of all the file names in the folder

Getting the File Names from a folder using the FILES function Excel

Want to Extract Files with a Specific Extension??

If you want to get all the files with a particular extension, just change the asterisk with that file extension. For example, if you want only excel files, you can use *xls* instead of *

So the folder address that you need to use would be C:UsersSumitDesktopTest Folder*xls*

Similarly, for word document files, use *doc*

How does this work?

FILES formula retrieves the names of all the files of the specified extension in the specified folder.

In the INDEX formula, we have given the file names as the array and we return the 1st, 2nd, 3rd file names and so on using the ROW function.

Note that I have used ROW()-2, as we started from the third row onwards. So ROW()-2 would be 1 for the first instance, 2 for the second instance when the row number is 4, and so on and so forth.

Watch Video – Get List of File Names from a Folder in Excel

Using VBA Get a List of All the File Names from a Folder

Now, I must say that the above method is a bit complex (with a number of steps).

It’s, however, a lot better than doing this manually.

But if you’re comfortable with using VBA (or if you’re good at following exact steps that I am going to list below), you can create a custom function (UDF) that can easily get you the names of all the files.

The benefit of using a User Defined Function (UDF) is that you can save the function in a personal macro workbook and reuse it easily without repeating the steps again and again. You can also create an add-in and share this function with others.

Now let me first give you the VBA code that will create a function to get the list of all the file names from a folder in Excel.

Function GetFileNames(ByVal FolderPath As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim MyFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = MyFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
For Each MyFile In MyFiles
Result(i) = MyFile.Name
i = i + 1
Next MyFile
GetFileNames = Result
End Function

The above code will create a function GetFileNames that can be used in the worksheets (just like regular functions).

Where to put this code?

Follow the steps below to copy this code in the VB Editor.

How to Use this Function?

Below are the steps to use this function in a worksheet:

  • In any cell, enter the folder address of the folder from which you want to list the file names.
  • In the cell where you want the list, enter the following formula (I am entering it in cell A3):
    =IFERROR(INDEX(GetFileNames($A$1),ROW()-2),"")
  • Copy and paste the formula in the cells below to get a list of all the files.

Get List of File Names from Folder using VBA function

Note that I entered the folder location in a cell and then used that cell in the GetFileNames formula. You can also hard code the folder address in the formula as shown below:

=IFERROR(INDEX(GetFileNames("C:UsersSumitDesktopTest Folder"),ROW()-2),"")

In the above formula, we have used ROW()-2 and we started from the third row onwards. This made sure that as I copy the formula in the cells below, it will get incremented by 1. In case you’re entering the formula in the first row of a column, you can simply use ROW().

How does this formula work?

The GetFileNames formula returns an array that holds the names of all the files in the folder.

The INDEX function is used to list one file name per cell, starting from the first one.

IFERROR function is used to return blank instead of the #REF! error which is shown when a formula is copied in a cell but there are no more file names to list.

Using VBA Get a List of All the File Names with a Specific Extension

The above formula works great when you want to get a list of all the file names from a folder in Excel.

But what if you want to get the names of only the video files, or only the Excel files, or only the file names that contain a specific keyword.

In that case, you can use a slightly different function.

Below is the code that will allow you get all the file names with a specific keyword in it (or of a specific extension).

Function GetFileNamesbyExt(ByVal FolderPath As String, FileExt As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim MyFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = MyFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
For Each MyFile In MyFiles
If InStr(1, MyFile.Name, FileExt) <> 0 Then
Result(i) = MyFile.Name
i = i + 1
End If
Next MyFile
ReDim Preserve Result(1 To i - 1)
GetFileNamesbyExt = Result
End Function

The above code will create a function ‘GetFileNamesbyExt‘ that can be used in the worksheets (just like regular functions).

This function takes two arguments – the folder location and the extension keyword. It returns an array of file names that match the given extension. If no extension or keyword is specified, it will return all the file names in the specified folder.

Syntax: =GetFileNamesbyExt(“Folder Location”,”Extension”)

Where to put this code?

Follow the steps below to copy this code in the VB Editor.

  • Go to the Developer tab.
  • Click on the Visual Basic button. This will open the VB Editor.
  • In the VB Editor, right-click on any of the objects of the workbook you’re working in, go to Insert and click on Module. If you don’t see the Project Explorer, use the keyboard shortcut Control + R (hold the control key and press the ‘R’ key).
  • Double click on the Module object and copy and paste the above code into the module code window.

How to Use this Function?

Below are the steps to use this function in a worksheet:

  • In any cell, enter the folder address of the folder from which you want to list the file names. I have entered this in cell A1.
  • In a cell, enter the extension (or the keyword), for which you want all the file names. I have entered this in cell B1.
  • In the cell where you want the list, enter the following formula (I am entering it in cell A3):
    =IFERROR(INDEX(GetFileNamesbyExt($A$1,$B$1),ROW()-2),"")
  • Copy and paste the formula in the cells below to get a list of all the files.

Get File Names from a Folder in Excel by Extension keyword

How about you? Any Excel tricks that you use to make life easy. I would love to learn from you. Share it in the comment section!

You May Also Like the Following Excel Tutorials:

  • Filter cells with bold font format.
  • How to Combine Multiple Excel Files into One Excel Workbook.
  • Creating a Drop Down Filter to Extract Data Based on Selection.
  • Using VBA FileSystemObject (FSO) in Excel.

Excel Ebook Subscribe

Get 51 Excel Tips Ebook to skyrocket your productivity and get work done faster

121 thoughts on “Get the List of File Names from a Folder in Excel (with and without VBA)”

  1. Awesome, Thanks. really helpful….Though i guess this works only for local drive folders. Is there a way to get the sever location work? As, if there are huge amounts of data it’s not wise to copy paste on my local drive and then do this. There should be a way to get the files names from the severs connected. Could you please help me out with that?

  2. Fantastic, thanks many tonnes.

  3. 1. select file in folder
    2. hold shit and right click
    3. select “copy as path”
    4. paste in excel
    5. Use find/replace to find “folder path” and replace with ” “

  4. Amazing solutions both with/without VBA.
    It works in my PC but I would like to know why is doesn’t work if the folder is in Onedrive?
    I´m using in cell A1 =REPLACE(CELL(“filename”),FIND(“[“,CELL(“filename”)),LEN(CELL(“filename”)),”MyFolder/”)
    to obtain the folderpath that is in One drive and in B1=INDEX(GetFileNames(A1,1),””)

  5. This is awesome!! Thanks

  6. Super bro! worked out correctly for me (using the Excel formula). Many thanks for sharing your knowledge.

  7. Very well. I like the code of vba. But i think you have some issue with ReDim Result(1 To MyFiles.Count) and with the ReDim Preserve Result(1 To i – 1). Because i run the code and 1 of files i can’t see.
    I think the best to change
    ReDim Result(0 To MyFiles.Count)
    ReDim Preserve Result(0 To i – 1).
    And after this all works.
    Thanks for great job.

  8. i have more sub folder in one folder in need formula to get all folder name in excl

  9. Awesome!!! Thanks a lot, man! Got it done, what I needed to, following your video. Kudos to you!

  10. Is there a way to select file names based on their created date or last modified date? For example, I want files created in the last 24 hrs, 36 hrs, and 5 days?

  11. Hi, this is great, but I need a list of the file names without their extension.. how to do this in one step?

    • You can use below formula

      =IFERROR(LEFT(INDEX(FileNameList,ROW()-2),FIND(“.”,INDEX(FileNameList,ROW()-2))-1),””)

  12. is that any way to update excel list when one of the file in the folder delete ?

  13. if one of the file in the folder delete this program can not update that and old file name remain in the list

  14. I find it faster to stick the folder path into a browser and then copy and paste into excel.
    But yes, even better when excel is set up to extract the data with a click of the button.

  15. Great!
    Why doesn’t it work?

  16. Hi, what i like to know is….
    i have a cell A1 in sheet1, and i like to output the highest file number of a folder in that cell.
    So when the folder name = userinvoice and the file name in pdf and xlsm is for example 20190001.pdf range 20190199 and 20190001.xlsm to 20190199 i like to display the value of the highest number in that folder to cell A1 in sheet1. In this example it would be 20190199.pdf and 20190199.xlsm

    Thank you very much for you effort.

  17. Thanks very much. Saved me hours of manual entry!

  18. hi

    thankyou for the post

    I need a macro which can automate the work of renaming the pdf with amount within the pdf, instead of depending on a software

  19. I want to see Respective File Name with Save Time & Date…
    Please help for the Macro Code for the same.

  20. Thank you for this wonderful post !!!

  21. I see the method for only listing specific extensions but is there a way to exclude extensions?

  22. Thanks a lot for your tip. it’s helped me a lot.. 🙂 ..

  23. Thanks for the tip – worked like a charm!

  24. I need to get at the place to make a file name and go where I took pictures at yesterday

  25. Nice work

    it made our work very easy with our macro

    • oh

  26. Amazing ! i’m mind blown here,
    I knew of to do it with marco but with a simple formula! wonderful!

  27. DEVE

  28. hoping someone could help, hoping I could automate my excel list using VBA or other procedure,

    For A, the idea is I have a PDF file, let say rev. 1,2,3,4 etc, and I will put it in one folder, what I need is I need to capture the latest revision with hyperlink using formula.

    For B, the idea is almost same as above except for one revision, let say rev. 01 and I will put it in one folder (same folder as formula A), what I need is I need to capture the exact revision with hyperlink using formula.

    I get this this formula but i don’t know how it will work- thanks in advance.

    A) Formula for latest “rev number” column

    =IF(Bfile(“Z:3 M+ MWC3.1 M+_RSSM+ (CC_2015_3A_022)3_DrawingsUSBM+ WS4_Drawings”&MIDB($A50,11,3)&”PDF”&MIDB($A50,1,35)&”-“&LOOKUP(1,0/($K50:$DF50” “),$K50:$DF50)&”.PDF”),HYPERLINK(“Z:3 M+ MWC3.1 M+_RSSM+ (CC_2015_3A_022)3_DrawingsUSBM+ WS4_Drawings”&MIDB($A50,11,3)&”PDF”&MIDB($A50,1,35)&”-“&LOOKUP(1,0/($K50:$DF50” “),$K50:$DF50)&”.PDF”,LOOKUP(1,0/($K50:$DF50″ “),$K50:$DF50)),”*”&LOOKUP(1,0/($K50:$DF50” “),$K50:$DF50))

    B) Formula for latest “rev number individual” column

    =IF(Bfile(“Z:3 M+ MWC3.1 M+_RSSM+ (CC_2015_3A_022)3_DrawingsUSBM+ WS4_Drawings”&MIDB($A52,11,3)&”PDF”&MIDB($A52,1,35)&”-00.PDF”),HYPERLINK(“Z:3 M+ MWC3.1 M+_RSSM+ (CC_2015_3A_022)3_DrawingsUSBM+ WS4_Drawings”&MIDB($A52,11,3)&”PDF”&MIDB($A52,1,35)&”-00.PDF”,”00″),”*00″)

  29. I only tried the first method and it works perfectly for me… thank you so much for saving me days of boring inputing!!

  30. How to get the file name list in Date Modified order in this excel workbook ??

  31. Umm its not working on MAC 🙁
    The formula you’ve provided (in column A) gives me this:
    /Volumes/Data/Reports/*

    So the INDEX formula (in column B) gives #N/A
    🙁

    • Remove the first “/” (the one before Volumes) and change the rest of the slashes to colons.

  32. I used the code above to obtain a list of files. The files names are as below:
    Diesel___1234567___NIR_cuvette___20180912_234811.0
    Diesel___1234567___NIR_cuvette___20180912_235510.0
    The code only pulls the first file for each sample and fails to list the second (or third file). Is there a way to correct for this? Thanks.

  33. Hey,
    I have a ecxel sheet which have some product names, and also have a folder which have some pdf files named same as in cell data, like if cell A2 value is apple1, Pdf file name is apple1.pdf, i want to know which name file is missing, can we get that in excel somwhow..

  34. Hi Sumit,

    I want to list the names and duration of all videos in a folder and its subfolders using Excel VBA. From the code below I can get the duration of video files, but I can’t exclude all other files. This gives me a list of all the file names, which I don’t need. Also I am failing to loop through subfolders.
    What I want to achieve is for the macro to loop through all subfolders in the the given root folder and list only video names and duration in columns A and B.
    Some help with this is truly appreciated.
    Option Explicit

    Dim i As Long, SourceFldr
    Dim c As Range, rng As Range
    Dim sFile As Variant
    Dim oWSHShell As Object
    Dim WS As Worksheet
    Dim lRow As Long

    Sub GetDuration()

    Dim fldr As FileDialog
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    Set oWSHShell = CreateObject(“WScript.Shell”)

    With fldr
    .Title = “Select a Source Folder”
    .AllowMultiSelect = False
    .InitialFileName = oWSHShell.SpecialFolders(“Desktop”)
    If .Show -1 Then GoTo NextCode
    SourceFldr = .SelectedItems(1)
    NextCode:
    End With

    Dim oShell: Set oShell = CreateObject(“Shell.Application”)
    Dim oDir: Set oDir = oShell.Namespace(SourceFldr)

    i = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row + 1

    For Each sFile In oDir.Items
    Cells(i, 1).Value = oDir.GetDetailsOf(sFile, 0) ‘File Name
    Cells(i, 2).Value = oDir.GetDetailsOf(sFile, 27) ‘File Lenght
    i = i + 1
    Next sFile

    Set oDir = Nothing
    Set oShell = Nothing

    End Sub

  35. Wow! That’s ingenious and too much for free 😀 May Allah bless you brother. Thanks a lot.

  36. Hey! Sumit Bansal right? As a matter of fact you are my excel HERO. I’ve been following your blog for quite a while now and everything you thought was amazing. Even though I’m still a student, I know one day this knowledge is going to save me a lot of time. I thought I was an excel expert with my one semester training So I created a blog to publish my skills on (http://excel-programming.com). But upon discovering your skills and experience I think I still have a a long way to go. Thank you very much for this blog.

  37. You are doing wonderful work Sumit to educate Excel users. God bless you.
    Please try the Excel Addin called ASAP Utilities by downloading it. There is a free (Home&Student) and paid version. File listing in Excel sheet of any directory and nested sub directories, with many properties of the files is so easy with many menu driven options (Menu-File & System-Item 24) This is just one of more than 300 utilities. It will be very useful for all Excel users and saves tons of time and effort. Current version is 7.4 and the link to the site is http://www.asap-utilities.com/ . I do not have any pesronel intrest in the product except to make it known to many Excel users to benifit in their work. It was developed by Bastien Mensink from Netherlands way back in 1999. I am using it since that time. Feed back on your experience is appreciated.

  38. Sumit this one deserves a kudos!!

    Some time back i was working on its VBA and m non VBA guy……….

  39. I was also wondering if there is a way to extract additional properties information at the same time
    ie
    “File Name”
    “Created”
    “Owner”
    “Author”
    “Title”
    “Comments”
    “Tags”

    • This would be fabulous.

  40. nice. really interesting. thanks a lot

  41. Hmm, nowadays I would go with a Power Query ( Get and Transform) solution. Read from folder, and delete all columns except file name. Save and load to table. No macro, no formula involved.

  42. Thank you for this repost. Is there a way to list folders in a directory?

    • I just saw a post below that this function does not work with folders. Too bad 🙁

  43. Since it has not been corrected I assume that it has not been reported yet. The first version of this formula: =IFERROR(INDEX(FileNameList,ROW()-2,””) should actually be: =IFERROR(INDEX(FileNameList,ROW()-2),””). The trick won’t work until the right formula is used.

    • Thanks for pointing out Charles.. have corrected it!

  44. Hi Sumit, Great trick. Thanks a lot. However I was wondering if there is a way to extract the file path as well along with the file name

  45. I copied everything exactly but my cells are blank in the B column and it doesn’t populate the file names. any reason why? Also I’m using office 2010.

    • I figured out the issue, i didn’t have a slash before the asterisk * at the end. But I have one more question. Can this be used to get a value from a cell in these docs as well? e.g. I get a list of all docs in a given folder, can I then get a value from a cell in each of those docs if its all the same cell in each doc?

  46. Hi
    Was wondering if there is a way to extract properties information at the same time
    ie
    “File Name”
    “Created”
    “Owner”
    “Author”
    “Title”
    “Comments”
    “Tags”

    Much appreciated

  47. Hi Sumit, great tutorial. I used this because files are constantly being added to a specific folder. This allows for the names of those new folders to show. Since I do not know the names of the new files that will be created I was hoping to then use the results of this in an external reference formula. Do you know if this is possible?

  48. One method I have used before uses the command prompt. Navigate to the folder you want to extract file names from. Type (dir /b > “sample.txt”) minus the parenthesis. This will create a text file in the same directory that you can then open in Excel for further processing.

  49. how to have excel list all the file in one row instead of using multiple rows

  50. dear sir,
    how can i Get a List of File Names from a Folder in Excel without extension like . jpg, .pdf

  51. Amazing! Thanks for this Great Trick!!!

    Question: When the New File Names come in, they Start Over from the Top-Shifting File Names Down, how can I get them to come in at the bottom of the list (based on date/time modified)?

    Make File Name Hyperlink? If I Select the Column with your Formula, Insert Hyperlink and Add Folder Location, this links them to the folder, but how can I make it open the file directly? Also If you can Help: I have a Folder Filled with Email Messages (.msg Files) that I am keeping a Running List of in Excel and have to manually enter data from each Email such as Name (Email Address before @) + Company (Email Address after @), Date Received etc. – Is there a way to Auto Populate this information into Excel from the .msg File following the Automated File Name you have created here?

  52. I have a single folder with multiple sub-folders each with multiple files, can I extract at the highest folder level?

  53. Hi, Is there a way i can get the time the file is created in addition to the file name?

  54. Hei Sumit. I got Folder name in A1. But INDEX will not work properly, I get only #N/A, (I define A1 as “NM”)
    Can you plz look at screenshot and give me some guide lines that where i do wrong?
    And my required folder is on Sharepoint.

  55. Amazingly quick response. I will re-check. Thank you.

  56. I tried Getting a List of File Names from a Folder in Excel. Why did I get #NAME? instead of the name of the first file? I like your video lesson. Thank you.
    Husen Kabeer, myaquadome@yahoo.com

    c:This PCDocumentsHusen Data Files – 2014Word*
    =INDEX(FileNameList,1)
    #NAME?

    • Hello Husen.. Check the named range reference. It seems your named range is not referring to the cell that has the folder path.

  57. Thank you very much. This is amazing ..:)

    • Thanks for commenting.. Glad you liked it 🙂

  58. Sumit, is there a way for this formula to look within a series of sub-folders for the same results.

    • Thanks for commenting David.. With this method, you can only get file names from a specified folder

  59. Hi, Sumit
    Googled for a few minutes just now. I love your work. As a newbie you’ve helped me so much but for the life of me I just couldn’t get this working. Found an alternative method that actually lists the file names as hyperlinks. Thought I’d share the link here, in case you or your other fans/followers were interested –

    http://www.extendoffice.com/documents/excel/627-excel-list-files.html

  60. if this done with a folder that gets updated a lot, will this auto update with the new file names or will you have to start all over

    • It would automatically update if you open the workbook or you press F9 (to force a calculation), or even if you make any change in the worksheet.

      • Thanks, its working just the way that i was wanting it to

      • Hello Sumit, thank you for your post. Made my life easier. Never the less I still have a problem with the update. It does not update automatically. I have to drag the formula again each time I open the document, or either double click the cell to updated itself. Do you know what I might do wrong? For your information I used your formula in combination with other formulas as bellow :

        =LEFT($B$3;LEN($B$3)-1)&IFERROR(INDEX(FileList0916;ROWS($B$4:B33));””)

  61. Hi. I have been here for more than an hour and for some reason I can’t get this to work. Know I’m going to love it and use it a lot, once I can get the first one working. Any chance you can take a look at mine and tell me what I’m doing wrong? I would so much appreciate it!

    https://www.dropbox.com/s/ex6rtxpgr2twyne/Excel%20Index.xlsx?dl=0

    • Hello Brenda. You have created a named range with the name “ExcelList”, while the formula uses “FileNameList”. Change the formula to =IFERROR(INDEX(ExcelList,ROWS($B$1:B1)),””)

        • Are you using the formula to get the folder address. Use this formula =REPLACE(CELL(“filename”),FIND(“[“,CELL(“filename”)),LEN(CELL(“filename”)),”*”)

          It shouldn’t look something as shown in your spreadsheet. Also, make sure the excel file (in which you are extracting the file names) is saved in the same folder.

          • Morning,
            At it again this am. Losing my mind. Want this so bad and I just can’t get it to work. Tried everything. Must be something really small and stupid hanging me up. Heading to work. Little bit OCD – lol. I will get back at it when I get home but not too optimistic.

  62. hi sumit! i followed the instructions but all i got was a blank cell..

  63. Hi
    The function of FILES does not exist in my version of excel 2010! May be it originated from some Add-Ins?

  64. That is an awesome way. Thanks a lot!!…
    Also, is there a way to get the list of all the folders,subfolders and filenames along with file size and modification date columns.

    • Thanks for commenting.. Using this method, you can only get file names from a specified folder

  65. Another way to get the directory.
    Portuguese version of formula =INFORMAÇÃO(“DIRECTÓRIO”)
    I guess in English will be =INFO(“DIRECTORY”)
    Even easier!

  66. Hi Sumit, thanks a lot for that.. is there any way I can also get the tabs within each excel file that I am looking up in a drive to populate in the columns next to file names? Please let me know it will be really helpful

    • Hi Bharat. You won’t be able to get tab names using the FILES function. For that, you would need to resort to a VBA code

      • HI Sumit, thanks for the quick response. is there anyway you can help with that code? I have been trying to search for it online but nothing seems to pop up.

  67. Never seen this trick before. Great stuff.

    i think this formula should also work for retrieving the file path, looks shorter 🙂
    =LEFT(CELL(“filename”),FIND(“[“,CELL(“filename”))-1)&”*”

    • Thanks for sharing the formula Victor.. Yours is much better 🙂

  68. I was able to follow your instructions, but when i save it and go back it isnt there it just has name#. I am not familiar with Macros and it ask me to save Macros-Free and when I do my list isnt there. how can I save it. apologize in advance.

    • Hi Elisa.. Thanks for commenting. Try and save your file as a macro-enabled workbook (with .xlsm extension) and it would work. Since FILES is an old macro formula, it requires the workbook to be saved in .XLSM format. And don’t worry about not knowing macros, it would still work

  69. Awesome solution thank you! However I could only register 256 files (rows). After that I get #¡REF!. Do you know a way to make it work for larger number of files. I need it for 2.000 files aprox. Thank you again. Jacobo

    • Thanks for commenting.. Could you share the sample file you are using. Since FILES is an old formula it may have some limitations, need to check on it.

  70. Once I wanted to do the same so I wrote an Excel Add-in for doing that.

    It can get filenames, folders, file extensions and other information regarding files.

    This tool can write up to excel limit number of rows in just a few minutes.

    In a stress test I did, I got more than 1,000,000 file names in just about 3 minutes.

    Here is a link to try:

    http://excel.gegprifti.com

  71. Dear Sumit,
    Suppose i want to do same for folder name than how we can do?

    • Hi, I am waiting for your revert.

      • Hi Narayandatta.. FILES can not be used to get the folder names within in folder. It only works for files that have an extension

  72. This was a great time saver Sumit, thanks. ? is there a way to make them a hyperlink without going through every single one?
    Thanks

  73. fantastic

    • A formula that only works in named range?!!..this is great find.

  74. That is really useful, thanks very much!

    • Thanks for commenting.. Glad you found this useful 🙂

  75. Interesting.

    Before dragging down, we may use

    =COUNTA(FileNameList)

    to get a sense of how far we need to go down.

    btw, another approach in getting the directory for consideration.

    =REPLACE(CELL(“filename”),FIND(“[“,CELL(“filename”)),LEN(CELL(“filename”)),”*”)

    • Thanks for commenting.. Your formula is much better 🙂

  76. Thanks this will be useful
    We can also do the same thing with Power Query

  77. Wow, this is great. Easier than the VBA code I wrote to do the same thing!

    • Yeah.. this old macro4 formula does makes it quite easy to do this

  78. you save my life.

    thnx a lot for such a great trick.

    • Thanks for the comment. Glad you liked it 🙂

      • Dear Sumit,

        Is “Files” function is valid only Excel 2013.

        I am trying to make it in Excel 2010 but could not find the Turkish of “Files” in Excel?

        Do you have an idea?

      • Dear Sumit,

        I am dying here to try above trick but still waiting your reply about the function FILES ?
        🙁

        • Hey.. this formula is valid for all versions of Excel. However, I could not find its equivalent for Turkish Excel. Since it’s an old function, even the help is not available for it now.

          • Dear Sumit,

            Thnx for your reply.

            I made it but unfortunately when I drag down, it gives only the first file name ?

            Do you have any idea?

          • It seems the second argument of INDEX is not changing. Can you try changing it to see if it work. Also, would be great if you could share the file (a link to dropbox or onedrive)

          • I think I got the issue.. Replace the function ROW with ROWS, and it should work for you. Hope this helps.

          • omg!
            how dumb! I am…
            Thnx a lot and sorry for wasting your time!

          • Glad it worked 🙂

          • I need those macros in Polish, and find this way:

            In VBA I write and run simple macro like:

            Sub Makro1()
            ActiveWorkbook.Names.Add Name:=”Test”, RefersToR1C1:=”=FILES(Sheet1!R2C1)”
            End Sub

            Then in Name Menager I have 4.0 Macro Function name in my Excel language (for my it’s Polish)

Comments are closed.

As we work with Excel, we may need to extract the file names of files in local or network folders for, for example, documentation.

We can do this the old-fashioned way of copying and pasting, but it is tedious, inconvenient, and time-consuming, especially when processing many files.

This tutorial shows three time-saving techniques for getting file names from a folder or subfolders in Excel.

How to Get Names of Files Within the Main Folder

The methods in this section are limited to getting the filenames of files in the main folder.

The following section will present using the Get & Transform feature to extract the names of files in the main folder and subfolders. 

Using the FILES Function

We can use the FILES function to return a list of names of files in a folder.

One important thing to know about the FILES function is that it only works in named cell ranges but not Excel cells.

Consider the “Excel Tutorials” folder on my local C drive.

a folder from which I want to get the list of all the file names in Excel

Notice that the folder has 23 items, 22 files with various extensions, and one subfolder called “Excel Tutorials 2.”

We want to use the FILES function to extract the names of the 22 files in the main folder in an Excel file.

We use the following steps:

  1. Select cell A1 and enter the full path of the “Excel Tutorials” main folder followed by an asterisk (*) symbol.
enter the folder path in a cell in Excel

Note: If you do not know the full path of the main folder, you can get it using the below steps:

  • Open any of the existing workbooks in the main folder (for which you want to get the folder path) or create and save a new Excel file in the same folder and then open it.
  • Select any cell in the workbook and enter the formula below:
=REPLACE(CELL("filename"),FIND("[",CELL("filename")),LEN(CELL("filename")),"*")

Notice that this formula returns the full path of the main folder followed by an asterisk (*) symbol.

  • Press Ctrl + C to copy the cell contents, and press Ctrl + Alt + V to paste it as values in cell A1 or any other cell of the worksheet in which you want to get the file names. 
  • If you create a new file to get the main folder’s path, delete it so that it is not included in the names of the files to be extracted.
  1. On the Formulas tab, on the Defined Names group, click the Define Name button.
click on the define name option in the ribbon in Excel
  1. Do the following on the New Name dialog box that appears:
  • On the Name box, enter List_File_Names or any other name you choose. Remember not to put any spaces in the name (as named ranges are not allowed to have spaces in between).
  • Open the Scope drop-down and select Workbook.
  • Enter the formula =FILES(Sheet1!$A$1) on the ‘Refers to’ field. If you chose a different cell for the folder’s path, update the formula accordingly (so change $A$1 with the cell reference that you are using). 
  • Click OK.
create a define name using the files function in Excel
  1. Select cell A4, where we want the list to start, and enter the following formula:
=IFERROR(INDEX(List_File_Names,ROW()-3),"")
enter the formula in a cell where you want to start getting the list of file names from a folder in Excel

Note: Update the formula if you start the list in a different cell. For example, if you start the list in cell A5, subtract the value four from the ROW function inside the INDEX function.

  1. Drag the Fill Handle feature to copy the formula down the column and get the list of the filenames of the files in the main folder. 
drag the formula down to get all the file names from the folder in Excel as a list

Note: FILES is a Macro-4 function, and you need to save your workbook as a Macro-Enabled Workbook (*.xlsm) to avoid losing the list when you save the file. Excel informs you accordingly when you attempt to save the workbook as a regular .xlsx file:

Alternatively, you can copy the list and paste it as values to avoid the need to save the file as a macro-enabled workbook.

How to Get Files Names With a Particular Extension

If you want to extract the filenames of the files with a specific extension, replace the asterisk (*) symbol with that particular file extension. 

For example, if you want to get only the files names of macro-enabled workbooks, you must replace the asterisk with *xlsm extension as in the example below:

specify the extension of which you want to get all the file names

When you use an asterisk symbol (*) at the end of the folder path address, it tells the FILES function to fetch all the files irrespective of the file extension. But when you use *xlsm, it forces the FILES function to only give us the list of those file names that end with xlsm

Explanation of the FILES function technique

The FILES formula, =FILES(Sheet1!$A$1), extracts the filenames of the files in the main folder. 

In the =IFERROR(INDEX(List_File_Names,ROW()-3),””) formula, the names returned by the FILES function are fed to the IINDEX function as an array, and then the ROW function returns the first file name, second file name, third file name, and so on. 

Notice that we used ROW()-3 because we started the list in the fourth row. So ROW()-3, equivalent to 4-3 when the row number is 4, returns the first file name. Next, ROW()-3 equals 2 (i.e., 5-3) when the row number is 5, returns the second file name, and so on.

Lastly, the IFERROR function wrapping the formula suppresses the #REF! Error and returns an empty string after the formula returns the last file name.

Notice that this technique did not return the files names of the files in the “Excel Tutorials 2” subfolder. 

Also read: Extract Last Name in Excel

Using a User-Defined Function (Created using VBA)

We can create a User Defined Function using Excel VBA to return the names of files in a folder.

The advantage of this method over Method #1 is that the function can be saved in a personal macro workbook and reused without repeating the steps.

We use the below steps to create the User Defined Function:

  1. Press Alt + F11 to launch the Visual Basic Editor.
  2. In the Visual Basic Editor, select any object of the workbook you are working on, click Insert on the menu bar, and choose Module.
click on the module option to insert a new module

A new module is added to the project in the Project window. 

a new module has been inserted for the workbook

Note: If you do not see the Project window, activate it by pressing Ctrl + R or choosing Project Explorer on the View menu.

click on the project explorer option if you do not see the project explorer in the VB editor
  1. Double-click the new module to open its code window on the right.
  2. Copy and paste the following function procedure into the module’s code window.
'Code developed by Steve Scott from https://spreadsheetplanet.com
Function EXTRACTFILENAMES(ByVal FolderPath As String) As Variant
Dim i As Integer
Dim files As Variant
Dim fileObj As Object
Dim folderObj As Object
Dim fileColl As Object
Dim fsoObj As Object
Set fsoObj = CreateObject("Scripting.FileSystemObject")
Set folderObj = fsoObj.GetFolder(FolderPath)
Set fileColl = folderObj.files
ReDim files(1 To fileColl.Count)
i = 1
For Each fileObj In fileColl
files(i) = fileObj.Name
i = i + 1
Next fileObj
EXTRACTFILENAMES = files
End Function
  1. Save the procedure and the workbook as a Macro-Enabled Workbook (*.xlsm).

How to Use the User-Defined Function in the Workbook

Use the following steps to put the function into action:

  • Select any cell and enter the full path of the folder from which we want to extract the file names. In this case, we enter the full path in cell A1:
enter the folder path in a sale in Excel
  • In the cell from which you want to start the list of file names (in this case, it is A4), enter the following formula (update the formula according to the cell from which you want to start the list):
=IFERROR(INDEX(EXTRACTFILENAMES($A$1),ROW()-3),"")
enter the formula in a cell where you want to start getting the list of file names
  • Drag the Fill Handle feature to copy the formula down the column, and you will get the list of the filenames of the files in the “Excel Tutorials” folder.
drag the formula down to get all the file names

Note: In case you do not want to enter the path of the folder in a cell, you can hard-code the path into the formula as shown below:

=IFERROR(INDEX(EXTRACTFILENAMES("C:Excel Tutorials"),ROW()-3),"")

If you want to start the list in row 1, you can modify the formula as below:

=IFERROR(INDEX(EXTRACTFILENAMES("C:Excel Tutorials"),ROW()),"")

Explanation of the Formula

=IFERROR(INDEX(EXTRACTFILENAMES($A$1),ROW()-3),””)

In INDEX(EXTRACTFILENAMES($A$1),ROW()-3) part of the formula, the EXTRACTFILENAMES function returns an array of all the file names of the files in the main folder.

The array of file names is then fed into the INDEX function, and the ROW function returns the first file name, second file name, third file name, and so on.

We used ROW()-3 in the formula because we started the list in the fourth row. So ROW()-3, equivalent to 4-3 when the row number is 4,  returns the first file name.

Next, ROW()-3 equals 5-3 when the row number is 5, returns the second file name, and so on.

Finally, the IFERROR function enclosing the formula suppresses the #REF! errors and returns empty strings after the formula returns the last file name.

Notice that this technique did not return the names of the files in the “Excel Tutorials 2” subfolder. 

Using User-Defined Function to Get List of File Names With a Specific Extension 

Sometimes we may want a list of names of only those files with a specific extension, for example, .docx.

We can create a User-Defined Function that we can use to return only those file names with a particular extension.

We use the below steps to create the User Defined Function:

  1. Press Alt + F11 to launch the Visual Basic Editor.
  2. In the Visual Basic Editor, select any object of the workbook you are working on, click Insert on the menu bar, and choose Module.
insert a new module

A new module is added to the project in the Project window. 

a new module has been created

Note: If the Project window is not open, activate it by pressing Ctrl + R or choosing Project Explorer on the View menu.

  1. Double-click the new module to open its code window on the right.
  2. Copy and paste the following function procedure into the module’s code window.
'Code developed by Steve Scott from https://spreadsheetplanet.com
Function EXTRACTFILENAMESBYEXT(ByVal FolderPath As String, FileExtension As String) As Variant
Dim i As Integer
Dim files As Variant
Dim fileObj As Object
Dim fsoObj As Object
Dim fileColl As Object
Dim folderObj As Object
Set fsoObj = CreateObject("Scripting.FileSystemObject")
Set folderObj = fsoObj.GetFolder(FolderPath)
Set fileColl = folderObj.files
ReDim files(1 To fileColl.Count)
i = 1
For Each fileObj In fileColl
If InStr(1, fileObj.Name, FileExtension) <> 0 Then
files(i) = fileObj.Name
i = i + 1
End If
Next fileObj
ReDim Preserve files(1 To i - 1)
EXTRACTFILENAMESBYEXT = files
End Function
  1. Save the function procedure and the workbook as a Macro-Enabled Workbook (*.xlsm).

How to Use the Above User-Defined Function to Get File Names from a Folder

  • Select any cell in a worksheet and enter the full path of the folder containing the files whose names you want to extract. In this case, I have entered the folder’s full path in cell A1. 
enter the folder path in a cell from which you want to get the list of file names in Excel
  • Enter the extension of the file names you want to extract in another cell. You can also enter a relevant search term. In this case, I have entered the png file extension in cell B1 because I want to extract the file names of images.
enter the file extension in other cell
  • Enter the following formula in a cell where you want the list to start. In this case, I have entered the formula in cell A4:
=IFERROR(INDEX(EXTRACTFILENAMESBYEXT($A$1,$B$1),ROW()-3),"")
use the formula that takes the folder path as well as the file extension as inputs
  • Drag the Fill Handle to copy the formula down the column and get all the names of the image files in the main folder.
copy down the formula to get all the files with the specified extension as a list in Excel

In this example, since I entered the function in cell A4 (which is row number 4), I used ROW()-3, as I wanted to start the numbering from 1 (where the ROW function would give 4 as the function is in cell A4). If you use it in any other cell, you need to adjust this part accordingly.

In case you want to fetch all the files in the folder, leave the extension argument blank (which is cell B1 in our example).

Also read: Remove Middle Name from Full Name in Excel

How to Get Names of Files Within the Main Folder and the Subfolders

The methods we covered in the previous section of this tutorial can only extract the names of files in the main folder.

But what if you want to extract all the names in the main folder as well as all the file names in all the subfolders as well.

This can easily be done using the Get & Transform feature (known as the Power Query feature).

Using the Get & Transform Feature (Power Query) 

Get & Transform is a feature in Excel that enables us to extract, transform, and load data from various sources.

For example, we can use this feature to extract the names of all the files in a folder and its subfolders.

Let’s look at the following “Excel Tutorials” folder on my local C drive:

folder from which I want to get the list of all the final names in Excel

The folder has 22 files and one subfolder called “Excel Tutorials 2.” Let me open the subfolder we see what it contains:

the subfolder also has six files that I want to get as a list in Excel

The subfolder contains six files with various extensions.

We want to use the Get & Transform feature to extract the names of the 22 files in the main folder plus the names of the six files in the subfolder. 

We use the following steps:

  1. On the Data tab, on the Get & Transform Data group, open the Get Data drop-down, select From File, and choose From Folder on the sub-menu.
click on the from folder option in the get data dropdown
  1. Use the Browse feature to locate the “Excel Tutorials” folder, select the folder and click Open.
locate and open the folder from which you want to get the list of file names

On the dialog box that appears, we can see the list of names of files in the main folder and subfolder alongside other metadata.

all the file names now appear in power query
  1. Click the Transform Data button at the bottom of the dialog box.
click on the transform data button
  1. In the Power Query Editor, right-click any column that you don’t want to appear in the final list of file names and choose the Remove option on the shortcut menu. In the following example, I want to remove the Content column:
remove any columns that you do not want in the Excel

In the example below, I have removed all columns except the Name column:

all columns have been removed except the name column that shows the list of all the file names that we want in Excel
  1. Click the Close & Load button.
click on the close and load option in the power query Editor ribbon

The names of the 22 files in the main folder, plus the names of the six files in the subfolder, have been loaded onto a worksheet:

all the file names from the folders are now listed in Excel in a column

This tutorial showed three Excel techniques for extracting the names of files in folders. We hope you found the tutorial helpful.

Other Excel articles you may also like:

  • How to Open an MPP file in Excel?
  • How to Open XML Files in Excel?
  • How to Open DAT Files in Excel?
  • How to Get Sheet Names in Excel?
  • How to Select Multiple Items from a Drop Down in Excel?
  • How to Insert an Excel file into MS Word?

This post will teach you how to get the list of file names in a given directory to a worksheet in Excel. You will learn that how to use Excel to view Files and Folders in your worksheet by get the list of file names with different ways, such as: Excel VBA Macro, or FILES function.

If you want to get the list of file names from a folder that contain hundreds of files in it. You may be think the simplest way is that selecting the file and copying its name, then paste the file name in a cell in your worksheet, then repeat the above steps. If you follow this way to do it, you will take a long time to complete it. So it is a simple way, but it is also a huge waste of time. Do we have some quick way to achieve the same result? Of course yes, the below will talk two ways to copy the list of file names from a folder into worksheet quickly.

Table of Contents

  • Method 1: Using FILES function to get list of file names
  • Method 2: Using File browser and web browser to get list of file names
  • Method 3: Using Excel VBA macro to get list of file names
    • Related Functions

Method 1: Using FILES function to get list of file names

You can use the FILES function to get the list of file names from a directory, and this function is only works in name Defined Names. And then you can use a combination of the IFERROR function, the INDEX function and the Row function to create an excel formula. Let’s see the below steps:

1# Assuming that you want to get the list of file names from a directory, such as: C:UsersdevopsTracingWPPMedia*, and enter this directory path into Cell B1.

get list of file names from a folder1

2# On the FORMULAS Tab, click Define Name command under Defined Names group, then select Define Names… from the drop-down menu list.

get list of file names from a folder2

3# the New Name window will appear. Set a name in the Name box, such as: FileNameList, type the following formula in the Refers to box.

=FILES(Sheet7!$B$1)

get list of file names from a folder3

4# enter the following formula in the Cell B3, then drag the AutoFill Handle down to others cells to apply this formula.

=IFERROR(INDEX(FileNameList,ROW()-2)," ")

get list of file names from a folder4

You will see that all file names from the specified folder are listed in your worksheet.

Method 2: Using File browser and web browser to get list of file names

If you want to use this method to get the list of file name from a directory, you need to install one web browser, such as: Firefox, Chrome or IE. Then do it follow steps:

1# Move to the destination folder or directory on the Windows File Explorer, then copy the path of that directory. Such as: C:UsersdevopsTracingWPPMedia

get list of file names from a folder5

2# open any web browser installed in your computer and paste the copied path in the address bar, then press Enter key.

3# you will see that it will add prefix file:/// at the beginning of the path in the address bar. And the file name list will be shown in the web page.

get list of file names from a folder6

4# press Ctrl + A shortcut to select all of file names in the web page and then press Ctrl +C to copy the selected content.

5# open your worksheet, then press Ctrl + V to paste all file names into your worksheet.

get list of file names from a folder7

Or you can save the web page in the Step 3 as the offline copy. Just press Ctrl + S or right-click on the web page, and then select Save Page As to save that web page.

Open the saved web page from the web browser, and copy its web address. Then click From WEB command under Get External Data group on the DATA tab in your worksheet.

get list of file names from a folder8

Paste the web address in Address box, then click Go button. Then click Import button. You will see that all files and folders details are imported to your worksheet.

Method 3: Using Excel VBA macro to get list of file names

You can write an excel VBA macro code to get the list of file names from a specified directory,

1# click on “Visual Basic” command under DEVELOPER Tab.

Get the position of the nth using excel vba1

2# then the “Visual Basic Editor” window will appear.

3# click “Insert” ->”Module” to create a new module

convert column number to letter3

4# paste the below VBA code into the code window. Then clicking “Save” button.

get list of file names from a folder9

Option Explicit
Sub GetFileNames()
    Dim xRow As Long
    Dim xDirect$, xFname$, InitialFoldr$
    InitialFoldr$ = "C:"
    With Application.FileDialog(msoFileDialogFolderPicker)
        .InitialFileName = Application.DefaultFilePath & ""
        .Title = "Please select a folder to list Files from"
        .InitialFileName = InitialFoldr$
        .Show
        If .SelectedItems.Count <> 0 Then
            xDirect$ = .SelectedItems(1) & ""
            xFname$ = Dir(xDirect$, 7)
            Do While xFname$ <> ""
                ActiveCell.Offset(xRow) = xFname$
                xRow = xRow + 1
                xFname$ = Dir
            Loop
        End If
     End With
End Sub

5# back to the current worksheet, then run the above excel macro.

get list of file names from a folder10

6# select a folder that you want to get all names, then click OK button.

get list of file names from a folder11


  • Excel IFERROR function
    The Excel IFERROR function returns an alternate value you specify if a formula results in an error, or returns the result of the formula.The syntax of the IFERROR function is as below:= IFERROR (value, value_if_error)…
  • Excel INDEX function
    The Excel INDEX function returns a value from a table based on the index (row number and column number)The INDEX function is a build-in function in Microsoft Excel and it is categorized as a Lookup and Reference Function.The syntax of the INDEX function is as below:= INDEX (array, row_num,[column_num])…
  • Excel ROW function
    The Excel ROW function returns the row number of a cell reference.The ROW function is a build-in function in Microsoft Excel and it is categorized as a Lookup and Reference Function.The syntax of the ROW function is as below:= ROW ([reference])….

Tracking and managing data across multiple files can be challenging. With Power Query, you can get the file names from a specific folder and all its sub-folders. In this article, we are going to show you how to get a list of file names in Excel.

Download Workbook

We will get help from Power Query to get a list of file names. Although Excel’s Power Query feature is for gathering and querying data, we can use it to list name of files instead of data in them.

What is Power Query?

The Power Query is a data management and querying tool for Excel. It was released as an add-in for Excel 2010 and 2013. Microsoft merged it into Excel with 2016 version. If you are using Excel 2016 or newer — including Microsoft 365 — you most likely already have this feature. To learn more about Power Query, see Power Query 101.

Using Power Query to get a list of file names

  1. If you’re using Excel 2016, 2019 or Office 365, follow Data > Get Data > From File > From Folder in the Ribbon.
    If you’re using Excel 2013 or earlier, follow Power Query > From File > From Folder in the Ribbon.
    How to get a list of file names in Excel 01
  2. Enter the main folder of your files either by typing its name or using Browse. Click OK when you have the target selected.
    How to get a list of file names in Excel 02
  3. Next is a preview window. You can see a list of files in the folder you selected and its sub-folders. You can click the Load button to populate the full list in your workbook. Power Query also allows you to modify this data before inserting it in to the worksheet. Click Transform Data (or Edit in older versions) to proceed.
    How to get a list of file names in Excel 03
  4. Clicking Transform Data button opens the Power Query window with the list of names. You can,
    1. Delete unwanted columns, such as Content.
    2. Show additional information about files.
    3. Change the order of the names, such as ascending names or descending modify date.
    4. Filter by folder or file type (extension).
    5. Filter out hidden files or folders
      How to get a list of file names in Excel 04
  5. We suggest removing the Content column first and then expanding the Attributes column to organize the list.
    1. You can remove the Content column by right-clicking on it and selecting Remove.
      How to get a list of file names in Excel 05
    2. To expand the Attributes column, click on the icon at the header, de-select the items you do not need and click OK.
      How to get a list of file names in Excel 06
  6. Clicking OK will add the selected fields as columns. You can use these fields for filtering or sorting as well.
    How to get a list of file names in Excel 07
  7. Once you are satisfied with the result, click Close & Load on the upper left of the Power Query window.
    How to get a list of file names in Excel 08
  8. Excel will load the table in a new worksheet. Another advantage is that you can refresh the table or connections at any time to get the updated file names and information.
    How to get a list of file names in Excel 09

Содержание

  1. Get the List of File Names from a Folder in Excel (with and without VBA)
  2. Using FILES Function to Get a List of File Names from a Folder
  3. Using VBA Get a List of All the File Names from a Folder
  4. Using VBA Get a List of All the File Names with a Specific Extension
  5. How To Get A List Of File Names From A Folder And All Subfolders
  6. Create a From Folder Query
  7. Select the Parent Folder to Query
  8. Edit the From Folder Query
  9. Remove the Content Column
  10. Expand the Attribute Column for More Information
  11. Close and Load the Query
  12. Query Results List All Files
  13. About the Author
  14. John MacDougall
  15. Subscribe
  16. John MacDougall

Get the List of File Names from a Folder in Excel (with and without VBA)

On my first day in my job in a small consulting firm, I was staffed on a short project for three days.

The work was simple.

There were many folders on the network drive and each folder had hundreds of files in it.

I had to follow these three steps:

  1. Select the file and copy its name.
  2. Paste that name in a cell in Excel and hit Enter.
  3. Move to the next file and repeat step 1 & 2.

Sounds simple right?

It was – Simple and a huge waste of time.

What took me three days could have been done in a few minutes if I knew the right techniques.

In this tutorial, I will show you different ways to make this entire process super fast and super easy (with and without VBA).

This Tutorial Covers:

Using FILES Function to Get a List of File Names from a Folder

Heard of FILES function before?

Don’t worry if you haven’t.

It is from the childhood days of Excel spreadsheets (a version 4 formula).

While this formula does not work in the worksheet cells, it still works in named ranges. We will use this fact to get the list of file names from a specified folder.

Now, suppose you have a folder with the name – ‘Test Folder‘ on the desktop, and you want to get a list of file names for all the files in this folder.

Here are the steps that will give you the file names from this folder:

  1. In cell A1, enter the folder complete address followed by an asterisk sign (*)
    • For example, if your folder in the C drive, then the address would look like
      C:UsersSumitDesktopTest Folder*
    • If you are not sure how to get the folder address, use the following method:
        • In the folder from which you want to get the file names, either create a new Excel Workbook or open an existing workbook in the folder and use the below formula in any cell. This formula will give you the folder address and adds an asterisks sign (*) at the end. Now you can copy-paste (paste as value) this address in any cell (A1 in this example) in the workbook in which you want the file names.

Want to Extract Files with a Specific Extension??

If you want to get all the files with a particular extension, just change the asterisk with that file extension. For example, if you want only excel files, you can use *xls* instead of *

So the folder address that you need to use would be C:UsersSumitDesktopTest Folder*xls*

Similarly, for word document files, use *doc*

How does this work?

FILES formula retrieves the names of all the files of the specified extension in the specified folder.

In the INDEX formula, we have given the file names as the array and we return the 1st, 2nd, 3rd file names and so on using the ROW function.

Note that I have used ROW()-2, as we started from the third row onwards. So ROW()-2 would be 1 for the first instance, 2 for the second instance when the row number is 4, and so on and so forth.

Watch Video – Get List of File Names from a Folder in Excel

Using VBA Get a List of All the File Names from a Folder

Now, I must say that the above method is a bit complex (with a number of steps).

It’s, however, a lot better than doing this manually.

But if you’re comfortable with using VBA (or if you’re good at following exact steps that I am going to list below), you can create a custom function (UDF) that can easily get you the names of all the files.

The benefit of using a User Defined Function (UDF) is that you can save the function in a personal macro workbook and reuse it easily without repeating the steps again and again. You can also create an add-in and share this function with others.

Now let me first give you the VBA code that will create a function to get the list of all the file names from a folder in Excel.

The above code will create a function GetFileNames that can be used in the worksheets (just like regular functions).

Where to put this code?

Follow the steps below to copy this code in the VB Editor.

How to Use this Function?

Below are the steps to use this function in a worksheet:

  • In any cell, enter the folder address of the folder from which you want to list the file names.
  • In the cell where you want the list, enter the following formula (I am entering it in cell A3):
  • Copy and paste the formula in the cells below to get a list of all the files.

Note that I entered the folder location in a cell and then used that cell in the GetFileNames formula. You can also hard code the folder address in the formula as shown below:

In the above formula, we have used ROW()-2 and we started from the third row onwards. This made sure that as I copy the formula in the cells below, it will get incremented by 1. In case you’re entering the formula in the first row of a column, you can simply use ROW().

How does this formula work?

The GetFileNames formula returns an array that holds the names of all the files in the folder.

The INDEX function is used to list one file name per cell, starting from the first one.

IFERROR function is used to return blank instead of the #REF! error which is shown when a formula is copied in a cell but there are no more file names to list.

Using VBA Get a List of All the File Names with a Specific Extension

The above formula works great when you want to get a list of all the file names from a folder in Excel.

But what if you want to get the names of only the video files, or only the Excel files, or only the file names that contain a specific keyword.

In that case, you can use a slightly different function.

Below is the code that will allow you get all the file names with a specific keyword in it (or of a specific extension).

The above code will create a function ‘GetFileNamesbyExt‘ that can be used in the worksheets (just like regular functions).

This function takes two arguments – the folder location and the extension keyword. It returns an array of file names that match the given extension. If no extension or keyword is specified, it will return all the file names in the specified folder.

Syntax: =GetFileNamesbyExt(“Folder Location”,”Extension”)

Where to put this code?

Follow the steps below to copy this code in the VB Editor.

  • Go to the Developer tab.
  • Click on the Visual Basic button. This will open the VB Editor.
  • In the VB Editor, right-click on any of the objects of the workbook you’re working in, go to Insert and click on Module. If you don’t see the Project Explorer, use the keyboard shortcut Control + R (hold the control key and press the ‘R’ key).
  • Double click on the Module object and copy and paste the above code into the module code window.

How to Use this Function?

Below are the steps to use this function in a worksheet:

  • In any cell, enter the folder address of the folder from which you want to list the file names. I have entered this in cell A1.
  • In a cell, enter the extension (or the keyword), for which you want all the file names. I have entered this in cell B1.
  • In the cell where you want the list, enter the following formula (I am entering it in cell A3):
  • Copy and paste the formula in the cells below to get a list of all the files.

How about you? Any Excel tricks that you use to make life easy. I would love to learn from you. Share it in the comment section!

You May Also Like the Following Excel Tutorials:

Источник

How To Get A List Of File Names From A Folder And All Subfolders

Excel is awesome! But with so many people using Excel in large companies, the number of spreadsheets used can become quite massive. Keeping track of all these can become a job in itself.

I worked at a large insurance company and we were in the midst of a project to take inventory of all the spreadsheets used.

We created a VBA procedure that would take a folder path and spit out all the file names in that folder. Each department was responsible for using this to take inventory of all their files. Fortunately for me, my department used only a few folders and subfolders for our work otherwise I would have tried to modify the code to loop through all subfolders in a folder.

We were using Excel 2010 and installing the Power Query add-in was not an option due to IT security lock down. With Power Query this would have been a much less time consuming task and with no coding needed.

Create a From Folder Query

From any workbook that you want to create a file inventory in, you can create a From Folder query. Go to the Data tab in the ribbon and select Get Data from the Get & Transform section. Then choose the From File option in the menu and then the From Folder option in the submenu.

Select the Parent Folder to Query

Add the folder path of the parent folder which you want to query. You can copy and paste this from a windows file explorer address bar or you can use the Browse option to select the folder.

Edit the From Folder Query

A preview will show and you can check the output to make sure it’s the correct folder. Press the Edit button to edit the query. Editing is an optional step if you want more information on the files. Otherwise you can Load the query without editing.

Remove the Content Column

If all you’re looking for is the list of file names from the folders, then you don’t need this column. This column can be used to import data from multiple files in multiple folders.

To remove the Content column, right click on the column heading and select Remove from the menu.

I also like to move the Folder Path column over to the left most column. You can do this by dragging and dropping the column.

Expand the Attribute Column for More Information

Expanding the Attributes column will allow us to see more detailed information about the files. Otherwise we will only see the Folder Path, Name, Extension, Date accessed, Date modified and Date created which may well be all you want to see.

  1. Left click on the filter icon on the Attributes column.
  2. Select or unselect the different file attributes you want to see in the query results.
  3. Uncheck Use original column name as prefix if you don’t want your new attribute columns to be prefixed (ie. Attributes.Kind)
  4. Press the OK button.

You’ll now see the extra columns you chose in the query editor preview.

Close and Load the Query

From the Home tab, press the Close & Load button.

Query Results List All Files

The query will load and then you’ll have a table with information on all the files from your chosen folder and subsequent subfolders. You can then filter this table to look at particular folders or file types, or sort on dates to find the most recent version of a file.

John MacDougall

Subscribe

Subscribe for awesome Microsoft Excel videos 😃

John MacDougall

I’m John, and my goal is to help you Excel!

You’ll find a ton of awesome tips, tricks, tutorials, and templates here to help you save time and effort in your work.

Источник

Понравилась статья? Поделить с друзьями:
  • File merge for excel
  • File menu in microsoft word
  • File lists to excel
  • File listing to excel
  • File labels in word