Clif McIrvin
New Member
- Joined
- Dec 22, 2023
- Messages
- 11
- Office Version
- 365
- 2016
- Platform
- Windows
I added code to my personal macro workbook to save a copy before saving changes.
The code is working as intended, but I have discovered that the new changes are not getting saved.
That is, I'm getting a timestamped copy of the original workbook, but the new changes are not getting saved.
I'm hoping someone can point out what my problem is.
My first thought was that the file system object .CopyFile method was changing the Cancel value, but setting Cancel=False before exit did not solve the problem.
Here is my code:
And the file system object call:
I'm running Microsoft® Excel® for Microsoft 365 MSO (Version 2312 Build 16.0.17126.20190) 64-bit
The code is working as intended, but I have discovered that the new changes are not getting saved.
That is, I'm getting a timestamped copy of the original workbook, but the new changes are not getting saved.
I'm hoping someone can point out what my problem is.
My first thought was that the file system object .CopyFile method was changing the Cancel value, but setting Cancel=False before exit did not solve the problem.
Here is my code:
VBA Code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
With Application
.ScreenUpdating = True
.DisplayStatusBar = True
.StatusBar = "Saving " & ThisWorkbook.Name & "..."
End With
' create copy of thisworkbook with timestamp
' S:\QC\Excel\XLSTART --} S:\QC\Excel
v = Copy_File(ThisWorkbook.FullName, _
Replace(ThisWorkbook.FullName, "\XLSTART", "", Count:=1) _
& Format(Now, "yyyy-mm-dd_hh-nn-ss"))
If v <> True Then
MsgBox "Error " & v & Error(v) & vbCrLf & _
"Unable to copy " & ThisWorkbook.FullName, vbCritical + vbOKOnly, _
"VBA Code Backup Error"
End If
Application.StatusBar = False 'return control to Excel
Cancel = False
End Sub
VBA Code:
Public Function Copy_File(srcFilePath As String, _
destFilePath As String, _
Optional overwrite As Boolean = False) As Variant
If fso Is Nothing Then ' fso is a global variable
Set fso = GetFileSystemObject()
End If
Err.Clear
On Error Resume Next
fso.CopyFile srcFilePath, destFilePath, overwrite
Copy_File = Err.Number
On Error GoTo 0
If Copy_File = 0 Then
Copy_File = True
End If
End Function