Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim x As String
ActiveWorkbook.Save
strPath = ActiveWorkbook.Path & «Temp»
On Error Resume Next
x = GetAttr(strPath) And 0
If Err = 0 Then ‘ если путь существует — сохраняем копию книги
strdate = Format(Now, «yyyy/mm»)
ActiveWorkbook.SaveAs Filename:=strPath & strdate & «.xlsm», FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
‘Application.DisplayAlerts = True
‘Application.DisplayAlerts = false
End If
End Sub
GIG_ant не получается
се равно спрашивает заменить книгу (Да,Нет,Отмена)
закрытие екселя с сохранением и без предупреждения |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
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:
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
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.
Sub CloseBook()
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
You can also use the SaveChanges argument of the Close method.
The following macro closes the workbook without saving changes:
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
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:
Sub Auto_Close()
If ThisWorkbook.Saved = False Then
ThisWorkbook.Save End If
End Sub
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.
Need more help?
Сохранение файла рабочей книги Excel, существующего или нового, с помощью кода VBA. Методы Save и SaveAs объекта Workbook, параметр SaveChanges метода Close.
Сохранение существующего файла
Сохранить существующий открытый файл рабочей книги Excel из кода VBA можно несколькими способами. В примерах используется выражение ActiveWorkbook, которое может быть заменено на ThisWorkbook, Workbooks(«ИмяКниги.xlsx»), Workbooks(myFile.Name), где myFile — объектная переменная с присвоенной ссылкой на рабочую книгу Excel.
Простое сохранение файла после внесенных кодом VBA Excel изменений:
Сохранение файла под другим именем (исходная рабочая книга будет автоматически закрыта без сохранения внесенных изменений):
ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx» |
Сохранить файл рабочей книги можно перед закрытием, используя параметр SaveChanges метода Close со значением True:
ActiveWorkbook.Close SaveChanges:=True |
Чтобы закрыть файл без сохранения, используйте параметр SaveChanges метода Close со значением False:
ActiveWorkbook.Close SaveChanges:=False |
Сохранение файла под другим именем при закрытии рабочей книги:
ActiveWorkbook.Close SaveChanges:=True, Filename:=«C:ТестоваяНоваяКнига.xlsx» |
Если в примерах с методом Close параметр SaveChanges пропустить, будет открыто диалоговое окно с запросом о сохранении файла.
Новая книга сохраняется с указанием полного имени:
Workbooks.Add ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx» |
После этого к новой книге можно обращаться по имени: Workbooks ("НоваяКнига.xlsx")
.
Если не указать полное имя для сохраняемого файла:
Workbooks.Add ActiveWorkbook.Save |
тогда новая книга будет сохранена с именем и в папке по умолчанию, например: Книга1.xlsx, Книга2.xlsx, Книга3.xlsx и т.д. в папке «Документы».
How to allow your macro/vba code to overwrite an existing Excel file.
This allows you to do things like, export a weekly report to a specific file and have it overwrite that file each week.
The technique in this tutorial does not require any confirmation in order to overwrite the file.
Sections:
Overwrite A File Using VBA
Example
Notes
Overwrite A File Using VBA
Add these two lines to any macro to allow them to overwrite a file without having the confirmation window appear:
Add to the top of the macro:
Application.DisplayAlerts = False
Add to the bottom of the macro:
Application.DisplayAlerts = True
Application.DisplayAlerts controls if Excel will show pop-up window alert messages, such as when you go to overwrite an existing file and Excel wants to warn you about that.
When you set this value to False, these messages will not appear and, so, you won’t have to confirm anything that the macro does.
Make sure to set it back to True at the end of the macro so that Excel will function normally again after the macro has finished running.
Example
Here is a simple macro that you can use to test this out:
Sub Save_File_Overwrite()
' Save the current workbook as Test.xlsm
' 51 for regular file
' 52 for macro enabled workbook
ThisWorkbook.SaveAs "C:Test.xlsm", 52
End Sub
Run the above macro twice from a macro-enabled workbook. The second time that you run it, you will see a confirmation dialogue box asking if you want to overwrite the existing file or not.
Add the DisplayAlerts lines of code to the file and try it again:
Sub Save_File_Overwrite()
' Don't show confirmation window
Application.DisplayAlerts = False
' Save the current workbook as Test.xlsm
' 51 for regular file
' 52 for macro enabled workbook
ThisWorkbook.SaveAs "C:DirectoryTest.xlsm", 52
' Allow confirmation windows to appear as normal
Application.DisplayAlerts = True
End Sub
Now, the file will overwrite the existing file without making a mention of it.
Notes
Be careful! When you disable alerts in Excel, data can be overwritten without you knowing about it. If you have a large and complex macro that works fine except for one area where you want to save the file, disable alerts only for that one area and enable them afterwards for the rest of the macro; this reduces the chance that other data will get overwritten without warning.
Download the sample file if you want to see the above example in Excel.
Similar Content on TeachExcel
Excel VBA MsgBox — Message Box Macro
Tutorial: Create a pop-up message box in Excel using VBA Macros. This allows you to show a message t…
Logical Operators in Excel VBA Macros
Tutorial: Logical operators in VBA allow you to make decisions when certain conditions are met.
They…
Require a Password to View Hidden Worksheets in Excel — VBA Tutorial
Tutorial:
Full Course
A simple macro that allows you to require a password in order to view hidden …
Excel VBA — Create an Array — 3 ways
Tutorial: Ill show you three different ways to create an array in Excel VBA and Macros and how to ge…
Loop Through an Array in Excel VBA Macros
Tutorial:
I’ll show you how to loop through an array in VBA and macros in Excel. This is a fairly…
Loop through a Range of Cells in Excel VBA/Macros
Tutorial: How to use VBA/Macros to iterate through each cell in a range, either a row, a column, or …