Как правильно закрыть книгу Excel — WorkBook или WorkBooks
24.12.2014, 01:13
Как правильно закрыть excel, после того как я закрываю workbook? как правильно закрыть сам excel, после того как я закрываю workbook? ObjExcel.close? не работает .
Как правильно закрыть Excel Вопрос в следующем — нужно из проги открыть книгу Excel, записать на Листе информацию и, сохранив.
Как правильно закрывать книгу Excel? Из проги открываю Xl в фоновом режиме, поработав с ним, закрываю. После необходимо открывать.
Как правильно закрыть Excel из Access97? В Access97 формирую сложным образом xls_файл. После этого Excel надо закрыть. Делаю Quit, Close,set.
24.12.2014, 09:582
Delphi
24.12.2014, 11:22 [ТС]
3
Так не работает. Выполняю в блоке try. except . вызывает исключение.
А так ExcelApp.Workbooks.Close работает. Объясните разницу между Workbook и Workbooks. Это типа закрытие активной книги или закрытие всех книг ?? И еще вопросик. Dro >
24.12.2014, 11:45
4
24.12.2014, 11:50 [ТС]
5
Не знаю тогда ) Может потому что у меня excel 2010, но Workbook вызывает исключение, а Workbooks нет и все работает нормально. Excel закрывается.
Добавлено через 1 минуту Кстати при создании книги пишу Workbooks.Add а не Workbook. А вы как ?
24.12.2014, 11:56
6
serg55, чтобы не заморачиваться попробуйте закрывать книгу так
Delphi
24.12.2014, 12:15 [ТС]
7
24.12.2014, 12:54
8
Решение
Здесь нужна поправка. ExcelApp.Workbook — такого объекта нет в объектной структуре MS Excel. В MS Excel есть тип: Excel.Workbook. Этот тип описывает отдельную рабочую книгу. А вот объект ExcelApp.Workbooks — есть. Этот объект является объектом-коллекцией, который обеспечивает доступ ко всем рабочим книгам, которые открыты в текущем сеансе работы MS Excel. И есть соответствующий тип: Excel.Workbooks. Т. е. объект типа Excel.Workbooks обеспечивает доступ к перечню объектов типа Excel.Workbook. Каждый объект типа Excel.Workbook имеет свойство Excel.Workbook.Worksheets — оно содержит ссылку на коллекцию рабочих листов книги. Тип такого объекта: Excel.Worksheets. Объект этого типа обеспечивает доступ к отдельным рабочим листам рабочей книги. А отдельный рабочий лист имеет тип Excel.Worksheet. Рабочая книга имеет ссылку на ещё одну коллекцию листов — Excel.Workbook.Sheets. Эта коллекция содержит все листы рабочей книги — рабочие листы и листы диаграмм.
Пример с пояснениями:
Delphi
24.12.2014, 12:59 [ТС]
9
24.12.2014, 13:20
10
Delphi
24.12.2014, 13:24 [ТС]
11
24.12.2014, 13:27
12
24.12.2014, 13:43 [ТС]
13
Dro > Добавлено через 3 минуты Mawrat исчерпывающе ответил <Освобождение интерфейсов. Это делается через обнуление ссылок на эти интерфейсы. Обнулить надо все ссылки на интерфейсы. Т. е., обнулить надо все соответствующие переменные: exApp, exBooks, exBook, exSheets, exSheet. Если ссылки на интерфейсы не обнулить, то объекты, связанные с этими интерфейсами, так и останутся в памяти.>
1. Если переменные exApp, exBooks, exBook, exSheets, exSheet объявлены на локальном уровне, т. е., внутри подпрограммы — метода, процедуры или функции, то вручную можно эти переменные не обнулять. Потому, что перед тем, как управление покинет тело подпрограммы, такие переменные будут автоматически обнулены кодом завершения. Такой код завершения добавляется компилятором во все подпрограммы.
2. Если переменные exApp, exBooks, exBook, exSheets, exSheet объявлены на глобальном уровне, то такие переменные надо обнулить вручную. Обнуление следует выполнить в момент, когда известно, что связанные объекты в программе больше не понадобятся.>
«How to suppress Save Changes» prompt when you close a workbook in Excel
Summary
In Microsoft Excel, you can create a Microsoft Visual Basic for Applications (VBA) macro that suppresses the Save Changes prompt when you close a workbook. This can be done either by specifying the state of the workbook Saved property, or by suppressing all alerts for the workbook.
More Information
NOTE: Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure. However, they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
To prepare for implementing either of the examples below, perform these steps first:
Start Excel and open a new workbook.
Press ALT+F11 to start the Visual Basic editor.
On the Insert menu, click Module.
Type the sample macro code into the module sheet.
Press ALT+F11 to return to Excel.
In Microsoft Office Excel 2003 and in earlier versions of Excel, choose Macro from the Tools menu, and then click Macros.
In Microsoft Office Excel 2007, click Macros in the Code group on the Developer tab.
If the Developer tab is not available, consider doing this:
a. Click the Microsoft Office Button, and then click Excel Options.
b. In the Popular category, under Top options for working with Excel, click to select the Show Developer tab in the Ribbon check box, and then click OK.
Select the macro that you want, and then click Run.
The Saved property returns the value False if changes have been made to a workbook since it was last saved.
You can use the reserved subroutine name Auto_Close to specify a macro that should run whenever a workbook is closed. In doing so, you can control how the document is handled when the user closes the documents in Excel.
Example 1: Close the workbook without saving changes
To force a workbook to close without saving any changes, type the following code in a Visual Basic module of that workbook:
When the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save.
The DisplayAlerts property of the program can be used for the same purpose. For example, the following macro turns DisplayAlerts off, closes the active workbook without saving changes, and then turns DisplayAlerts on again.
You can also use the SaveChanges argument of the Close method.
The following macro closes the workbook without saving changes:
Example 2: Close the workbook and save the changes
To force a workbook to save changes, type the following code in a Visual Basic module of that workbook:
If ThisWorkbook.Saved = False Then
ThisWorkbook.Save End If
This subprocedure checks to see if the file Saved property has been set to False. If so, the workbook has been changed since the last save, and those changes are saved.
Excel vba workbooks close
добрый день, скажите как закрыть ексель (полностью выйти) с сохранением под таким же названием и без предупреждения скажите что в этом коде не так((((
добрый день, скажите как закрыть ексель (полностью выйти) с сохранением под таким же названием и без предупреждения скажите что в этом коде не так((((
Сообщение добрый день, скажите как закрыть ексель (полностью выйти) с сохранением под таким же названием и без предупреждения скажите что в этом коде не так((((
‘ сохраняет книгу в файл С ДРУГИМ именем Excel.ActiveWorkbook.SaveAs («rl.xlsm»)
‘ сохраняет книгу в файл С ТЕМ ЖЕ именем Excel.ActiveWorkbook.Save
‘ закрывает книгу Workbooks.Close
‘ закрыть с сохранением (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close True
‘ закрыть без сохранения (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close False
‘ закрыть Excel (закроется только если в этом же Application больше нет открытых и не сохраненных книг, ‘ иначе будет запрашивать подтверждения сохранения, при .DisplayAlerts = True) Application.Quit
‘ сохраняет книгу в файл С ДРУГИМ именем Excel.ActiveWorkbook.SaveAs («rl.xlsm»)
‘ сохраняет книгу в файл С ТЕМ ЖЕ именем Excel.ActiveWorkbook.Save
‘ закрывает книгу Workbooks.Close
‘ закрыть с сохранением (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close True
‘ закрыть без сохранения (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close False
‘ закрыть Excel (закроется только если в этом же Application больше нет открытых и не сохраненных книг, ‘ иначе будет запрашивать подтверждения сохранения, при .DisplayAlerts = True) Application.Quit
‘ сохраняет книгу в файл С ДРУГИМ именем Excel.ActiveWorkbook.SaveAs («rl.xlsm»)
‘ сохраняет книгу в файл С ТЕМ ЖЕ именем Excel.ActiveWorkbook.Save
‘ закрывает книгу Workbooks.Close
‘ закрыть с сохранением (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close True
‘ закрыть без сохранения (без запроса подтверждения пользователя, даже если .DisplayAlerts = True) Workbooks.Close False
‘ закрыть Excel (закроется только если в этом же Application больше нет открытых и не сохраненных книг, ‘ иначе будет запрашивать подтверждения сохранения, при .DisplayAlerts = True) Application.Quit
Сообщение все отлично)) спасибки. вот чего я хотел)
3 Tips to Save and Close All Open Excel Workbook Files + Macro
Bottom line: Learn a few shortcuts and tips to save and close all open Excel workbooks.
Skill level: Beginner
If you use Excel all day every day like I do, then it can be easy to have a lot of workbooks open at the same time. I try to stay disciplined with this, but sometimes it’s hard. And at the end of the day, we just want to close all open workbooks and go home! So this post contains a few tips for quickly closing all open files to help beat rush hour traffic.
Tip #1: Shift + Close Window Button
The quickest way to close all open workbooks is to hold the Shift key while pressing the Close Window button. The Close Window button is the “x” in the top-right corner of the application window.
If all of the open workbooks have been saved, then they will all be closed.
If any of the open workbooks have NOT been saved, then you will be prompted to save the file. The pop-up window will appear and you will have to press Save or Don’t Save for each unsaved workbook.
The window also contains a Save All button. You can press this to Save All the unsaved workbooks in one step.
Clicking the Cancel button will cancel the entire operation and the wordbooks that are still open will remain open.
But what if we don’t want to save all or some of the open workbooks? We’ll get to that in tip #3.
Tip #2: Add the Close All Button to the Quick Access Toolbar
We can also add the Close All button to the Quick Access Toolbar (QAT) to close all open workbooks. This does the same thing as the Shift+Close Window shortcut.
The advantage here is that we can use a keyboard shortcut to press the button. The QAT buttons can be accessed with a keyboard shortcut by pressing the Alt Key and the number assigned to the button.
To add the Close All button to the QAT, open the Excel Options window (File>Options) and follow the steps on the image below.
After pressing the Close All button we will be prompted with the same window as described in tip #1.
Bonus Tip: We can also use the keyboard shortcut Ctrl+W to close a single workbook. I mentioned this tip in my post on 17 Excel shortcuts for 2017.
Tip #3: Close All Open Workbooks with a Macro
In this section I will share a few macros that can be used to close all open workbooks. The macros give us a lot more flexibility when we want to control which workbooks are saved before closing.
You can download the Excel file that contains the macros here.
Save And Close All Files Macros.xlsm (15.8 KB)
Macro to Close All Workbooks Without Saving
If we don’t want to save any of the open files, then we can use the following macro.
How does this macro work?
The macro above loops through all of the open workbooks on the computer using a For Next Loop. It uses an If statement to check if the file in the loop (wb.Name) is NOT (<>) the file that contains the code ThisWorkbook.Name.
It then uses the Workbooks.Close method (MSDN Help Page) to close the workbook. The Close method has an optional parameter to SaveChanges. We can set this to True to save changes, and False to close without saving.
Note: This macro should only be run if you are certain you don’t want to save changes to any of the open files. There is no way to undo this. You might also want to add a Yes/No Message Box prompt to warn the user before running this macro.
Macro to Save All Except New Unsaved Workbooks (Scratch Pads)
At the end of my workday I usually have a combination of some workbooks that I want to save, and some that I do NOT want to save. I often open new workbooks to use the Excel files for quick calculations. I call these “scratch pads”. I don’t necessarily want to save these, but I might want to save all other open files.
The scratch pad files have never been saved, so they don’t have a file extension yet. They are named: Book1, Book2, Book2, etc. Notice in the screenshot that there is no file extension (.xlsx, .xlsm).
So we can add an If statement to our macro to see if a file extension exists. If the file extension exists, then we will save the file. If not, then we will close without saving.
How does this macro work?
This macro is similar to the macro to close all workbooks. The difference is we use an If statement to test if the file has an extension.
The Right function is used to return the 5 characters at the end of the file name. If wb is an existing file that has already been saved, then Right(wb.Name, 5) will return “.xlsx” or “.xlsm”.
The Instr function (MSDN Help Page) is used to find a string within a string. It returns the starting character number of the string. So, if Instr finds “.xls” within “.xlsx” or “.xlsm”, it will return 1. Otherwise, it will return a 0.
The If statement checks if the return value from Instr is greater than 0, and saves changes while closing the workbook. Otherwise, changes are not saved for workbooks that do NOT contain an extension.
Macro to Save and Close All Workbook and Automatically Name Files
Sometimes we might want to save some of those new files (scratch pads), but don’t have time to go through each file and save it with a name. This is like hitting the Excel eject button when we don’t want to lose any of our work.
The following macro will save and close ALL files, and automatically name the new files that have not been saved. It puts all the new (scratch pad) files in a folder that you specify.
You can then go back to that folder when you have some free time to move and rename the files.
How does this macro work?
This macro works similar to the other two above. The only difference is that it saves the new files (scratch pads) to a folder on your computer.
To use this macro you will need to change the sPath variable to a folder on you computer. Make sure to end the file path string with a back slash.
The Workbooks.Close method has another optional parameter (Filename) that allows us to specify a file name where we want to save the file, if the file has NOT been saved yet.
If we do not use the Filename parameter, then Excel will prompt us with the Save As menu for each file. So, specifying the Filename bypasses this window and can save us a lot of time.
The value of the Filename parameter is concatenating the string for the full file path. It is also amending the current date and time to the end of the file name using the Format and Now functions. The Format function in VBA is similar to the TEXT function in Excel, and allows us to specify a number format. The Now function returns the current date and time on the user’s computer.
I recommend adding these macros to your Personal Macro Workbook so you can use them anytime. Checkout my article and video series on the personal macro workbook to learn more.
Free Webinar on Getting Started with Macros & VBA
If you are interested in learning more about macros, I’m currently running my free webinar called “The 7 Steps to Getting Started with Macros & VBA”. It’s running all this week, and it’s absolutely free to register.
During the webinar I explain why you might want to learn VBA, and a lot of the basic coding concepts that will help you get started. I jump into Excel and the VB Editor and walk through how to write and run our first macro. Even if you have been using VBA for awhile, I’m sure you will learn some new tips.
What Are Your Tips for Savings & Closing Files?
I hope those tips and macros help you end the day a little quicker. Do you have any other tips for closing files. Please leave a comment below with any suggestions or questions. Thank you!