To copy a file with VBA in Excel for Microsoft 365 on Windows, use the FileCopy statement or FileSystemObject.CopyFile. Give the code the source file path and a destination path; the destination folder must already exist.
What “copy and paste a file” means in VBA
In everyday terms, copying and pasting a file means making a second copy of it in another folder or under another name. In VBA, this is a file-system operation, not the same as copying cells in Excel. The source stays where it is, and the procedure writes a separate file at the destination.
For example, a macro might copy D:\Incoming\monthly.csv to D:\Archive\monthly.csv. You can also choose a new destination name, such as D:\Archive\monthly-backup.csv. The extension does not have to be changed, but retaining the original extension helps other programs identify the file type.
Use a file-copy method when you need to duplicate a document, image, CSV, or workbook as a file. If you mean copying cells, a worksheet, or a workbook’s contents, use Excel’s range or worksheet methods instead. Those operations work with Excel objects and are not interchangeable with copying a file through Windows.
Choose FileCopy or FileSystemObject.CopyFile
VBA provides the FileCopy statement for a straightforward copy. Its basic form is FileCopy sourcePath, destinationPath. It is suitable when the source and destination paths are known and you do not need extra file-system features.
FileSystemObject.CopyFile is useful when you want to state clearly whether an existing destination may be overwritten. It also provides methods to check whether files and folders exist. The example below uses late binding, so you do not need to add a reference to the Microsoft Scripting Runtime library in the VBA editor.
For a single, predictable copy, either approach can work. Prefer explicit checks and an overwrite choice when a macro will be reused, run on other people’s folders, or used for important files. A copy operation can replace valuable data if the destination is not what you expected.
Example: copy one file with an overwrite choice
This Windows example checks that the source file and destination folder exist before copying. The final argument, True, allows the procedure to overwrite a file with the same name in the destination folder. Change the paths to match your own folders before running it.
Before running any macro that changes files, save a separate copy of the workbook containing the code. VBA macros cannot be undone with Ctrl+Z, and the copied or overwritten file is not restored by Excel’s Undo command.
Public Sub CopyOneFile()
Dim fso As Object
Dim sourcePath As String
Dim destinationFolder As String
Dim destinationPath As String
On Error GoTo CopyError
Set fso = CreateObject("Scripting.FileSystemObject")
sourcePath = "D:\Incoming\monthly.csv"
destinationFolder = "D:\Archive"
destinationPath = destinationFolder & "\monthly.csv"
' Check the inputs before copying.
If Not fso.FileExists(sourcePath) Then
Err.Raise vbObjectError + 1000, "CopyOneFile", "Source file was not found."
End If
If Not fso.FolderExists(destinationFolder) Then
Err.Raise vbObjectError + 1001, "CopyOneFile", "Destination folder was not found."
End If
' True permits replacing a same-named destination file.
fso.CopyFile sourcePath, destinationPath, True
MsgBox "File copied to: " & destinationPath, vbInformation
Exit Sub
CopyError:
MsgBox "Copy failed: " & Err.Description, vbExclamation
End Sub
To use it, open the workbook in Excel, press Alt+F11 on Windows to open the Visual Basic Editor, and choose Insert > Module. Paste the procedure into the module, edit the two folder paths and file name, then run CopyOneFile from the editor or through Excel’s macro list. On a Mac, the Visual Basic Editor shortcut differs by keyboard and Excel setup; use Tools > Macro > Visual Basic Editor if the shortcut is unavailable. File-system access and scripting support can also differ on Mac, so test with nonessential files first.
How source and destination paths work
A path identifies where the source file is and where the copy should go. A full Windows path generally begins with a drive letter, such as C:\Users\Alex\Documents\report.xlsx, or uses a network share such as \\Server\Team\report.xlsx. The source path must include the file name and extension.
In the example, destinationFolder contains the folder, while destinationPath joins that folder with the destination file name. Keeping these values separate makes it easier to change the folder without accidentally omitting the file name. The backslash in a VBA string is not a special escape character, so a Windows path can be written with ordinary backslashes.
- Use a complete path rather than relying on the current working directory.
- Check that the destination folder exists; the sample reports an error rather than creating it.
- Make sure the account running Excel has permission to read the source and write to the destination.
- For a network location, confirm the share is connected and accessible when the macro runs.
A mapped drive such as Z: may not be available in every context, particularly when Excel is run with different credentials or through an automated process. A network share path can be more dependable in some managed environments, but it still requires access rights and a live connection.
Overwriting, renaming, and copying many files
The third argument to CopyFile controls whether an existing destination file can be replaced. In the example, True means overwrite is allowed; use False to prevent replacing a same-named file. With overwrite disabled, a collision causes the copy to fail and the error handler displays the problem. That is often safer when preserving prior files matters.
To give the copy a different name, change only the destination file name. For instance, setting destinationPath to D:\Archive\monthly-copy.csv preserves the original and creates a clearly named duplicate. If you want dated backups, build the new name using a date value, while ensuring the resulting name is valid and does not accidentally collide with another file.
For batches, FileSystemObject can copy a set of files matching a pattern, but wildcards need careful handling. A broad pattern such as *.* may include files you did not intend to copy. Start by testing a narrow pattern, verify the destination contents, and consider logging each file copied and each failure. Do not assume that one successful copy means every file in a batch succeeded.
Common errors and how to troubleshoot them
A “file not found” or similar error usually means the source path is misspelled, the file was moved, or the drive is unavailable. Check the full path in File Explorer and confirm that the extension is included. Windows may hide known file extensions, so a visible name can differ from the actual name on disk.
A destination-folder error means the target directory does not exist or the path is incorrect. The sample intentionally checks the folder and stops. If your workflow should create folders, add and test folder-creation logic separately rather than assuming that CopyFile will create missing directories.
Access-denied errors can result from permissions, a read-only location, security software, or a file being held open in a way that prevents the operation. A file open in Excel or another program may also interfere, depending on how that program has opened it. Close the source or destination file where practical, check permissions, and try a safe test folder.
If Excel reports that it cannot create the object, the scripting component may be unavailable or restricted by the computer’s configuration. The late-bound example avoids setting a reference in the editor, but it still relies on the Windows scripting component. On Mac, Windows-specific scripting support and file paths are not a drop-in match; consider VBA’s built-in FileCopy statement or a platform-appropriate method, and validate behavior on the actual Mac version in use.
File copying versus copying Excel content
Copying an entire .xlsx or .xlsm file creates a second file, including its sheets and other saved workbook content. It does not selectively copy a range, and it does not merge the copied file’s cells into the workbook that runs the macro. If the goal is to duplicate a worksheet inside the same open workbook, use the worksheet’s Copy method. If the goal is to transfer cell values or formatting, copy a range instead.
There is an important practical distinction: copying a workbook file while it is open may produce an incomplete or out-of-date copy, depending on when Excel has saved changes and how the file is being accessed. If the copy must contain the latest edits, save the workbook first. For a reliable backup, close the file before copying when possible, or use a deliberate Excel workflow that saves the current workbook and then makes the file copy.
Safety and good macro practices
A macro that writes to the file system deserves the same care as one that edits workbook data. Verify the source and destination before enabling overwrite, and test first with disposable files. If a destination file is important, keep a separate backup rather than expecting VBA or Excel Undo to recover it.
- Use explicit, reviewed paths instead of constructing a destination from untrusted cell text.
- Choose overwrite behavior intentionally; do not use
Trueautomatically for archives or user-selected folders. - Show a clear completion or failure message, and consider recording the full paths for batch operations.
- Run macros only from workbooks you trust. Do not lower Excel’s macro security settings just to run unknown code.
- For important copies, verify the destination file exists and, where appropriate, compare file size or open the copy to confirm it is usable.
To save macro code, use an Excel macro-enabled workbook (.xlsm) rather than saving it as a standard .xlsx file, which does not retain VBA code. This is separate from the file being copied: the macro workbook and the source file can have different formats and locations.
Frequently Asked Questions
Can VBA copy a file without opening it in Excel?
Yes. FileCopy and FileSystemObject.CopyFile operate on file paths, so the file does not need to be opened as an Excel workbook. The macro still needs permission to access the source and destination.
Does VBA copy and paste also delete the original?
No. A copy leaves the source in place. Moving a file is a different operation and should be handled separately; do not delete the source unless you have verified the destination copy and intentionally want to remove it.
Can I copy a file to a folder that does not exist?
Not with the sample as written. It checks for the destination folder and stops if it is missing. Create the folder first, or add tested folder-creation code before calling the copy method.
How do I stop the macro from overwriting a file?
In the example, change the last argument of fso.CopyFile from True to False. Then an existing file with the same destination name causes the operation to fail rather than replace it.
Can I use the same VBA code on Mac?
Not necessarily. Excel for Mac supports VBA, but Windows paths and the Windows scripting component used by FileSystemObject are not universally interchangeable with Mac file access. Test with a harmless file and use a method supported by the specific Mac Excel environment.
Related
- Microsoft Excel: How to Remove Duplicate Rows Safely
- Microsoft Excel Goal Seek: How It Works and How to Use It
- Microsoft Excel Group Rows: How It Works and When to Use It
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Find Last Column With Data: Reliable VBA MethodsTo find the last column containing a value or formula anywhere on a worksheet, use VBA’s Range.Find method…
- Excel VBA: Add a New Worksheet With a Specific NameIn Excel VBA, add a worksheet with Worksheets.Add, then set its Name property. For example, the key steps…
- Excel VBA: Check Whether a String Is Empty or BlankIn Excel VBA, use Len(text) = 0 to check whether a string has no characters. If you also…
- Outlook Macros: How to Enable Them Safely in Classic OutlookTo enable VBA macros in classic Outlook for Windows, open File > Options > Trust Center > Trust…
- Excel UserForm Keeps Changing Size? Causes and FixesAn Excel UserForm usually changes size because VBA or its AutoSize setting changes its dimensions, or because Windows…
- Excel VBA Sort Order: Ascending, Descending, and CustomIn Excel VBA, set a sort field’s Order to xlAscending or xlDescending to choose its direction. For a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.