I try to use Workbook.SaveAs method to save a new workbook with a specific name. I found it runs fine within the Application which the code run on. But caused excel crash with a new application. What's the problem? Excel 2016 on Windows 10 Pro. Codes below:
Sub test()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name1"
'above SaveAs succeed
Set wb = new_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name2"
'above SaveAs cause excel crash
End Sub
If I use SaveCopyAs
method (code below), both is fine. But I still want to know why SaveAs
caused Excel crashed.
Sub test()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveCopyAs Filename:="new_file_name1.xlsx"
'above SaveCopyAs succeed
Set wb = new_app.Workbooks.Add
wb.SaveCopyAs Filename:="new_file_name2.xlsx"
'above SaveCopyAs also succeed
End Sub
The following works for me (Excel 2013):
Option Explicit
Sub TestMe()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name11"
'above SaveAs sucessed
Set wb = new_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name22"
'above SaveAs cause excel crash
End Sub
I suppose that your problem was in app.Visible
or that you already had a file named new_file_name2
, thus it crashed. Try changing the files and always add Option Explicit
on the top of your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.