Close Workbooks
If you close a workbook that has unsaved changes, Excel prompts whether you want to save before closing
. This works the same way whether you close a workbook through the user interface or through code. You can turn off the prompt in code by setting the SaveChanges argument, however:
ThisWorkbook.Close True
The preceding code saves the current file, then closes it. You can just as easily discard changes by setting SaveChanges to False:
ThisWorkbook.Close False
In either case, Excel closes the workbook without displaying any prompts. You can even use Close to save a workbook to a new file, as shown here:
ThisWorkbook.Close True, "Copy of " & ThisWorkbook.Name
That’s a little unusual, but it comes in handy if you are creating workbooks from some other source, such as text or XML data, as shown by the following bold additions to the previous example:
Sub TestImportToXMLTemplate( )
Dim xmap As XmlMap, wb As Workbook
' Create a workbook using the Order template.
Set wb = Workbooks.Open(ThisWorkbook.Path & "\ch08_order.xlt")
' Get the XML Map.
Set xmap = wb.XmlMaps("Order_Map")
' Import the data.
wb.XmlImport ThisWorkbook.Path & "\ch08_2002.xml", xmap
' Save the file in Excel format and close.
wb.Close True, wb.Name
End SubIn this case, Excel creates a new workbook, imports XML data, then saves and closes the workbook. You can work through a long list of XML files this way converting them to workbooks for later use.
If you use the Close method on the Workbooks collection, Excel ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access