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

 

Ответить

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!

Сохранение файла рабочей книги 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 и т.д. в папке «Документы».


When saving a file in Excel from VBA code it is sometime useful to avoid the display of a Save As dialog if the file to be saved already exists (i.e. to overwrite any exisiting files).

This is pretty easy but one of those things I always forget how to do!

Here’s the code:

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs (etc.)
Application.DisplayAlerts = True

Thanks to the users at http://www.vbforums.com/showthread.php?t=528826 who reminded me of this for about the hundredth time!

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