How to Copy a Folder in VBA (With Example)

VBA, or Visual Basic for Applications, is an incredibly powerful language used for programming in the Microsoft Office Suite of applications. It is commonly used by developers to automate certain tasks within a Microsoft Office application, such as creating new folders, copying and moving data, and more. One of the most common tasks that VBA can be used for is copying a folder. This article will explain the importance of being able to copy a folder in VBA, and provide an example of how to do so.


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:UsersbobDocumentscurrent_data"
DestFolder = "C:UsersbobDesktop"

'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:UsersbobDocumentscurrent_data"
DestFolder = "C:UsersbobDesktop"

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

End Sub

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 .

x