Vba copy file in vba in Excel

At many instances, the user may be required to copy one or more files from one location to another within the program.

This type of requirement is most seen in corporate applications where files are moved often.

The Excel VBA allows the user to move or copy file with ease without involving the manual work of opening drive folders copy, paste and so on.

The following code demonstrates the file transfer with VBA.

  1. Sub filecopy()
  2. Dim fDialog As FileDialog, result As Integer
  3. Dim sfil As String
  4. Dim fldr As FileDialog
  5. Dim sItem As String
  6. Dim FSO
  7. Set FSO = CreateObject("Scripting.FileSystemObject")
  8. Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
  9. fDialog.AllowMultiSelect = False
  10. fDialog.Title = "Select a file"
  11. fDialog.InitialFileName = "C:\"
  12. fDialog.Filters.Clear
  13. fDialog.Filters.Add "Excel files", "*.xlsx"
  14. fDialog.Filters.Add "All files", "*.*"
  15. If fDialog.Show = -1 Then
  16. MsgBox fDialog.SelectedItems(1)
  17. sfil = fDialog.SelectedItems(1)
  18. End If
  19. Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
  20. With fldr
  21. .Title = "Select a Folder"
  22. .AllowMultiSelect = False
  23. .InitialFileName = Application.DefaultFilePath
  24. If .Show <> -1 Then GoTo NextCode
  25. sItem = .SelectedItems(1)
  26. End With
  27. MsgBox "You have selected " & sItem
  28. NextCode:
  29. GetFolder = sItem
  30. Set fldr = Nothing
  31. FSO.CopyFile (sfil), sItem, True
  32. End Sub

The above code demands the user to select file to copy and destination folder and then copies the file from source to destination.

The screenshot of the editor is as shown below.

excel vba copy file in vba


You can find similar Excel Questions and Answer hereunder

1) How can I find the last used cell in a Column in VBA?

2) Vba clear the contents of an entire sheet in Excel

3) Here some explanations about XPATH. XPath is a syntax for defining parts of an XML document

4) Vba delete entire row if contains certain text in Excel

5) Here a explanation about the global seek function in VBA. Goal Seek is another tool under What If analysis that does a unique function as Scenario Manager.

6) Here an explanation about the file dialog and how to control in with VBA

7) How can I hide a sheet completely from users (the sheet should not even appear in Unhide dialog box)?

8) Vba to return week numbers in Excel

9) How can I hide all comments in my WorkSheet using VBA?

10) How can I list all files in a folder using VBA?


Here the previous and next chapter