简体   繁体   中英

Close workbook and finish VBA procedure in another workbook

I use the following VBA to create a copy of the spreadsheet which is used:

Sub Files()
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\testfile.xlsm"
Workbooks.Open "C:\Users\" & Environ("Username") & "\Desktop\" & "testfile.xlsm", UpdateLinks:=False
ThisWorkbook.Close SaveChanges = False
MsgBox ("File saved successfully on desktop.")
End Sub

This code puts a copy of the Excel file on the desktop. Once this is done the new created Excel file is opened and the other one is closed.
However, the closing of the other one causes the VBA to stop as well; therefore, the MsgBox ("File saved successfully on desktop.") does not appear anymore.

How do I have to change the VBA so it continues in the new opened spreadsheet and displays the message box?

ThisWorkbook.Close SaveChanges = False closes the workbook. The VBA code is inside, thus the MsgBox does not appear.

The easiest solution is to change a bit your code like this:

MsgBox ("File saved successfully on desktop.")
ThisWorkbook.Close SaveChanges = False

To make sure that your MsgBox does not "lie", introduce Error-capture:

Sub Files()

    On Error GoTo Files_Error

    ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\testfile.xlsm"
    Workbooks.Open "C:\Users\" & Environ("Username") & "\Desktop\" & "testfile.xlsm", UpdateLinks:=False
    MsgBox ("File saved successfully on desktop.")
    ThisWorkbook.Close SaveChanges = False

    On Error GoTo 0
    Exit Sub

Files_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Files of Sub Modul1"

End Sub

If the file cannot be saved after the MsgBox , a new MsgBox would pop-up.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM