Vba excel сохранить книгу как без подтверждения

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 не получается  
се равно спрашивает заменить книгу (Да,Нет,Отмена)

закрытие екселя с сохранением и без предупреждения

85Muslim85

Дата: Суббота, 21.03.2015, 14:08 |
Сообщение № 1

Группа: Заблокированные

Ранг: Участник

Сообщений: 60


Репутация:

-23

±

Замечаний:
80% ±


Excel 2007

добрый день, скажите как закрыть ексель (полностью выйти) с сохранением под таким же названием и без предупреждения
скажите что в этом коде не так((((

[vba]

Код

Sub вава()
Range(«A1») = 1
Workbooks.Application.DisplayAlerts = False
Excel.ActiveWorkbook.SaveAs («rl.xlsm»)
Workbooks.Close
End Sub

[/vba]

Сообщение отредактировал 85Muslim85Суббота, 21.03.2015, 16:26

 

Ответить

KSV

Дата: Суббота, 21.03.2015, 14:29 |
Сообщение № 2

Группа: Друзья

Ранг: Ветеран

Сообщений: 770


Репутация:

255

±

Замечаний:
0% ±


Excel 2013

все правильно

[vba]

Код

‘ подавляет предупреждения Excel
Workbooks.Application.DisplayAlerts = False

‘ сохраняет книгу в файл С ДРУГИМ именем
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

[/vba]


KSV.VBA@gmail.com
Яндекс.Деньги: 410011921213333

Сообщение отредактировал KSVСуббота, 21.03.2015, 14:34

 

Ответить

85Muslim85

Дата: Суббота, 21.03.2015, 14:35 |
Сообщение № 3

Группа: Заблокированные

Ранг: Участник

Сообщений: 60


Репутация:

-23

±

Замечаний:
80% ±


Excel 2007

все отлично)) спасибки… вот чего я хотел)

Workbooks.Application.DisplayAlerts = False
Excel.ActiveWorkbook.Save
Application.Quit

 

Ответить

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:

  1. Start Excel and open a new workbook.

  2. Press ALT+F11 to start the Visual Basic editor.

  3. On the Insert menu, click Module.

  4. Type the sample macro code into the module sheet.

  5. Press ALT+F11 to return to Excel.

  6. 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.

  7. 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 …

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Понравилась статья? Поделить с друзьями:
  • Vba excel сохранить как книгу без макросов
  • Vba excel сохранить изменения в книге
  • Vba excel сохранить документ word
  • Vba excel сохранить в pdf все листы
  • Vba excel сохранение файла в формате