Hello,
Briefly I have a code that creates a separate non-macro version of my workbook and saves it with a different name.
Works well when used as a normal Macro.
However, now i'm trying to get it to execute when my workbook is saved (to keep from having to press a button to save the non-macro version).
This version does not work.
It gives me the error:
Run-time error '91':
Object variable or With block variable not set.
I set my variables at the very beginning and it works as a normal macro, so what gives?
In bold is where the error occurs.
Cheers!
Briefly I have a code that creates a separate non-macro version of my workbook and saves it with a different name.
Works well when used as a normal Macro.
However, now i'm trying to get it to execute when my workbook is saved (to keep from having to press a button to save the non-macro version).
This version does not work.
It gives me the error:
Run-time error '91':
Object variable or With block variable not set.
I set my variables at the very beginning and it works as a normal macro, so what gives?
In bold is where the error occurs.
Cheers!
Code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wb As Workbook, wb2 As Workbook
Dim Path As String, WorkbookName As String, FName1 As String, FName2 As String
WorkbookName = ActiveWorkbook.Name
Path = "C:\Users\" & Environ("Username") & "\Documents\"
Set wb = ThisWorkbook
wb.Save
FName1 = Path & "Copy of " & WorkbookName
wb.SaveCopyAs (FName1) 'save copy
If InStr(WorkbookName, ".") > 0 Then
WorkbookName = Left(WorkbookName, InStr(WorkbookName, ".") - 1)
End If
FName2 = Path & WorkbookName & " " & "DASHBOARD.xlsx"
Set wb2 = Workbooks.Open(FName1)
Application.DisplayAlerts = False
[B]wb2.SaveAs FName2, xlOpenXMLWorkbook [/B] 'use copy to save macro-free workbook
wb2.Close
VBA.Kill FName1 'delete copy
Application.DisplayAlerts = True
End Sub