Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The last macro opens selected files.
The animated image below shows the user typing the folder name in cell B1, press with left mouse button on "Refresh list" button and cell range A4:B6 is populated with file names, file sizes and checkboxes.
The checkboxes allow the user to select workbook files to open, the selected workbooks are opened as soon as the user press with left mouse button ons on "Open selected files" button located on the worksheet.
What you will learn in this article
- How to insert buttons on the worksheet.
- How to assign macros to the buttons.
- How to use macros.
- How to list files and file sizes from a given folder on a worksheet using VBA.
- How to insert checkboxes programmatically.
- How to open selected files programmatically.
- How to save VBA code to your workbook.
List files in a folder
The following macro is assigned to the "Refresh list" button. It lists all *.xls, *.xlsx and *.xlsm files in the folder specified in cell B1.
'Name macro Sub ListFiles() 'Dimension variables and declare data types Dim cell As Range, selcell As Range Dim Value As String Dim Folder As Variant, a As Long ReDim Folders(0) 'Save cell A4 to object cell Set cell = Range("A4") 'Save selected cell (range) to variable selcell Set selcell = Selection 'Clear cell range A4:B10000 Range("A4:B10000").Value = "" 'Save value in cell B1 to variable Folderpath Folderpath = Range("B1").Value 'Check if variable Folderpath ends with \ (backslash) If Right(Folderpath, 1) <> "\" Then 'Add a backslash if missing Folderpath = Folderpath & "\" End If 'Return first file name in path specified in variable Folderpath Value = Dir(Folderpath, &H1F) 'Continue iterate through files in folder until it is empty Do Until Value = "" 'Make sure file name is not . (current directory) or .. (parent directory) If Value <> "." And Value <> ".." Then 'Make sure file name is not a folder If GetAttr(Folderpath & Value) <> 16 Then 'Make sure file name ends with .xls or .xlsx or .xlsm If Right(Value, 4) = ".xls" Or Right(Value, 5) = ".xlsx" Or Right(Value, 5) = ".xlsm" Then 'Save file name and file size to cell A4 and cell B4 respectively cell.Offset(0, 0).Value = Value cell.Offset(0, 1).Value = FileLen(Folderpath & Value) 'Move to cell below Set cell = cell.Offset(1, 0) End If End If End If 'Continue with next file Value = Dir 'Go back to Do Until Loop 'Start macro Addcheckboxes Call Addcheckboxes 'Select the same cells that were selected when the macro started selcell.Select End Sub
Recommended reading
Recommended articles
Today I'll show you how to search all Excel workbooks with file extensions xls, xlsx and xlsm in a given folder for a […]
Add checkboxes to column C
'Name macro Sub Addcheckboxes() 'Dimension variables and declare data types Dim cell, LRow As Single Dim chkbx As CheckBox Dim CLeft As Double, CTop As Double, CHeight As Double, CWidth As Double 'Stop Excel screen from updating, this makes the macro a lot faster Application.ScreenUpdating = False 'Delete all old checkboxes on active worksheet ActiveSheet.CheckBoxes.Delete 'Save row number of cell containing non-empty values to variable LRow LRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 'Iterate through number 4 to number stored in variable LRow For cell = 4 To LRow 'Make sure cell is not empty If Cells(cell, "A").Value <> "" Then 'Save the number of pixels between cell in column C based on the row number stored in variable cell and left edge CLeft = Cells(cell, "C").Left 'Save the number of pixels between cell in column C based on the row number stored in variable cell and top CTop = Cells(cell, "C").Top 'Save the height (number of pixels) of cell in column C based on the row number stored in variable cell CHeight = Cells(cell, "C").Height 'Save the cell width (in pixels) of cell in column C based on the row number stored in variable cell CWidth = Cells(cell, "C").Width 'Insert and select checkbox based on left, top, width and height ActiveSheet.CheckBoxes.Add(CLeft, CTop, CWidth, CHeight).Select 'Remove text and make sure checkbox is not checked With Selection .Caption = "" .Value = xlOff .Display3DShading = False End With End If Next cell 'Show Excel screen changes Application.ScreenUpdating = True End Sub
Recommended reading
Recommended articles
This article demonstrates macros that allow you to search for a text string(s) in multiple worksheets and workbooks located in […]
Open selected files
The macro below is assigned to "Open selected files" button. It checks if a checkbox is enabled and opens the excel file.
'Name macro Sub OpenFiles() 'Dimension variables and declare data types Dim Folderpath As String Dim cell As Range Dim r As Single, LRow As Single Dim CWB As Workbook 'Save value in cell B1 to variable Folderpath Folderpath = Range("B1").Value 'Save Active Workbook to object CWB Set CWB = ActiveWorkbook 'Check if last character in folder path is not a backslash If Right(Folderpath, 1) <> "\" Then 'Add backslash Folderpath = Folderpath & "\" End If 'Iterate through checkboxes located on active worksheet For Each chkbx In ActiveSheet.CheckBoxes 'Check if checkbox is enabled If chkbx.Value = 1 Then 'Count cells above checkbox in order to open the right file For r = 1 To Rows.Count 'Check if pixel count is the same between cell and checkbox If Cells(r, 1).Top = chkbx.Top Then 'Open workbook based on name in cell Workbooks.Open Filename:=Folderpath & Range("A" & r).Value 'Stop macro Exit For End If 'Continue with next row number Next r 'Activate workbook CWB.Activate End If Next End Sub
Where to put the macros?
- Press Alt + F11 to open the Visual Basic Editor.
- Press with left mouse button on "Insert" on the top menu.
- Press with left mouse button on "Module" to insert a code module. It will appear in the project explorer, see image above.
- Copy above VBA code and paste to the code module.
- Exit VB Editor and return to Excel.
Check boxes category
This article demonstrates a macro that copies selected rows based on enabled check boxes. The image above shows data on […]
In this post, I will demonstrate a macro that creates checkboxes in nonempty rows, see checkboxes in column E in image […]
Today I will share a To-do list excel template with you. You can add text to the sheet and an […]
Files and folders category
Today I'll show you how to search all Excel workbooks with file extensions xls, xlsx and xlsm in a given folder for a […]
This article demonstrates macros that allow you to search for a text string(s) in multiple worksheets and workbooks located in […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
Macro category
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
Excel categories
42 Responses to “Open Excel files in a folder [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
This is a great tool, However any idea on how to make it work for excel for mac 2011?
Run-time error '5': invalid prodedure call or argument on Value = Dir(Folderpath, &H1F)
Cyril,
Try this:
Value = Dir(Folderpath)
Run-time error '68': device unavailable on Value = Dir(Folderpath)
Now could he be related with the way the path is written? No c:\ in mac... Any suggestion?
Cyril,
I found this and Dir seems to work on excel for mac 2011:
https://stackoverflow.com/questions/7294838/loop-though-files-in-a-folder-on-mac-os-x-vba-excel-2011
Oscar, what's this "&H1F" supposed to do?
chrisham,
great question, I am not sure where I got it from.
You can find the attributes here: https://www.techonthenet.com/excel/formulas/dir.php
Hi OScar,
how about a macro to close open workbooks?
Danilo,
I think this i what you are looking for:
https://www.mrexcel.com/forum/excel-questions/31760-visual-basic-applications-close-all-workbooks-macro.html
This is great tool. But in my case, i need to list all xls from folder, and its subfolders. Can you help me with this ?
I love this and will be using it everyday from today, but when I try to open the files I get one only to open and get a error "code execution has been interrupted". Can you help me with this?
ok I found this, it seems that it is an excel bug, you just need to put this code as the first line in your sub and thats it...
But be aware that if you have coded endless loops, and you insert the above code, you can't interrupt it using Esc or Ctrl+Pause/Break!!!!
ScottyG,
I found this answer from Dick Kusleika:
It's most likely a corruption of the p-code that's created when you compile. Some people have had success by choose Clear All Breakpoints from the Debug menu. The rock solid method is to export all of your modules, delete them, then reimport them. This round trip through plain text forces a complete rebuild of the p-code. Google for Rob Bovey's Code Cleaner for a free utility that automates this process.
https://stackoverflow.com/questions/6033953/why-does-vba-stop-if-enablecancelkey-is-not-disabled
Hi, do you know why there is a syntax in the code? Please see my post. thank you
seems like there is a syntax with the &:
If GetAttr(Folderpath & Value) 16 Then
How can I fix?
Also, how can I use the xlm files? They dont appear to be .xls files.
thank you
OK I think it is a copy and paste issue. I see the & changes to & Value but must be careful and if it doesnt change then do it manually.
Where do you put the file path at?
Tony,
Thank you for letting me know about the amp error. I removed it from the code. It happens sometimes when I update a post in wordpress, I don´t know why.
Also, how can I use the xlm files? They dont appear to be .xls files.
The following code also lists *.xlm files:
HI Oscar, thanks for the reply about the syntax. Where would I put the path to my folder on the network drive? I am not a programmer and dont know much about VBA so would appreciate a lamens explanation. thanks...
Regarding the xlm files, I thought that the link " List all files in a folder.xlsm" would provide xls files ie sample files?
Tony,
Where would I put the path to my folder on the network drive?
Enter the path in cell B1. See the first picture.
oh I see... thank you. Will circle back if I have any issues. I like your website. thanks...
Everything works just great, thank you very much!
I wonder if it would be possible to add another vba code that can uncheck the eventually checked boxes?
Nic,
I wonder if it would be possible to add another vba code that can uncheck the eventually checked boxes?
Sure!
Hi Oscar thank you for your replay,
I saw the change you made "chkbx.Value = 0" and I did realize that¨my question was not so complete... Sorry for that, my English is not that good, I'm not a programmer and I'm a simple excel user
I try again :)
I would like to have a button that clear the checked boxes, if i check more than one. Is that possible? If yes, what is the vba code?
Well thank you for your time and have a great day.
My best
Nic
I found the solution, it was too easy for me lol
I just need to reload the dir to uncheck the boxes. I have about 20 dir and about 150 files in each one.
I learned something today.
Thank you again
Hi,
Firstly this is brilliant and just what I was looking for Thank you
ListFiles and Addcheckboxes run fine.
My only problem is I get an error when running the open files code. Run-time error `1004': Application-defined or object-defined error.
I am just starting out using VBA and have no idea how to correct this error, or even find it for that matter!
I am using Excel 2003
any help would be apreciated
Thanks again,
Mark
Hi,
I have got the code to work!
I was trying to use it to open a .doc word file. It works fine with excel files.
I have ammended to search for and list .doc files
Is there anyway to change this code to also open .doc files?
Thank you!
Mark,
I am happy you got it working!
I was trying to use it to open a .doc word file. It works fine with excel files.
I have ammended to search for and list .doc files
Is there anyway to change this code to also open .doc files?
Yes!
Get the Excel *.xlsm file
List-all-files-in-a-folder-open-doc1.xlsm
Thank you !
This works absolutly perfect !
again, thanks for helping me out !
Mark
Hi again,
Thanks for your help already given.
I have been using the code a lot and found it really usefull.
I was wondering if there was anyway to also open .pdf .tiff and .jpeg files?
This would be really handy and include all the filetypes I need to be working with to open.
Thanks in advance for your help.
Mark
Hi Oscar, can you write a code for pdf, png (Snagit), txt, prn files?
Thanks in advance.
Mark and Anibal,
Get the Excel *.xlsm file
List-all-files-in-a-folder-open-any-file.xlsm
Oscar,
Hi and thanks for your reply.
I have been trying to add code to yours to open up .pdf files using .shell command. I got a code to work to open .pdf's the problem with this is it searches for and opens Acrobat reader (AcroRd32.exe) then opens the file. This created a long code and upon opening Acrobat reader caused it to crash anyway.
I see what you have done with this code . . .
[vb1="vbnet"language="."]
ActiveWorkbook.FollowHyperlink Folderpath & Range("A" & r).Value, NewWindow:=True
[/vb]
Using the folder path and filename as a hyperlink to open. Works every time. with any file extension. Even AutoCAD. where I was taking a similar approach using AutoCAD.Application and .Documents.Open which I couldn't get to work either.
I was totally stuck and writing longer and longer and more complicated codes! that didn't work!
the .FollowHyperlink is GENIUS! Simple and Genius
And all done in 1 line ! I would never of thought of this in a million years!
Thanks again so much for the help and thanks for your time.
This is a really useful Macro, I use it on a daily basis!
Thank you and compliments on a really helpful website.
Mark
Mark,
Thanks! I found out about the ActiveWorkbook.FollowHyperlink here:
https://www.vbaexpress.com/kb/getarticle.php?kb_id=905
It is great!
Hi Oscar,
could it be possible to have another button that gives me the possibility to print the file/files I check, without the need to open them?
If yes, can you please write the code?
Thanks in advance
Nic
Nic,
Try this:
That works just perfect Oscar!
Thank you so much for your help and your time
Have a nice summer
/Nic
Hi Oscar, can you pls help me on this...
lets say that i have 4 dirctories and in each dir I have 50 workbooks.
On the main workbook called index.xlsm, that works like a file explorer, I got 4 buttons linked to the dirs 1-2-3-4, here I'm using your code " list excel files in a specified folder ...." to see the files of each dir as a list.
In the index.xlsm i have put a 5th button called "förhandsgranska" (preview).
So when I Press with left mouse button on the button "1", in the index.xlsm, I see the files.
When the list is populated I Press with left mouse button on the button 5, a window pops up and it shows me the same file list that I see in the index.xlsm.
At this point when I select a file name, in the popup window, i see an image or preview of that file.
I would like to have a print button on the popup window that prints the preview of that file i choosed to view and that it doenst close the popup window.
The index.xlms is in the same folder [img] there the images are.
I found the code of that "popup window" on a site and I lost the link to it.
I made some small changes to the originnal to fit my needs.
Hope I was enough clear.... my English is still bad.
Thank you
/nic
Hi Oscar,
First off, thanks for the code - it is almost exactly what I have been trying to do!
I say almost as all I really needed to do was to move the cell locations around a little. Essentially the checkboxes go to column A and all is well and good. This works for the first file, but for the second and third the code "thinks" that none of the checkboxes are selected.
Any ideas?
Cheers,
Gary
Gary Hicks,
List-all-files-in-a-folderv2.xlsm
Hi Oscar, can you pls help me on this...
My code opens files in a selected folder and perform some actions on the file before closing the file.
What I want to do is before opening the file, the code should check and skip all files that are not protected with a known password.
Thanks
Freeman Kwashie,
The macro demonstrated here: https://www.get-digital-help.com/2014/01/08/search-all-workbooks-in-a-folder/
ignores workbooks with a password. Perhaps you can use the same technique to only open workbooks password-protected with a known password.
Probably something like this (not tested):
Hi is the possible to have button that gives me the possibility to print all type of file that (atleast excel and word) I check, without the need to open them?
Ramesh,
no. Not that I know.