How can I copy a folder in VBA, and can you provide an example?

VBA (Visual Basic for Applications) is a programming language used to automate tasks in Microsoft Office applications. To copy a folder in VBA, you can use the “FileCopy” method. This method allows you to copy a file or folder from one location to another. An example of how to use this method is as follows:

FileCopy “C:UsersUsernameDesktopFolder1”, “C:UsersUsernameDesktopFolder2”

This code will copy the entire contents of “Folder1” to “Folder2” on the user’s desktop. It is important to note that the destination folder must already exist for the method to work. By using the “FileCopy” method, you can easily copy folders in VBA to automate tasks and improve efficiency.

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 folderSourceFolder = "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 folderSourceFolder = "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 .

Additional Resources

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

x