How to Copy a Folder in VBA (With Example)


You can use the CopyFolder method in VBA to copy a folder from one location to another.

Here is one common way to use this method in practice:

Sub CopyMyFolder()

Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
    
'specify source folder and destination folder
SourceFolder = "C:\Users\bob\Documents\current_data"
DestFolder = "C:\Users\bob\Desktop\"

'copy folder
FSO.CopyFolder Source:=SourceFolder , Destination:=DestFolder

End Sub

This particular macro copies the folder called current_data from the Documents folder to the Desktop.

The following example shows how to use this syntax in practice.

Example: How to Copy Folders Using VBA

Suppose we have a folder called current_data located in a folder called Documents:

Now suppose we would like to use VBA to copy this entire folder to the Desktop, which currently contains two folders:

Before using VBA to copy this file, we need to first enable Microsoft Scripting Runtime within the VB Editor.

To do so, open the VB Editor, then click Tools, then click References:

In the new window that appears, scroll down until you see Microsoft Scripting Runtime and check the box next to it. Then click OK.

Next, we can create the following macro to copy the folder:

Sub CopyMyFolder()

Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
    
'specify source folder and destination folder
SourceFolder = "C:\Users\bob\Documents\current_data"
DestFolder = "C:\Users\bob\Desktop\"

'copy folder
FSO.CopyFolder Source:=SourceFolder , Destination:=DestFolder

End Sub

Once we run this macro, the folder named current_data will be copied from the Documents folder to the Desktop:

The original current_data folder will still remain in the Documents folder as well.

Note: You can find the complete documentation for the CopyFolder method here.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

How to Create Folders Using VBA
How to Delete Folders Using VBA
How to List Files in Folder Using VBA

Leave a Reply

Your email address will not be published. Required fields are marked *