Copy excel files vba

Excel VBA FileCopy Function

FileCopy is a built-in VBA function used to copy the file from one location to another mentioned location. To use this function, we need to mention the current file path and destination file path.

Table of contents
  • Excel VBA FileCopy Function
    • Examples
      • Example #1
      • Example #2 – Use Variables to Store Source Path and Destination Path.
      • Example #3 – Error with File Copy Function
    • Recommended Articles

Let us look at the syntax of the FileCopy function.

FileCopy syntax

  • Source: This is nothing but from where we need to copy the file. We need to mention the fully qualified folder path.
  • Destination: This is the destination folder where we must paste the copied file.

Examples

Below are examples of how to copy files using VBA CodeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

You can download this VBA File Copy Excel Template here – VBA File Copy Excel Template

Example #1

Let us start with a simple example. We have a file named “Sales April 2019” in the folder. Below is the image of the same “Source.”

VBA FileCopy Example 1

We want to copy and paste this file to a different folder from the above location. Below is the image of the same, “Destination Source.”

VBA FileCopy Example 1-1

Let us write the code for it.

Open the FileCopy function inside the Sub procedure.

Code:

Sub FileCopy_Example1()

FileCopy

End Sub

VBA FileCopy Example 1-2

For the first argument, we need to mention the file path where our currency is in.

Code:

Sub FileCopy_Example1()

FileCopy “D:My FilesVBAApril Files

End Sub

VBA File Copy Example 1-1

After mentioning the folder path, we need to mention the file with a file extension. So, mention the file name by putting a backslash ().

Code:

Sub FileCopy_Example1()

FileCopy "D:My FilesVBAApril FilesSales April 2019.xlsx",

End Sub

Provide File Name

The second argument mentions where we need to paste the copied file.

Code:

Sub FileCopy_Example1()

FileCopy "D:My FilesVBAApril FilesSales April 2019.xlsx", "D:My FilesVBADestination FolderSales April 2019.xlsx"

End Sub

Paste Destination Path

One thing we need to do hereafter mentioning the folder path at the end is mention the file name in the destination argument.

Now, run the code using the F5 key or manually. Then, it will copy the file from the below location to a destination location.

“D:My FilesVBAApril FilesSales April 2019.xlsx”

“D:My FilesVBADestination FolderSales April 2019.xlsx”

Destination Path

Example #2 – Use Variables to Store Source Path and Destination Path.

In the previous example, we supplied the source and destination paths directly to the formula. But this is not the best practice to continue, so let’s store them in variables.

For example, look at the below code.

Code:

Sub FileCopy_Example2()

Dim SourcePath As String
Dim DestinationPath As String

SourcePath = "D:My FilesVBAApril FilesSales April 2019.xlsx"
DestinationPath = "D:My FilesVBADestination FolderSales April 2019.xlsx"

FileCopy SourcePath, DestinationPath

End Sub

Code #2

Let me explain the code in detail for you.

First, we have declared two variables.

Dim SourcePath As String

Dim DestinationPath As String

Then, for the first variable, we have assigned the folder path from where it has to copy the file and its name along with its extension.

SourcePath = "D:My FilesVBAApril FilesSales April 2019.xlsx"

Similarly, we have assigned the destination folder path with the file name and excel extension.Excel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more

DestinationPath = "D:My FilesVBADestination FolderSales April 2019.xlsx"

Then for the formula FileCopy, we have supplied these variables instead of lengthy folder path strings.

FileCopy SourcePath, DestinationPath

Like this, we can use variables to store the paths and use them efficiently.

Example #3 – Error with File Copy Function

Sometimes the FileCopy function encounters an error of “Permission denied.”

Error

We get this error when the copying file is open. Therefore, always close the file and execute the code if you try to copy the above error.

Recommended Articles

This article has been a guide to VBA FileCopy. Here, we discuss copying Excel files from one directory to another using the FileCopy function and examples. Below you can find some useful Excel VBA articles: –

  • INSTRREV Function in VBA
  • VBA Chr
  • File System Object in VBA
  • VBA Delete File

FileCopy in VBA

Excel VBA FileCopy

There are many ways to copy or move a file from one folder to another. We can do it manually from Copying and cutting the file icon and pasting it into the destination folder. But when it comes to automating this process of copying the file, we can do that in VBA as well. To copy the file, we have a function available in VBA named as same “File Copy”.

Syntax of FileCopy in Excel VBA

It is very easy to apply File Copy in VBA. The syntax of File Copy is as shown below.

Syntax of VBA File Copy

File Copy has only two components to feed. Which are:

  • Source – Here we will put the source location from where we need to copy the file.
  • Destination – And this will be the destination folder where we will be pasting the copied file.

The complete syntax will be in String datatype. Because we will be using the path of the file which will be as text.

How to Copy a File in Excel VBA?

Now let us try with some examples on VBA File Copy in Excel.

You can download this VBA Copy a File Excel Template here – VBA Copy a File Excel Template

Example #1 – FileCopy In VBA

In the first example, we will see how to copy a file from a source location and paste it in a destination location in a very simple way.

For this, we need a file of any kind or extension. Here we are considering an Excel file with extension xlsx. As we can see, we have placed that excel file into a location which is easy to access named as Test.

VBA Copy File Example 1.1

Now we will copy this file with the help of FileCopy to the below destination folder.

VBA Copy File Example 1.2

Step 1: For this, go to VBA and open a Module from Insert menu drop-down option as shown below.

FileCopy Module

Step 2: Now in the opened module, write the subcategory of VBA FileCopy or in any other name as per your choice.

Code:

Sub VBA_Copy1()

End Sub

VBA Copy File Example 1.3

Step 3: Now directly open the FileCopy function as shown below.

Code:

Sub VBA_Copy1()

FileCopy(

End Sub

VBA Copy File Example 1.4

Step 4: Now in quotes write the source location address followed by file name and extension as shown below.

Code:

Sub VBA_Copy1()

FileCopy "D:Test1Hello.xlsx",

End Sub

VBA Copy File Example 1.5

Step 5: For the Destination location, again put the path in inverted commas followed by file and extension.

Code:

Sub VBA_Copy1()

FileCopy "D:Test1Hello.xlsx", "D:VPB FileApril FilesHello.xlsx"

End Sub

Example 1.6

Step 6: Now compile the code and run it by clicking on the Play button which is located below the menu bar. We will see, the excel file with name Test is now copied from the source location to destination location as shown below. As there was nothing in the file so the size of the file is coming as 0 KB.

Example 1.7

Example #2 – FileCopy In VBA

In another example, we will see how to copy the file from Source location to Destination by defining the variable. This process is little lengthy but more reliable as we will be fixing the parameters and variable.

Step 1: Now first open a new module and write the subcategory of VBA File Copy as shown below.

Code:

Sub VBA_Copy2()

End Sub

VBA Copy File Example 2.1

Step 2: First, define a variable where we will be putting the source location of the file same excel file which we have used in example-1 as String.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String

End Sub

VBA Copy File Example 2.2

Step 3: In a similar way, we will be needing another variable for the Destination location.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

End Sub

VBA Copy File Example 2.3

Step 4: Now put the location in the first defined variable which is “FirstLocation” along with file name and its extension.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:Test1Hello.xlsx"

End Sub

Example 2.4

Step 5: In a similar way, do that same thing for Destination location using variable “SecondLocation” which we have defined above.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:Test1Hello.xlsx"
SecondLocation = "D:VPB FileApril FilesHello.xlsx"

End Sub

Example 2.5

Step 6: Now it is the time to use FileCopy function.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:Test1Hello.xlsx"
SecondLocation = "D:VPB FileApril FilesHello.xlsx"

FileCopy

End Sub

VBA Copy File Example 2.6

As per syntax of the FileCopy first, we have to put source location, where we have kept the file. But as we have already defined the source and destination location folders in above for both variables.

Step 7: So here we can directly select those variables. First select source location variable which is FirstLocation.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:Test1Hello.xlsx"
SecondLocation = "D:VPB FileApril FilesHello.xlsx"

FileCopy FirstLocation

End Sub

Example 2.7

Step 8: Again in a similar way, select the destination location variable which is SecondLocation as shown below.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:Test1Hello.xlsx"
SecondLocation = "D:VPB FileApril FilesHello.xlsx"

FileCopy FirstLocation, SecondLocation

End Sub

Example 2.8

Step 9: Once done, we will compile the code by pressing F8 functional key. And if there is no error found, then run the code. We will see, the file from source location is copied and pasted in the destination folder as shown below.

Example 2.6

We can try different location path as well. For test let’s consider another source location where we will be having a word file.

As we can see, the file doesn’t have any data so the size is again showing as 0 KB.

Example 2.9

And the destination folder will be Output Location folder which is under Input Location folder. If we see inside the file, there is no data available.

Example 2.10

Now we will replace the source and destination in variables FirstLocation and Second Location respectively followed by the file name and its extension.

Code:

Sub VBA_Copy2()

Dim FirstLocation As String
Dim SecondLocation As String

FirstLocation = "D:VPB FileApril FilesNew ExcelTest Case.docx"
SecondLocation = "D:VPB FileApril FilesFinal locationTest Case.docx"

FileCopy FirstLocation, SecondLocation

End Sub

VBA Copy File Example 3

Now run the code.

We will see, the Test word file is now copied from the Input Location folder to Output location folder with the same size which is 0 KB.

VBA Final Output of Copy file

Pros of FileCopy In VBA

  • It can be used for copying more than 1 file in one shot.
  • It takes a similar amount of time for 10 files as it takes for copying one file.
  • We can use any extension file type which we want to copy.

Things to Remember

  • Always put the file name and its extension at the end of the location name.
  • Quote the destination and source location links into inverted commas.
  • Once done, save the code in Macro enable excel to use and retain the code for future purpose.
  • Always grant the permission to code so that it could copy the file from the source location and paste it in a destination location.

Recommended Articles

This is a guide to FileCopy in VBA. Here we discuss how to Copy an Excel file using VBA Code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA XML
  3. VBA Transpose
  4. VBA RGB

Копирование и перемещение файлов в VBA Excel с помощью методов CopyFile и MoveFile объекта FileSystemObject. Синтаксис, параметры, примеры.

Копирование файлов

Метод CopyFile

CopyFile – это метод объекта FileSystemObject, который копирует один или несколько файлов из одного расположения в другое.

Синтаксис

object.CopyFile source, destination, [overwrite]

Параметры

Параметр Описание
object Переменная, возвращающая объект FileSystemObject. Обязательный параметр.
source Строковое выражение, задающее полное имя файла, который требуется скопировать в другое расположение. Для копирования нескольких файлов используются подстановочные знаки. Обязательный параметр.
destination Строковое выражение, задающее конечное расположение, куда требуется скопировать файл (файлы) из элемента source. Подстановочные знаки не допускаются. Обязательный параметр.
overwrite Логическое значение, которое указывает, требуется ли перезаписывать существующие файлы в конечном расположении. True – файлы будут перезаписаны, False – перезапись не выполняется. Необязательный параметр, по умолчанию – True.

Если копируемый файл с полным именем source не существует, будет сгенерирована ошибка.

При копировании одного файла методом CopyFile допустимо в параметре destination указать другое собственное имя файла, тогда скопированный файл будет сохранен под новым именем. В том числе, можно изменить и расширение файла.

Примеры

Пример 1
Копирование одного файла в другое расположение с проверкой его существования:

Sub Primer1()

Dim fso As Object

‘Присваиваем переменной fso ссылку

‘на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

    ‘Проверяем существование копируемого файла

    If Dir(«C:Папка 1test1.txt») <> «» Then

        ‘Если файл существует, копируем его в другую папку

        fso.CopyFile «C:Папка 1test1.txt», «C:Папка 2«

    End If

End Sub

Пример 2
Наглядный, но неправильный пример по копированию одного файла в другую папку со сменой собственного имени, включая расширение:

Sub Primer2()

Dim fso As Object

Set fso = CreateObject(«Scripting.FileSystemObject»)

    If Dir(«C:Папка 1test1.txt») <> «» Then

        ‘Копируем файл в другую папку со сменой имени, включая расширение

        fso.CopyFile «C:Папка 1test1.txt», «C:Папка 2test2.xlsx»

    End If

End Sub

Пример назван неправильным, так как у скопированного файла меняется только расширение с .txt на .xlsx без конвертации в другой формат. На самом деле файл так и остается текстовым, и открыть его программой Excel невозможно.

Перемещение файлов

Метод MoveFile

MoveFile – это метод объекта FileSystemObject, который перемещает один или несколько файлов из одного расположения в другое.

Синтаксис

object.MoveFile source, destination

Параметры

Параметр Описание
object Переменная, возвращающая объект FileSystemObject. Обязательный параметр.
source Строковое выражение, задающее полное имя файла, который требуется переместить в другое расположение. Для перемещения нескольких файлов используются подстановочные знаки. Обязательный параметр.
destination Строковое выражение, задающее конечное расположение, куда требуется переместить файл (файлы) из элемента source. Подстановочные знаки не допускаются. Обязательный параметр.

Если перемещаемый файл с полным именем source не существует, будет сгенерирована ошибка. Ошибка произойдет и в том случае, если одноименный файл в расположении destination уже имеется.

Примеры

Пример 3
Перемещение одного файла без проверки его существования:

Sub Primer3()

Dim fso As Object

‘Присваиваем переменной fso ссылку

‘на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Завершаем программу, если произойдет ошибка

On Error Resume Next

‘Перемещаем файл в другую папку

fso.MoveFile «C:Папка 1Документ 1.docx», «C:Папка 2«

End Sub

Обработчик ошибок On Error Resume Next необходим для того, чтобы корректно завершить программу, если перемещаемый файл не существует, или он уже есть в папке назначения, в результате чего будет сгенерирована ошибка.

Пример 4
Перемещение нескольких файлов из одного расположения в другое:

Sub Primer4()

Dim fso As Object

Set fso = CreateObject(«Scripting.FileSystemObject»)

On Error Resume Next

‘Перемещаем файлы в другую папку

fso.MoveFile «C:Папка 1Документ*», «C:Папка 2«

End Sub

В результате работы этого кода VBA Excel в новое расположение будут перемещены все файлы начинающиеся с подстроки «Документ».

Знаки подстановки

  • Звездочка (*) – заменяет любое количество символов или ни одного.
  • Вопросительный знак (?) – заменяет один символ или ни одного.

Знаки подстановки позволяют создать шаблон, по которому можно скопировать или переместить сразу несколько файлов.

Примеры

Примеры шаблонов с подстановочными знаками:

Все файлы Word, включая файлы с расширениями .doc и .dot:
"C:Папка 1*.do??"

Файлы Word, кроме файлов с расширениями .dot, .dotx и .dotm:
"C:Папка 1*.doc?"

Все файлы с подстрокой «01.2020» в собственном имени:
"C:Папка 1*01.2020*"

VBA FileCopy function in Excel is categorized as a File and Directory function. This built-in VBA FileCopy function copies a file from the source directory to the destination directory. If you use FileCopy function on a currently open file, returns an error.

This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA FileCopy Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the FileCopy function, where we can use this FileCopy Function and real-time exampleS in Excel VBA.

Table of Contents:

  • Overview
  • Syntax of VBA FileCopy Function
  • Parameters or Arguments
  • Where we can apply or use VBA FileCopy Function?
  • Example 1: Copy file from source location to destination location
  • Example 2: Copy opened file from source location to destination location
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the FileCopy Function in VBA is

FileCopy(Source,Destination)

Parameters or Arguments:

The FileCopy function has two arguments in Excel VBA.
where
Source: It is a mandatory string parameter. The source argument represents the source file path that you want to copy. It may include folder or directory or drive.
Destination: It is a mandatory string parameter. The destination argument represents the destination file path that you want to copy the file to. It may include folder or directory or drive.

Where we can apply or use VBA FileCopy Function?

We can use this FileCopy Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Copy file from source location to destination location

Here is a simple example of the VBA FileCopy function. This below example copies file from specified source location to specified destination location. Now same file file is available in two different locations.

'Copy file from source location to destination location
Sub VBA_FileCopy_Function_Ex1()
    
    Dim sSourceFile As String
    Dim sDestinationFile As String
    
    sSourceFile = "C:VBAF1VBA FunctionsVBA Text FunctionsVBA Functionsa.xlsm"
    sDestinationFile = "C:VBAF1VBA FunctionsVBA Functionsa.xlsm"
    
    FileCopy sSourceFile, sDestinationFile

    MsgBox "Successfully file Copied.", vbInformation, "VBA FileCopy Function"

End Sub

Output: Here is the screen shot of the first example output.
VBA FileCopy Function

Example 2: Copy opened file from source location to destination location

Here is a simple example of the VBA FileCopy function. This below example tries to copy a file from source location to destination location. But it returns an error. Because the file is opened.

'Copy opened file from source location to destination location
Sub VBA_FileCopy_Function_Ex2()
    
    Dim sSourceFile As String
    Dim sDestinationFile As String
    
    sSourceFile = "C:VBAF1VBA FunctionsVBA Text FunctionsVBA Function Example File.xlsm"
    sDestinationFile = "C:VBAF1VBA FunctionsVBA Function Example File.xlsm"
    
    FileCopy sSourceFile, sDestinationFile
   
End Sub

Output:Here is the screen shot of the second example output.
VBA FileCopy Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Visual Basic gives us access to parts of the Windows environment; therefore, there are lots of file-based activities we can achieve with VBA. One of these is to use VBA to copy a file.

In this post, we look at 5 examples of how to achieve this.

In this post, we use the basic FileCopy method. For more advanced options, we can use the File Systems Options.

Example 1: Copy a file

The example below copies Example File.xlsx from C:UsersmarksDocuments to C:UsersmarksDocumentsTest.

Sub VBACopyFile()

FileCopy "C:UsersmarksDocumentsExample File.xlsx", _
    "C:UsersmarksDocumentsTestExample File.xlsx"

End Sub

Note: In this example, the file name is unchanged.

Example 2: Copy a file using variables

In Example 1, the file names were included within the FileCopy statement. However, they can also be provided as variables.

In the code below:

  • The variables are declared (i.e., created)
  • Values are assigned to the variables
  • The variables are used in the FileCopy statement
Sub VBACopyFileVariables()

'Declare variables
Dim copyFromFile As String
Dim copyToFile As String

'Assign values to variables
copyFromFile = "C:UsersmarksDocumentsExample File.xlsx"
copyToFile = "C:UsersmarksDocumentsExample File Copied.xlsx"

'Use variables in the FileCopy statement
FileCopy copyFromFile, copyToFile

End Sub

Note: In this example, the file is not copied to a new location, but is renamed from Example File.xlsx to Example File Copied.xlsx

Example 3: Copy a file based on cell values

In this example, we copy a file using file paths contained in cell values.

Look at the screenshot below. Cell C2 contains the current file path and Cell C4 contains the path to which the file is to be copied.

VBA copy file using cell values

We can run the following macro to rename a file using these cell values.

Sub VBACopyFileSheetNames()

FileCopy ActiveSheet.Range("C2"), _
    ActiveSheet.Range("C4")

End Sub

Note: In this example, the file is copied to a new folder and also renamed from Example File.xlsx to Example File Copied.xlsx

Example 4: Check file existence before VBA copy

The FileCopy command will happily overwrite a file without showing any errors. Therefore, it is a good idea to check if a file already exists before copying over it.

The code below checks for the existence of a file in the target location. If a file exists, a message box with a Yes/No options appear. Clicking No exists the macro.

Sub VBACheckTargetFileCopyFile()

'Declare variables
Dim copyFromFile As String
Dim copyToFile As String
Dim msgBoxAnswer As Long

'Assign variables to file names
copyFromFile = "C:UsersmarksDocumentsExample File.xlsx"
copyToFile = "C:UsersmarksDocumentsTestExample File Copied.xlsx"

'Check if the file already exists
If Dir(copyToFile) <> "" Then

    'Display message box and capture answer
    msgBoxAnswer = MsgBox(Prompt:="File already exists in that location." & _
        vbNewLine & "Do you wish to overwrite it?", Buttons:=vbYesNo, _
        Title:="Copying file")

    'If answer is No, the exist the macro
    If msgBoxAnswer = vbNo Then

        'Exit the macro
        Exit Sub

    End If

End If

'File does not exist or Yes clicked so continue
FileCopy copyFromFile, copyToFile

End Sub

Example 5: Avoiding errors when copying files

Copying files can trigger errors; the errors are outlined in the section below. The following code builds on Example 4 and also provides an error message box if any errors occur.

Sub VBAAdvancedCopyFile()

'Declare variables
Dim copyFromFile As String
Dim copyToFile As String
Dim msgBoxAnswer As Long

'Assign variables to file names
copyFromFile = "C:UsersmarksDocumentsExample File.xlsx"
copyToFile = "C:UsersmarksDocumentsTestExample File Copied.xlsx"

On Error Resume Next

'Check if the file already exists
If Dir(copyToFile) <> "" Then

    'Display message box and capture answer
    msgBoxAnswer = MsgBox(Prompt:="File already exists in that location." & _
        vbNewLine & "Do you wish to overwrite it?", Buttons:=vbYesNo, _
        Title:="Copying file")

    'If answer is No, the exist the macro
    If msgBoxAnswer = vbNo Then

        'Exit the macro
        Exit Sub

    End If

End If

'File does not exist or Yes clicked so continue
FileCopy copyFromFile, copyToFile

'Display message if error occured
If Err.Number <> 0 Then
    MsgBox Prompt:="Unable to copy file", Buttons:=vbOK, _
        Title:="Copy file error"
End If

'Turn error checking back on
On Error GoTo 0

End Sub

Possible errors

Copying a file during automation can cause errors. Below are some of the common errors from the VBA copy file process.

Copying a file that does not exist triggers an error: Run-time error’53’: File not found.

VBA Rename File error

Copying a file to a file location that is locked (i.e., another user has the file open) triggers an error: Run-time error ’70’: Permission denied

Copying to a file which is already opened

Notes on copying files

To finish off this post, there are just a few things to make you aware of:

  • We have used Excel workbooks in the examples, but we can use any file type.
  • FileCopy cannot copy complete folders, only files.
  • The FileCopy command is core Visual Basic code. We find this code in other applications windows applications such as Word and PowerPoint.
  • Check out this post for more example codes to manage files and folders: VBA code to copy, move, delete and manage files.

Also, check the VBA code library for hundreds of reusable code snippets.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Home / VBA / How to Copy an Excel File (Workbook) using VBA – Macro Code

You can use a VBA code to copy a file (workbook) from one folder to another or you can also copy a file to the same folder using a different name.

In this tutorial, we’re going to see how we can write code for both ways. Here you need to use the FileSystemObject that helps to access files and folders in Windows.

Copy an Excel File to a Separate Folder

Sub myMacro()

Dim myFile As Object
Set myFile = CreateObject("Scripting.FileSystemObject")
Call myFile.CopyFile("C:UserspuneetDesktopfoldertest-file.xlsx", "C:UserspuneetDesktop", True)

End Sub

To write the above code:

copy-an-excel-file-to-separate-folder
  1. First, you need to declare a variable.
  2. Then, you need to specify the FileSystemObject to the variable you have just defined.
  3. Next, you need to define the source location in the “CopyFile” method.
  4. In the end, define the folder location where you want to paste it.

When you run this macro, it copies the Excel workbook “text-file” from the folder and pastes it to the location that we have specified in the code.

specify-the-filesystemobject

Copy a File and Rename

When you try to copy and paste a file on the same location there are high chances that VBA shows you an error. In this situation, the best way is to rename the file while copying it.

Call myFile.CopyFile("C:UserspuneetDesktopfoldertest-file.xlsx",
"C:UserspuneetDesktop", True)

Above is the line code that I used in the earlier method. Now you need to make a change in this line only. For the destination location, you need to add the file that you want to use for the new file.

Call myFile.CopyFile("C:UserspuneetDesktopfoldertest-file.xlsx", 
"C:UserspuneetDesktopfoldertest-file1.xlsx ", True)

When you run this code, it will copy the file (text-file.xlsx) from the folder and copy it to the same folder with a different name (test-file1.xlsx).

copy-a-file-and-rename
Dim myFile As Object

Set myFile = _
CreateObject("Scripting.FileSystemObject")

Call myFile.CopyFile("C:UserspuneetDesktopfoldertest-file.xlsx", _
"C:UserspuneetDesktopfoldertest-file1.xlsx", True)

End Sub

Return to VBA Code Examples

This tutorial will demonstrate how to copy a file using VBA.

VBA allows you to copy a file, using the FileSystemObject.

If you want to learn how to rename a file, you can click on this link: VBA Rename File

Copy A File / Workbook

We will show how to copy the existing file Sample file 1.xlsx in the folder VBA Folder. In this example, we won’t rename the file, just copy and overwrite it. The folder currently has only this one file:

vba copy file

Image 1. File in folder C:VBA Folder

Here is the code:

Dim oFSO As Object
 
Set oFSO = CreateObject("Scripting.FileSystemObject")
 
Call oFSO.CopyFile("C:VBA FolderSample file 1.xlsx", "C:VBA Folder", True)

You first need to create the object of the class Scripting.FileSystemObject:

Set oFSO = CreateObject("Scripting.FileSystemObject")

Then we can use the method CopyFile:

Call oFSO.CopyFile("C:VBA FolderSample file 1.xlsx", "C:VBA Folder", True)

The first parameter of the method is the source path and the second is the destination path. The third parameter is Overwrite. As we have the same source and destination paths, we need to set Overwrite to True or False. In this example, we put True, which means that the original file is overwritten.

Let’s look now what happens if we have the same destinations, but set Overwrite to False. You just need to change this line of the code:

Call oFSO.CopyFile("C:VBA FolderSample file 1.xlsx", "C:VBA Folder", True)

As a result, you will get an error as you can see in Image 2:

vba copy file error

Image 2. Error when copying the file

Copy and Rename a File

Another possible option when copying a file is to rename it. It’s similar to copying a file, but now you just need to set destination path with a different name. Here is the code:

Dim oFSO As Object

Set oFSO = CreateObject("Scripting.FileSystemObject")

Call oFSO.CopyFile("C:VBA FolderSample file 1.xlsx", "C:VBA FolderSample file Copy.xlsx")

As you can see from the last line of the code, we want to copy file Sample file 1.xlsx in the same folder and name it Sample file Copy.xlsx:

Call oFSO.CopyFile("C:VBA FolderSample file 1.xlsx", "C:VBA FolderSample file Copy.xlsx")

Now we have two files in the VBA Folder. The result of the code is in Image 3:

vba copy rename file

Image 3. Copy and rename the file

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

I have an access file that I regularly need to copy to another directory, replacing the last version.
I would like to use an Excel macro to achieve this, and would also like to rename the file in the process.

   fileName = "X:DatabaseoldName.accdb"
   copyDestination = "Y:dbstore"
   newName = "newName.accdb"

Is there an easy way of doing this?

Christopher Oezbek's user avatar

asked Jun 5, 2013 at 14:48

harryg's user avatar

2

Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you’ll need to include:

Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")

Then you could use

Call fso.CopyFile(source, destination[, overwrite] )

where source and destination are the full names (including paths) of the file.

See https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method

Darren Bartrup-Cook's user avatar

answered Jun 5, 2013 at 14:54

Bathsheba's user avatar

BathshebaBathsheba

231k33 gold badges359 silver badges477 bronze badges

3

This method is even easier if you’re ok with fewer options:

FileCopy source, destination

Bathsheba's user avatar

Bathsheba

231k33 gold badges359 silver badges477 bronze badges

answered Mar 5, 2014 at 16:23

Jon's user avatar

JonJon

1,18911 silver badges17 bronze badges

1

Понравилась статья? Поделить с друзьями:
  • Copy data to excel vba
  • Copy data from excel
  • Copy columns to rows excel
  • Copy colors in excel
  • Copy color in word