Saving a Backup Copy of a Workbook (E033.xls)

Dave T

Board Regular
Joined
Jun 21, 2005
Messages
93
Hello MrExcel,

I have purchased a book called "Office VBA - Macros You Can Use Today" and I am having problems with one of the code examples from the book.

I have been trying to get the Excel example "Saving a Backup Copy of a Workbook" and its associated file E033.xls to save a backup copy of a file to a folder I have created on my C:\ drivework but for some reason I cannot get it to work.
I have not been using the cell on the worksheet, but have been trying to hard code the path.

I have tried in vain to contact someone via the e-mail addresses in the book without success.

I would love to post the code from the book and see if someone could find out why it is not working for me, but I am not sure about the ethics of posting the code from the book.

Any comments about how to resolve this would be appreciated.

Regards,
Dave T
 

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
Code extract:
Code:
Path = "\\Server\apps\"
Path = "C:\"
Path = Range("B1").Value
I have not tried it but would think that all you have to do is change the third line above to:
Code:
Path = "C:\MyBackupFolder"
where "C:\MyBackupFolder" needs to be the folder that you want to use.
 
Last edited:
Hello Derek,

Thanks for the reply.

Forgot to mention it before... but at work I am using Windows XP and Excel 2003 and at home Wndows 7 Home Premium and both Excel 2003 and Excel 2007.

I have tried most of the options you have suggested and many others, without the backup copy being saved anywhere that I can find it:
Code:
[COLOR=darkgreen]'Hard coded Path value[/COLOR]
[COLOR=darkgreen]'Path = "[/COLOR][URL="file://\\Server\apps\"][COLOR=darkgreen]\\Server\apps\[/COLOR][/URL][COLOR=darkgreen]"[/COLOR]
[COLOR=darkgreen]'Path = "[/COLOR][URL="file://\\Orion\ssapps\99"][COLOR=darkgreen]\\Orion\ssapps\99[/COLOR][/URL][COLOR=darkgreen] Temporary Data Storage\David\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\"[/COLOR]
Path = "C:\TIMESHEETS\"
[COLOR=darkgreen]'Path = "C:\TIMESHEETS\BACKUP FILES\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\Documents and Settings\trehearn\My Documents\BACKUP FILES\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\Documents and Settings\" & Environ("UserName") & "\Desktop\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\Documents and Settings\" & Environ("UserName") & "My Documents\BACKUP FILES\"[/COLOR]
[COLOR=darkgreen]'User inputs Path variable[/COLOR]
[COLOR=darkgreen]'Path = Range("B1").Value[/COLOR]
I have even tried coding a line like you have suggested without the 'trailing backslash' as the code later mentions.

I have used the " & Environ("UserName") & " code in other macros with success. Doing this means I do not have to hard code a specific users name.

I also have another question as to whether the file path for Windows 7 woukd be different, e.g.
Code:
[COLOR=darkgreen]'Path = "C:\Documents and Settings\" & Environ("UserName") & "\Desktop\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\Users\" & Environ("UserName") & "\Desktop\"[/COLOR]
[COLOR=darkgreen]'Path = "C:\Users\David\AppData\Roaming\"[/COLOR]
[COLOR=seagreen][COLOR=darkgreen]'Path = "C:\Users\username\AppData\Roaming\Microsoft\Windows\Templates\"[/COLOR][/COLOR]
Once again Derek...
Thanks for the reply.

Regards,
Dave T
 
I copy/pasted the path that you gave, into a copy of the workbook and it works for me.
However, I wonder if you are just doing a 'Save' instead of a 'Save As' as the code is designed to respond to.
If you look at the code in 'ThisWorkbook' it contains:
Code:
    If SaveAsUI Then
I am using Windows 7 and Excel 2010 but I would expect the code to work for all versions.
 
Last edited:
Dave -

Please feel free to post your modified code here so we can see what is happening.

Bill
 
Hello Derek,

You may very well be right regarding the 'SaveAs' comment.

But from reading the code I was under the impression that, when a user selects 'Save' the workbook was saved to a specified file path and up to 3 read only versions were also saved in the backup location.
It did not make sense to me to have to use 'SaveAs' each time to save a backup. I personally would just click 'Save' and close the workbook, which in my case would result in no backups.

Here is the code I have been trying to get to work...

Module code
Rich (BB code):
Option Explicit
Sub SaveBackup(Optional Book As Workbook)
'Call this macro from the BeforeSave event of the workbook
'Variable declaration
  Dim Path As String
  Dim FileNoExtension As String
  Dim Extension As String
  Dim TempFile As String
  Dim i As Long
'********
'>>>>>> WINDOWS XP FILE PATH OPTIONS <<<<<<
'Change the following variables
Const History As Long = 3    'Number of old versions of the
'book to save. If set to 0, no old version will be kept
'Hard coded Path value
'Path = "\\Server\apps\"
'Path = "\\Orion\ssapps\99 Temporary Data Storage\David\"
'Path = "C:\"
  Path = "C:\TIMESHEETS\"
'Path = "C:\TIMESHEETS\BACKUP FILES\"
'Path = "C:\Documents and Settings\trehearn\My Documents\BACKUP FILES\"
'Path = "C:\Documents and Settings\" & Environ("UserName") & "\Desktop\"
'Path = "C:\Documents and Settings\" & Environ("UserName") & "My Documents\BACKUP FILES\"
 
'User inputs Path variable
'Path = Range("B1").Value
'********
 
'********
'>>>>>> WINDOWS 7 FILE PATH OPTIONS <<<<<<
'Don't know if these are correct, just experimentimg as I am unsure if these are different in Windows 7
  'Path = "C:\Documents and Settings\" & Environ("UserName") & "\Desktop\"
  'Path = "C:\Users\" & Environ("UserName") & "\Desktop\"
  'Path = "C:\Users\David\AppData\Roaming\"
  'Path = "C:\Users\David\AppData\Roaming\"
  'Path = "C:\Users\username\AppData\Roaming\Microsoft\Windows\Templates\"
'********
 
  On Error GoTo err_h
'If we don't have a workbook, assume the active workbook
'If workbook isn't identified, assume the active workbook
  If Book Is Nothing Then
    Set Book = ActiveWorkbook
  End If
'Does the folder exist ?
  If Len(Dir$(PathName:=Path, Attributes:=vbDirectory)) = 0 Then
    MkDir Path
  End If
'Make sure that there is a trailing backslash
  If Right$(Path, Len(Application.PathSeparator)) <> _
     Application.PathSeparator Then
    Path = Path & Application.PathSeparator
  End If
  If History <= 0 Then
  'Don't keep a history, overwrite if the file exists
  'Continue if error occurs
    On Error Resume Next
    SetAttr PathName:=Path & Book.Name, Attributes:=vbNormal
    On Error GoTo err_h
    Book.SaveCopyAs Path & Book.Name
  'Mark it as read only
    SetAttr PathName:=Path & Book.Name, Attributes:=vbReadOnly
  Else
  'Store versions on the path
  'First, get the name of the file without the extension
    Extension = GetExtension(Book.Name)
    FileNoExtension = Left$(Book.Name, _
                            Len(Book.Name) - Len(Extension) - 1)
  'Delete the oldest version available
  'Continue if error occurs
    On Error Resume Next
    SetAttr PathName:=Path & FileNoExtension & "-" & Format$( _
                      History, "000") & "." & Extension, Attributes:=vbNormal
    Kill PathName:=Path & FileNoExtension & "-" & Format$( _
                   History, "000") & "." & Extension
    On Error GoTo err_h
  'Now rename any existing older versions
    For i = History - 1 To 1 Step -1
    'Name of the file being moved
      TempFile = Path & FileNoExtension & "-" & Format$(i, _
                                                        "000") & "." & Extension
    'Does the file exist?
      If FileExists(TempFile) Then
      'Rename it
        Name TempFile As Path & FileNoExtension & "-" & Format$( _
             i + 1, "000") & "." & Extension
      End If
    Next i
  'Finally, save the workbook!
    Book.SaveCopyAs Path & FileNoExtension & "-001." & Extension
  'Mark it as read only
    SetAttr PathName:=Path & FileNoExtension & "-001." & _
                      Extension, Attributes:=vbReadOnly
  End If
  Exit Sub
err_h:
  MsgBox "Error " & Err.Number & ", " & Err.Description, _
         vbCritical
End Sub
 
Function GetExtension(FileName As String) As String
'Variable declaration
  Dim i As Long
  For i = Len(FileName) To 1 Step -1
    If Mid$(FileName, i, 1) = "." Then
      GetExtension = Mid$(FileName, i + 1)
      Exit Function
    End If
  Next i
End Function
 
Function FileExists(sFullName As String) As Boolean
  FileExists = Len(Dir(PathName:=sFullName)) > 0
End Function

ThisWorkbook code
Rich (BB code):
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
                                Cancel As Boolean)
  If SaveAsUI Then
  'Only save backup if the workbook is being saved from Excel
    SaveBackup Me
  End If
End Sub

The code within the book and the associated file looked like a better version of what I currently using:

ThisWorkbook
Rich (BB code):
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
  Call SaveWorkbookBackup
End Sub

Module code
Rich (BB code):
Option Explicit
Sub SaveWorkbookBackup()
 'Sub SaveWorkbookBackupToFloppyA()
 'http://www.exceltip.com/exceltips.php?view=archive_showtips&ID=474
  Dim awb As Workbook, BackupFileName As String, i As Integer, OK As Boolean
  If TypeName(ActiveWorkbook) = "Nothing" Then Exit Sub
  Set awb = ActiveWorkbook
  If awb.Path = "" Then
    Application.Dialogs(xlDialogSaveAs).Show
  Else
    BackupFileName = awb.Name
    OK = False
    On Error GoTo NotAbleToSave
    If Dir("C:\Documents and Settings\trehearn\My Documents\BACKUP FILES\" & BackupFileName) <> "" Then
      Kill "C:\Documents and Settings\trehearn\My Documents\BACKUP FILES\" & BackupFileName
    End If
    With awb
      Application.StatusBar = "Saving this workbook..."
      .Save
      Application.StatusBar = "Saving this workbook backup..."
      .SaveCopyAs "C:\Documents and Settings\trehearn\My Documents\BACKUP FILES\" & BackupFileName
      OK = True
    End With
  End If
NotAbleToSave:
  Set awb = Nothing
  Application.StatusBar = False
  If Not OK Then
    MsgBox "Backup Copy Not Saved!", vbExclamation, ThisWorkbook.Name
  End If
End Sub

Maybe I have just misread the intent of the article.

Regards,
Dave T
 
Hello All,

I would still like to know if the code from the book is meant to save backup coipies each time the save button is clicked or does it only apply to SaveAs

Regards,
Dave T
 
Sorry - I have been rather busy lately and not able to get to my copy of the book.
I believe that the comment:
Code:
'Only save backup if the workbook is being saved from Excel
is incorrect. Have a look at the post at:
http://www.sqldrill.com/excel/programming-vba-vb-c-etc/300148-use-saveasui.html
If you remove:
Code:
  If SaveAsUI Then
  'Only save backup if the workbook is being saved from Excel

  End If
I would expect it to work everytime you Save or SaveAs.
 
Hello Derek,

I tried what you suggested and 'commented' out the three lines you highlighted.

Now when I select either 'Save As...' or 'Save' I get the following error message:
Error 53, File not found
Where the code says you can save three 'read only' backup versions made me think it would/should work each time you selected 'Save'

I must admit I would love to see a working file of the code from the book.

Regards,
Dave T
 
I don't know why you are getting that error.
I just tried that change myself and it works OK for me. Perhaps it is being caused by some of your other code.
There are sample files available, so you should be able to see a working file example. You will find the download link on page 5 of the book.
 

Forum statistics

Threads
1,222,731
Messages
6,167,891
Members
452,154
Latest member
lukmana_sam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top