Share via

How to use batch file code in a vba module

Peter Corbally 40 Reputation points
2026-03-24T11:58:28.08+00:00

I have a batch file that copies an excel file to different hard drives as a security measure. I want to take the batch file code and drop it into an excel module, thus eliminating the need for the batch file.

Microsoft 365 and Office | Excel | For home | Windows
0 comments No comments

Answer accepted by question author

AI answer

2026-03-24T11:58:43.1633333+00:00

Use VBA’s ability to run external commands instead of the batch file. The batch logic (copying files) can be implemented directly in VBA with either Shell (to call xcopy/robocopy) or native FileCopy.

Example 1 – Call the existing batch logic via xcopy (no .bat file needed):

Sub BackupWorkbook()
    Dim src As String
    Dim dest1 As String
    Dim dest2 As String
    Dim cmd As String

    src = "C:\Path\To\Source\MyFile.xlsx"
    dest1 = "D:\Backups\MyFile.xlsx"
    dest2 = "E:\Backups\MyFile.xlsx"

    ' Copy to first drive
    cmd = "cmd /c xcopy """ & src & """ """ & dest1 & """ /Y /I"
    Shell cmd, vbHide

    ' Copy to second drive
    cmd = "cmd /c xcopy """ & src & """ """ & dest2 & """ /Y /I"
    Shell cmd, vbHide
End Sub

Adjust the paths and add more destinations as needed. This reproduces what a batch file would do, but the commands live in the VBA module.

Example 2 – Use pure VBA (no command line):

Sub BackupWorkbookVBA()
    Dim src As String
    Dim dest1 As String
    Dim dest2 As String

    src = "C:\Path\To\Source\MyFile.xlsx"
    dest1 = "D:\Backups\MyFile.xlsx"
    dest2 = "E:\Backups\MyFile.xlsx"

    FileCopy src, dest1
    FileCopy src, dest2
End Sub

To run this macro:

  1. Press Alt+F11 to open the Visual Basic Editor.
  2. Insert a new Module and paste one of the procedures above.
  3. Close the editor, then in Excel use Alt+F8 → select the macro → Run.

For reuse on any workbook, place the macro in Personal.xlsb so it is available globally, or copy the module between workbooks using the Visual Basic Editor.


References:

AI-generated content may be incorrect. Read our transparency notes for more information.

Was this answer helpful?

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.