Same File Name, New Location

Muleskin57

New Member
Joined
Dec 22, 2016
Messages
23
I've created a tool to manage resources for disabled persons in a group home setting. It will be used by non-excel users mostly. I'm trying to create a macro that saves the existing file to a backup directory before exiting. Anyone have experience with this? I'm hitting my frustration point.
 

Some videos you may like

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.

Joe4

MrExcel MVP, Junior Admin
Joined
Aug 1, 2002
Messages
53,465
Office Version
365
Platform
Windows
You can use the Workbook_BeforeClose event procedure, which is VBA code that automatically run when they try to close the workbook.
We can capture the file name, and have it automatically save to some pre-determined backup location (hard-coded in the VBA code).

Paste the VBA code below in the "ThisWorkbook" module in VBA (it HAS to be in that module to work automatically).
Change the file path to wherever you want it saved.
Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    Dim buPath As String
    Dim wbName As String

'   Enter backup file path (ending in a "\")
    buPath = "C:\Temp\"

'   Capture just the name of the current file
    wbName = ActiveWorkbook.Name
    
'   Save file to backup directory
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs buPath & wbName
    Application.DisplayAlerts = True
    
End Sub
Also note that they must have Macros/VBA enabled for this code (or any automated VBA code) to work.
 

Muleskin57

New Member
Joined
Dec 22, 2016
Messages
23
That's great! If the file is to be saved on a subfolder of it's current location(subfolder named "backup"), how would I state that? Multiple locations would be using this form on a network location specific to each home. We have write only sub folders (backup) that we want to dump the file into after the month end macro runs.
 

Joe4

MrExcel MVP, Junior Admin
Joined
Aug 1, 2002
Messages
53,465
Office Version
365
Platform
Windows
If the file is to be saved on a subfolder of it's current location(subfolder named "backup"), how would I state that?
Just change this line:
Code:
buPath = "C:\Temp\"
to
Code:
buPath = ActiveWorkbook.Path & "\backup\"
 

Joe4

MrExcel MVP, Junior Admin
Joined
Aug 1, 2002
Messages
53,465
Office Version
365
Platform
Windows
You are welcome!
Glad I was able to help.
:)
 

Watch MrExcel Video

Forum statistics

Threads
1,099,647
Messages
5,469,918
Members
406,674
Latest member
melley

This Week's Hot Topics

Top