Folders and File Handling in Excel VBA

Home/Excel VBA/Folders and File Handling in Excel VBA

Folder and File Handling in Excel VBA Examples help you to create, delete,copy,move files and folder. And customize File or Folder dialog Box using VBA.

PREMIUM TEMPLATES LIMITED TIME OFFER

ON SALE80% OFF

BROWSE ALL TEMPLATES

50+ Project Management Templates Pack
Excel PowerPoint Word

VIEW DETAILS

Advanced Project Plan & Portfolio Template
Excel Template

VIEW DETAILS

Business Presentations Templates Pack
PowerPoint Slides

VIEW DETAILS

20+ Excel Project Management Pack
Excel Templates

VIEW DETAILS

20+ PowerPoint Project Management Pack
PowerPoint Templates

VIEW DETAILS

10+ MS Word Project Management Pack
Word Templates

VIEW DETAILS


Check if Folder Exists using Excel VBA


'In this Example I am checking if "C:\Temp" exits
Sub sbCheckingIfAFolderExists()

Dim FSO
Dim sFolder As String

sFolder = "C:\Temp" ' You can Specify Any Folder To Check It
Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FolderExists(sFolder) Then
MsgBox "Specified Folder Is Available", vbInformation, "Exists!"
Else
MsgBox folder &"Specified Folder Not Found", vbInformation, "Not Found!"
End If

End Sub

Opening Folders using VBA Excel


'In this Example I am Opening a Folder ("C:\Temp")
Sub sbOpeningAFolder()

Dim FSO
Dim sFolder As String
sFolder = "C:\Temp" 'You can specify your Folder which you wants to Open

Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FolderExists(sFolder) Then
MsgBox "Specified Folder Not Found", vbInformation, "Folder Not Found!"
ElseIf FSO.FolderExists(sFolder) Then
Call Shell("explorer.exe " &sFolder, vbNormalFocus)
End If

End Sub

Creating Folders in Excel VBA

'In this Example I am creating a Folder "C:\SampleFolder"
Sub sbCreatingAFolder()

Dim FSO
Dim sFolder As String

sFolder= "C:\SampleFolder" ' You can Specify Any Path and Name To Create a Folder
Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FolderExists(sFolder) Then
FSO.CreateFolder (sFolder) 'Checking if the same Folder already exists
MsgBox "New FolderCreated Successfully", vbExclamation, "Done!"
Else
MsgBox "Specified Folder Already Exists", vbExclamation, "Folder Already Exists!"
End If

End Sub

Copying Folders From One Location to Another in Excel VBA

'In this Example I am Coping "C:\Temp\" to "D:\Job\"
Sub sbCopyingAFolder()

Dim FSO
Dim sFolder As String, dFolder As String

sFolder = "C:\Temp\" 'Specify Your Source Folder
dFolder = "D:\Job\" ' Specify Your Destination Folder
Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FolderExists(dFolder) Then
FSO.CopyFolder sFolder, dFolder
MsgBox "Folder Copied Successfully to The Destination", vbExclamation, "Done!"
Else
MsgBox "Folder Already Exists in the Destination", vbExclamation, "Folder Already Exists!"
End If

End Sub

Move Folder From One Location to Another in Excel VBA

'In this Example I am Moving "C:\Temp\" to "D:\Job\"
Sub sbMovingAFolder()

Dim FSO
Dim sFolder As String, dFolder As String

sFolder = "C:\Temp\" 'Specify Your Source Folder
dFolder = "D:\Job\" ' Specify Your Destination Folder
Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FolderExists(dFolder) Then
FSO.MoveFolder sFolder, dFolder
MsgBox "Folder Moved Successfully to The Destination", vbExclamation, "Done!"
Else
MsgBox "Folder Already Exists in the Destination", vbExclamation, "Folder Already Exists!"
End If

End Sub

Deleting Folders in VBA Excel


'In this Example I am Deleting "C:\SampleFolder"
Sub sbDeletingAFolder()

Dim FSO
Dim sFolder As String

sFolder = "C:\SampleFolder" 'Specify Your Folder Which You Wants to Delete
Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FolderExists(sFolder) Then
FSO.DeleteFolder sFolder
MsgBox "Specified Folder Deleted Successfully", vbExclamation, "Done!"
Else
MsgBox "Specified Folder Not Found", vbExclamation, "Not Found!"
End If

End Sub

Make File Read Only in VBA Excel


Sub sbMakeFileReadOnly()

Dim strSaveFilename As String
Dim oFSO As Object
Dim oFile As Object

sFile = "C:\ExampleFile.xls" 'Your File name and Path to make it read only
'Create Objects
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.GetFile(FilePath:=sFile)

'Set file to be read-only
oFile.Attributes = 1

'Releasing Objects
If Not oFSO Is Nothing Then Set oFSO = Nothing
If Not oFile Is Nothing Then Set oFile = Nothing

End Sub

Copy all Excel Files One Folder to Another in VBA Excel


'In this Example I am Coping all excel files from one Folder ("C:\Temp\") to another Folder ("D:\Job\")
Sub sbCopyingAllExcelFiles()

Dim FSO
Dim sFolder As String
Dim dFolder As String

sFolder = "C:\Temp\" ' change to match the source folder path
dFolder = "D:\Job\" ' change to match the destination folder path
Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FolderExists(sFolder) Then
MsgBox "Source Folder Not Found", vbInformation, "Source Not Found!"
ElseIf Not FSO.FolderExists(dFolder) Then
MsgBox "Destination Folder Not Found", vbInformation, "Destination Not Found!"
Else
FSO.CopyFile (sFolder & "\*.xl*"), dFolder
MsgBox "Successfully Copied All Excel Files to Destination", vbInformation, "Done!"
End If

End Sub

Opening Files Using File Dialog Box in Excel VBA

Solution: You can get the file name using file dialog and open it by using Workbooks.Open method


Sub OpenWorkbookUsingFileDialog()

Dim fdl As FileDialog
Dim FileName As String
Dim FileChosen As Integer

Set fdl = Application.FileDialog(msoFileDialogFilePicker)

'Set the caption of the dialog box,
fdl.Title = "Please Select a Excel Macro File"
'Set the InitialFile Path
fdl.InitialFileName = "c:\"
'Set the Folder View
fdl.InitialView = msoFileDialogViewSmallIcons
'Set the filter
fdl.Filters.Clear
fdl.Filters.Add "Excel Macros Files", "*.xlsm"

FileChosen = fdl.Show

If FileChosen <> -1 Then
'Not choosen anything / Clicked on CANCEL
MsgBox "You have choosen nothing"
Else
'display name and complete path of file chosen
MsgBox fdl .SelectedItems(1)
End If

FileName = fdl.SelectedItems(1)
'Open the File
Workbooks.Open (FileName)

End Sub

Customize File or Folder Dialog Box in VBA Excel

Solution: You can set differ properties of the file-dialog box to look more prettier


Sub CustomizingFileDialog()

Dim fdl As FileDialog
Dim FileChosen As Integer

Set fdl = Application.FileDialog(msoFileDialogFilePicker)

'Set the caption of the dialog box,
fdl.Title = "Please Select a Excel Macro File"
'Set the InitialFile Path
' determine the initial folder selected
fdl.InitialFileName = "c:\"
'Set the Folder View
fdl.InitialView = msoFileDialogViewSmallIcons
'Set the filter
fdl.Filters.Clear
fdl.Filters.Add "Excel Macros Files", "*.xlsm"

FileChosen = fdl.Show

If FileChosen <> -1 Then
'Not choosen anything / Clicked on CANCEL
MsgBox "You have choosen nothing"
Else
'display name and complete path of file chosen
MsgBox fdl.SelectedItems(1)
End If

End Sub

Excel VBA File Dialog Box – Displaying Vanilla Dialog Box to Pick Files

Solution: You can use Application.FileDialog(msoFileDialogFilePicker) method


Sub ChooseFileUsingFileDialog()

Dim fld As FileDialog
Dim FileChosen As Integer

Set fld = Application.FileDialog(msoFileDialogFilePicker)
FileChosen = fld.Show

If FileChosen <> -1 Then
'Not choosen anything / Clicked on CANCEL
MsgBox "You have choosen nothing"
Else
'display name and complete path of file chosen
MsgBox fld.SelectedItems(1)
EndIf

End Sub

LIMITED TIME OFFER
By |June 15th, 2013|Excel VBA|19 Comments

About the Author:

Excel VBA Developer having around 8 years of experience in using Excel and VBA for automating the daily tasks, reports generation and dashboards preparation. Valli is sharing to helps us automating daily tasks.

19 Comments

  1. Paul July 24, 2014 at 5:25 PM - Reply

    Hi,
    I am trying the Opening A Folder Code but i am getting a syntax error on the below line

    Elself Not FSO.FolderExists(dfol) Then

    Please assist

    Thanks in advance

    • adminBA July 24, 2014 at 6:07 PM - Reply

      Hi Paul,

      Sorry! It was a mistake, I have corrected it, please check the updated code.

      Thanks-PNRao!

  2. Jeremy April 5, 2015 at 12:26 AM - Reply

    These are great examples but how about copying multiple file folders (and its contents) to multiple locations that are specified in the excel worksheet.
    Lets say that column A is the file (or source) that we want to move and column B is the new location (the destination) that we want the folder (and its contents) to be copied into.
    Then the next row would be a different source and destination from that one and so on. I’m working on a formula, hopefully it may work but if you have something created I would love to see it.

    • Gert August 27, 2015 at 8:55 PM - Reply

      I am having the exact same problem, did you manage to find a solution?

    • Tom August 31, 2015 at 10:54 AM - Reply

      Try this:

      Sub sbCopyFoldersFromSourceToDestination()
      ‘This will copy folders from a given source path to a destination path
      ‘The source folder list will be defined by the named range “src”
      ‘The destination path will be in the adjacent cell to the right of the the source path (+1 column)
      ‘e.g. if the the source folder paths are in range A2:A5 the destination paths need to be in range B2:B5

      ‘***Note this will overwrite any files/folders without warning! ***
      ‘Add an FSO.FolderExists(sDestinationPath) IF statement if you want to check the folder exists before overwriting

      Dim FSO
      Dim sSourcePath As String, sDestinationPath As String
      Dim oCell

      Set FSO = CreateObject(“Scripting.FileSystemObject”)

      For Each oCell In Range(“src”) ‘loop through the range and get the file paths
      sSourcePath = oCell ‘source file path
      sDestinationPath = oCell.Offset(0, 1) ‘destination file path in the nect column
      FSO.CopyFolder sSourcePath, sDestinationPath ‘copy the folder

      Next oCell
      MsgBox “Successfully Copied All Folders to Destination”, vbInformation, “Done!”
      End Sub

  3. Ajay November 23, 2015 at 1:37 PM - Reply

    how to create folder with user given name instead stead of one name

    • PNRao November 27, 2015 at 5:07 PM - Reply

      Hi Ajay,

      Please find the below code.

      Sub sbCreatingAFolder()
      Dim FSO
      Dim sFolder As String, FolName As String
      'Dynamic Folder Name
      FolName = InputBox("Please enter the folder name", "Folder Name")
      sFolder = "C:\Users\enirpai\Desktop\" & FolName ' You can Specify Any Path and Name To Create a Folder
      Set FSO = CreateObject("Scripting.FileSystemObject")
      If Not FSO.FolderExists(sFolder) Then
      FSO.CreateFolder (sFolder) 'Checking if the same Folder already exists
      MsgBox "New FolderCreated Successfully", vbExclamation, "Done!"
      Else
      MsgBox "Specified Folder Already Exists", vbExclamation, "Folder Already Exists!"
      End If
      End Sub
      

      Regards=Valli

  4. Tarek Kamel December 3, 2015 at 1:56 PM - Reply

    thanks a lot, it was very useful.

  5. Ashima Gupta January 14, 2016 at 11:21 AM - Reply

    Hello All,

    I want to display the path of the file selected in the text box.
    The path is stored in a variable I created i.e. mypath
    I want to display the path in the text box.

    • PNRao January 14, 2016 at 6:30 PM - Reply

      strFilePath=”Your filepath” ‘ This is your file path
      TextBox1.Text=strFilePath ‘This will place your file path in the textbox named TextBox1.

      Hope this helps.
      Thanks-PNRao!

  6. Bhupender February 3, 2016 at 9:20 AM - Reply

    Hi,

    I am trying to move folder from D:\PENDRIVE\solution\” to D:\Camera\New folder\” but when I am using your above mentioned code then it is showing error folder already exists, however folder is not exists in destination folder actually, so please help my out.

    Sub sbMovingAFolder()

    Dim fso
    Dim sFolder As String, dFolder As String

    sFolder = “D:\PENDRIVE\solution\” ‘Specify Your Source Folder
    dFolder = “D:\Camera\New folder\” ‘ Specify Your Destination Folder
    Set fso = CreateObject(“Scripting.FileSystemObject”)

    If Not fso.FolderExists(dFolder) Then
    fso.MoveFolder sFolder, dFolder
    MsgBox “Folder Moved Successfully to The Destination”, vbExclamation, “Done!”
    Else
    MsgBox “Folder Already Exists in the Destination”, vbExclamation, “Folder Already Exists!”
    End If

    End Sub

  7. Agni February 10, 2016 at 8:24 PM - Reply

    Hi,
    I am looking for the code, which will help me to move the converted files from the source location to another location(This should prompt the user to provide the path to create a folder).

    Converted file -> different versions….

  8. Pruthvi Vattikunta March 8, 2016 at 11:58 PM - Reply

    Hello,
    i want to write a code in vba in MS access to select a particular name using a combo box..can u please suggest me…

  9. Hasib April 30, 2016 at 1:00 AM - Reply

    Hello,

    These all seem very helpful. Could you please tell me how I could modify the code that makes a user select a file to allow them to select multiple files (from one location) and then loop through each selection so that I can have an action associated with each file?

    Thanks,

  10. Jay May 11, 2016 at 7:51 AM - Reply

    Hi,

    How can i approach this problem.

    I have multiple excel files in different folders in running dates order. There are data within each of those excel files which i want to copy and collate in a single master excel file.

    how can this be done?

  11. Rahman August 7, 2016 at 6:35 PM - Reply

    Hi,

    Thanks for useful examples, I want move or copy a file (which is excel or word and etc) from one folder to another folder. How can this be done?

  12. Glynn Norgan August 26, 2016 at 2:57 AM - Reply

    Thank you. Been working on how to open a folder all day. Your code is what i needed.

  13. Venkatesh September 27, 2016 at 3:40 PM - Reply

    Hi,

    Is there a code to close a folder

    Regards,
    Venkatesh

  14. VIVEK December 6, 2016 at 7:45 PM - Reply

    HI,
    I AM VIVEK TALAVIYA

    i want to formula of vba projects for converting amount into words in excel

    please,

    Yours Faithfully,
    vivek talaviya

Leave A Comment