Hello,
I have code designed to create an archive of my main sheet (as a .xlsx) by copying the sheet > saving the copied sheet in a new workbook > doing things to the sheet within the new workbook > saving and closing new workbook then continuing the rest of my code.
Everything works as coded except when the user selects (or keeps selected) the same file location, in the SaveAs dialog, that the original file (with the running VBA) is in. It returns a «Method ‘SaveAs’ of object ‘_Workbook’ failed» error.
I created an «If» check to see if the selected file location from the SaveAs dialog is the same as the file location of the original and was able to create an error handler (avoid the error), but not an error solution. I want to default to the same file location as the original, and regardless I want the user to be able to save into the same file location, especially since that is a very typical thing to do.
Line (59) with error 1004:
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook
ShiftYear (what code is in) and PleaseWait are userforms, and «Troop to Task — Tracker» is the sheet I’m copying.
Code with error:
'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range
'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
For Each Sheet_Archive In ThisWorkbook.Sheets
Select Case Sheet_Archive.CodeName
Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
ShVal = Sheet_Archive.Name
If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
With ObFD
.Title = "Archive Year(s) - Personnel Tracker"
.ButtonName = "A&rchive"
.InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
.FilterIndex = 1 'File Type (.xlsx)
.AllowMultiSelect = False
.InitialView = msoFileDialogViewDetails
.Show
If .SelectedItems.count = 0 Then
MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
Exit Sub
Else
PathAndFile_Name = .SelectedItems(1)
End If
End With
Application.DisplayAlerts = False
'Load year to be archived:
Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
Worksheets("Formula & Code Data").Range("I13").Value = "No"
Call Load_Year.Load_Year
'Copy Troop to Task - Tracker sheet into new workbook and format:
PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
DoEvents
File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate
'<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>
Excel.Workbooks(File_Name).Activate
Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
Application.DisplayAlerts = True
End If
End Select
If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
And ShVal <> ShiftYear.Shift_3.Value Then
PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
DoEvents
Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
DoEvents: End If
Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
'Do Nothing
End If 'Archive <=5 year(s) data externally - END
'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
Code with error handler:
'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range
'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
For Each Sheet_Archive In ThisWorkbook.Sheets
Select Case Sheet_Archive.CodeName
Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
Archive_Error:
ShVal = Sheet_Archive.Name
If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
With ObFD
.Title = "Archive Year(s) - Personnel Tracker"
.ButtonName = "A&rchive"
.InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
.FilterIndex = 1 'File Type (.xlsx)
.AllowMultiSelect = False
.InitialView = msoFileDialogViewDetails
.Show
If .SelectedItems.count = 0 Then
MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
Exit Sub
Else
PathAndFile_Name = .SelectedItems(1)
End If
End With
Application.DisplayAlerts = False
'Load year to be archived:
Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
Worksheets("Formula & Code Data").Range("I13").Value = "No"
Call Load_Year.Load_Year
'Copy Troop to Task - Tracker sheet into new workbook and format:
PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
DoEvents
File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
If PathAndFile_Name = ThisWorkbook.Path & "" & File_Name Then 'Error handler
Archive_Error_Actual:
MsgBox "You cannot save into the same location as this Tracker, in this version. Please select a different file location." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'UPDATE MESSAGE AND FIGURE OUT WAY TO FIX RUNTIME ERROR WHEN SAVING TO SAME LOCATION AS THE TRACKER!!!
ActiveWorkbook.Close savechanges:=False
GoTo Archive_Error
End If
On Error GoTo Archive_Error_Actual
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate
'<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>
Excel.Workbooks(File_Name).Activate
Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
Application.DisplayAlerts = True
End If
End Select
If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
And ShVal <> ShiftYear.Shift_3.Value Then
PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
DoEvents
Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
DoEvents: End If
Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
'Do Nothing
End If 'Archive <=5 year(s) data externally - END
'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
Any solution to this is much appreciated!
As Hugo stated, it could be an issue with the mapped drive. I prefer to use the full UNC path (\Thismachine…), in case the workbook gets used on a machine that doesn’t have the mapped drive set up.
I thought the missing extension could be the problem, but I just tested it in Excel 2013 and it automatically added .xlsx to the filename.
The issue is probably due to the wbNew
reference. It’s completely unnecessary and should not be combined with ActiveWorkbook
. Basically, you should have either a reference to a workbook, or use the predefined ActiveWorkbook
reference. I’d also recommend using ThisWorkbook
instead, since the user might click on another book while code is running.
Public Sub Copy_Save_R2()
Dim wbNew As Workbook
Dim fDate As Date
fDate = Worksheets("Update").Range("D3").Value
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:="Q:R2 Portfolio Prints#Archive - R2 PortfolioR2 Portfolio - CEC A " & Format(fDate, "mm-dd-yyyy") & ".xlsx"
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Update").Activate
End Sub
Edit: Added Application.DisplayAlerts
commands to prevent any Save popups, such as using .xlsx instead of .xlsm, and overwriting an existing copy.
Edit 2018-08-11: Added escape backslashes to fix UNC path display. Added strike-through to inaccurate statement about the With
statement (see comments below). Basically, since nothing between With
and End With
begins with a .
, the statement isn’t doing anything at all.
xseed Пользователь Сообщений: 15 |
#1 05.08.2016 17:50:04 Добрый день! Есть файл xls2txt с макросом, экспортирующий другой файл xls в текст:
при попытке выполнить который выдается это сообщение: Run-time error ‘1004’: Method ‘Saveas’ of object ‘_workbook’ failed Debug переходит на строку
Суть проблемы в том, если файл 1.xls не запаролен, он отрабатывает успешно, без ошибок. Но когда я пытаюсь запустить файл, имеющий запароленный макрос, вываливается эта ошибка. При этом, если сохранять вручную, никаких проблем не возникает. Проблемный файл 1.xls прилагаю. Прикрепленные файлы
Изменено: xseed — 05.08.2016 18:07:23 |
||||
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
Тут все просто. Вы пытаетесь сохранить файл, который уже открыт под тем же именем самим Excel. Поэтому VBA и генерирует ошибку — файл занят процессом и не может быть перезаписан. Это недопустимо. Сохраняйте либо в другую папку, либо под другими именем. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
xseed Пользователь Сообщений: 15 |
#3 05.08.2016 17:59:05
Я открываю файл xls2txt.xls. Выполняю в нем макрос1. Открывается файл 1.xls, сохраняется как 1.txt. Где тут сохранение под тем же именем? Имя то же. но расширение txt. причем, когда я делал запись макроса, excel спрашивал меня. что файл 1.txt уже существует. заменить? Я согласился, нажав Да. Изменено: xseed — 05.08.2016 17:59:30 |
||
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#4 05.08.2016 18:02:04 Да, проглядел расширение. Сказывается, видимо, пятница
P.S. Оформляйте код соответствующим тегом(<…>), а не шрифтом. Так нагляднее будет. Изменено: The_Prist — 05.08.2016 18:02:36 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
xseed Пользователь Сообщений: 15 |
The_Prist
, нет, файл 1.txt тут ни причем. Если вы выполните мой макрос с обычным xls файлом, никаких ошибок не возникнет, файл сохранится как txt, даже если он существует. Проблема возникнет, только если выполнить макрос с прикрепленным файлом 1.xls (причем его надо поместить в каталог C:nnCronthebat!) PS: прикрепил файл с макросом xls2txt.xls Изменено: xseed — 05.08.2016 18:12:04 |
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
Пароль к проекту какой? Может там еще какое событие срабатывает. Изменено: The_Prist — 05.08.2016 18:17:59 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
xseed Пользователь Сообщений: 15 |
Это не мой файл, пароля не знаю. Изменено: xseed — 05.08.2016 18:29:52 |
xseed Пользователь Сообщений: 15 |
А можно тогда, если уж макрос не получается выполнить на запаролленом файле, не выполнять его вообще? То есть, можно ли предварительно перед выполнением макроса проверить файл на защиту и если она установлена — не выполнять макрос? Как это сделать? Изменено: xseed — 05.08.2016 18:33:47 |
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#9 05.08.2016 18:32:39 Тогда сделайте так:
больше одного листа все равно не сохраните в txt Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
xseed Пользователь Сообщений: 15 |
#10 05.08.2016 18:40:31
Спасибо! Изменено: xseed — 05.08.2016 18:40:53 |
||
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#11 05.08.2016 18:44:31 Эта команда копирует один(в данном случае первый) лист в новую книгу. Книга создается автоматически. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
- Remove From My Forums
-
Question
-
Hello,
I am getting error 1004 — «SaveAs method of Workbook class failed» — from Workbook.SaveAs method. The error occurs regularly under specific conditions described below.My application (MyApp) creates an instance of Excel.Application ActiveX object and after adding a workbook to the Excel.Application object and filling in its sheet saves the workbook by calling the SaveAs method. MyApp process gets created by a scheduler
application (SchedApp) which can run as a Windows service or a standard application.If MyApp is spawned by SchedApp running as a Windows service, the call to the Workbook.SaveAs method fails returning 1004 — «SaveAs method of Workbook class failed».
If MyApp is spawned by SchedApp running as a standard application the call to Workbook.SaveAs method succeeds and produces .xsls file.Following is the list of tests I have made so far to find out the cause of the SaveAs failure:
1) SchedApp as a service runs under Local System account (NT AUTHORITYSYSTEM). I changed the account under which the service runs to an account which belongs to Administrators group. The new account was the same account under which SchedApp runs as
a standard application when call to the SaveAs method succeeds. SaveAs method failed anyway.2) Excel.Application and other Excel ActiveX objects are hosted by out-of-process COM server (EXCEL.EXE). This fact made me believe the cause of the SaveAs error is in privileges granted to the EXCEL.EXE out-of-process server which are too low to enable
the Workbook instance to write into the output path. In order to verify I created my own out-of-process COM server whose test object creates a file named identically to the .xsls file and in the same path as the path of .xsls file SaveAs is supposed to create.
I updated MyApp’s code to create an instance of the test object and attempt to create the output file. The test object successfully created and wrote arbitrary text to the .xsls file even if MyApp was spawned by SchedApp running as a service.3) I changed the output path where SaveAs is supposed to create .xsls file to the temporary file folder specific for the account under which MyApp is running. SaveAs method failed anyway.
4) I changed element in EXCELL.EXE manifest file (excel.exe.manifest) from
<requestedExecutionLevel level=»asInvoker» uiAccess=»false»>
to<requestedExecutionLevel level=»requireAdministrator» uiAccess=»false»>.
SaveAs method failed anyway.
5) In order to rule out possibility of the error being data dependent I removed the part of code in MyApp which fills in the Excel sheet so the output .xsls file would constitute an empty sheet. SaveAs method failed anyway.
6) I tested the aforementioned points (1-5) on Windows 2003 Server R2, Windows Vista, Windows 7, Windows 2012 R2. Save for Windows 2003 Server R2, the SaveAs method failed on all OSs — i.e. failed on Windows Vista, Windows 7, Windows 2012 R2. The only
exception was on Windows 2003 Server R2 where the SaveAs method succeeded no matter whether SchedApp was running as a service or a standard application.The bottom line seems to be the Workbook.SaveAs method fails whenever MyApp process gets created by SchedApp running as a service (with the exception of Windows 2003 Server R2 mentioned in point 6).
Would you know why the SaveAs method fails when SchedApp is running as a service and hot to make it work?
Thank you,
Radovan
Answers
-
-
Marked as answer by
Thursday, October 13, 2016 8:33 AM
-
Marked as answer by
Hello,
I have code designed to create an archive of my main sheet (as a .xlsx) by copying the sheet > saving the copied sheet in a new workbook > doing things to the sheet within the new workbook > saving and closing new workbook then continuing the rest of my code.
Everything works as coded except when the user selects (or keeps selected) the same file location, in the SaveAs dialog, that the original file (with the running VBA) is in. It returns a «Method ‘SaveAs’ of object ‘_Workbook’ failed» error.
I created an «If» check to see if the selected file location from the SaveAs dialog is the same as the file location of the original and was able to create an error handler (avoid the error), but not an error solution. I want to default to the same file location as the original, and regardless I want the user to be able to save into the same file location, especially since that is a very typical thing to do.
Line (59) with error 1004:
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook
ShiftYear (what code is in) and PleaseWait are userforms, and «Troop to Task — Tracker» is the sheet I’m copying.
Code with error:
'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range
'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
For Each Sheet_Archive In ThisWorkbook.Sheets
Select Case Sheet_Archive.CodeName
Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
ShVal = Sheet_Archive.Name
If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
With ObFD
.Title = "Archive Year(s) - Personnel Tracker"
.ButtonName = "A&rchive"
.InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
.FilterIndex = 1 'File Type (.xlsx)
.AllowMultiSelect = False
.InitialView = msoFileDialogViewDetails
.Show
If .SelectedItems.count = 0 Then
MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
Exit Sub
Else
PathAndFile_Name = .SelectedItems(1)
End If
End With
Application.DisplayAlerts = False
'Load year to be archived:
Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
Worksheets("Formula & Code Data").Range("I13").Value = "No"
Call Load_Year.Load_Year
'Copy Troop to Task - Tracker sheet into new workbook and format:
PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
DoEvents
File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate
'<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>
Excel.Workbooks(File_Name).Activate
Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
Application.DisplayAlerts = True
End If
End Select
If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
And ShVal <> ShiftYear.Shift_3.Value Then
PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
DoEvents
Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
DoEvents: End If
Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
'Do Nothing
End If 'Archive <=5 year(s) data externally - END
'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
Code with error handler:
'<PREVIOUS CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'''Declare variables:
'General:
Dim NewGenYear As Integer, LastGenYear As Integer, year_create_counter As Integer
NewGenYear = 0: LastGenYear = 0: year_create_counter = 0
'Personnel:
Dim cell_person As Range, cell_num As Range
Dim cell_num_default As Range
'Archive:
Dim Sheet_Archive As Worksheet, ShVal As Integer
Dim ObFD As FileDialog
Dim File_Name As String
Dim PathAndFile_Name As String
Dim Shape_Clr As Shape
Dim cell_color_convert As Range
'<A WHOLE BUNCH OF OTHER CHECKS AND CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
'Set then launch SaveAs dialog:
If ShiftYear.CheckBox5.Value = True Then 'Archive <=5 year(s) data externally - Checked:
For Each Sheet_Archive In ThisWorkbook.Sheets
Select Case Sheet_Archive.CodeName
Case Is = "Sheet4", "Sheet5", "Sheet6", "Sheet7"
Archive_Error:
ShVal = Sheet_Archive.Name
If Sheet_Archive.Range("A2").Value <> "N/A" And ShVal <> ShiftYear.Shift_3.Value Then
File_Name = "Archive " & Sheet_Archive.Name & "_" & ThisWorkbook.Name 'Set default (suggested) File Name
Set ObFD = Application.FileDialog(msoFileDialogSaveAs)
With ObFD
.Title = "Archive Year(s) - Personnel Tracker"
.ButtonName = "A&rchive"
.InitialFileName = ThisWorkbook.Path & "" & File_Name 'Default file location and File Name
.FilterIndex = 1 'File Type (.xlsx)
.AllowMultiSelect = False
.InitialView = msoFileDialogViewDetails
.Show
If .SelectedItems.count = 0 Then
MsgBox "Generation and archiving canceled. No year(s) were created, shifted, or overwritten. To continue generating without archiving, uncheck the ""Archive <=5 year(s) calendar/personnel data externally before overwriting"" box then click ""Generate"" again." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'<MY CODE THAT TURNS OFF MACRO ENHANCEMENT>
Exit Sub
Else
PathAndFile_Name = .SelectedItems(1)
End If
End With
Application.DisplayAlerts = False
'Load year to be archived:
Worksheets("Formula & Code Data").Range("I7").Value = Sheet_Archive.Name
Worksheets("Formula & Code Data").Range("I13").Value = "No"
Call Load_Year.Load_Year
'Copy Troop to Task - Tracker sheet into new workbook and format:
PleaseWait.Label2.Caption = "Creating " & Sheet_Archive.Name & " archive file ..."
DoEvents
File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "")) 'Update File Name to user's input
ThisWorkbook.Sheets("Troop to Task - Tracker").Copy
If PathAndFile_Name = ThisWorkbook.Path & "" & File_Name Then 'Error handler
Archive_Error_Actual:
MsgBox "You cannot save into the same location as this Tracker, in this version. Please select a different file location." _
, vbExclamation, "Year Shift & Creation - Personnel Tracker"
'UPDATE MESSAGE AND FIGURE OUT WAY TO FIX RUNTIME ERROR WHEN SAVING TO SAME LOCATION AS THE TRACKER!!!
ActiveWorkbook.Close savechanges:=False
GoTo Archive_Error
End If
On Error GoTo Archive_Error_Actual
ActiveWorkbook.SaveAs fileName:=PathAndFile_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate
'<ALL MY CODE THAT CHANGES THE NEW WORKBOOK>
Excel.Workbooks(File_Name).Activate
Excel.Workbooks(File_Name).Close savechanges:=True 'New workbook save and close
Application.DisplayAlerts = True
End If
End Select
If (Sheet_Archive.CodeName = "Sheet4" Or Sheet_Archive.CodeName = "Sheet5" _
Or Sheet_Archive.CodeName = "Sheet6" Or Sheet_Archive.CodeName = "Sheet7") _
And ShVal <> ShiftYear.Shift_3.Value Then
PleaseWait.Label2.Caption = "" & Sheet_Archive.Name & " archive file complete"
DoEvents
Else: PleaseWait.Label2.Caption = "Initailizing archive ..."
DoEvents: End If
Next Sheet_Archive
ElseIf ShiftYear.CheckBox5.Value = False Then 'Archive <=5 year(s) data externally - Unchecked:
'Do Nothing
End If 'Archive <=5 year(s) data externally - END
'<CONTINUING CODE THAT DOESN'T PERTAIN TO THE SAVEAS ISSUE>
Any solution to this is much appreciated!