Excel saveas перезаписать без подтверждения

   bvb

17.12.14 — 16:15

Редактирую существующий файл Excel

и запоминаю его :

WorkBook.SaveAs(ИмяФайлаXLS,-4143);

Как подавить запрос на перезапись ?

   бомболюк

1 — 17.12.14 — 16:16

прибить файло сначала

   silent person

2 — 17.12.14 — 16:20

Екзель = Новый COMОбъект(«Excel.Application»);  

Екзель.displayAlerts = 0;

не помогает ?

   Vladal

3 — 17.12.14 — 16:26

(2) Не. надо сначала отключить алерты:

Excel.DisplayAlerts=0;

Excel.Workbooks(ИмяФайла).SaveAs(ИмяФайла,-4143);

Excel.DisplayAlerts=1;

   Vladal

4 — 17.12.14 — 16:27

(2) Хотя да. Я первую строку принял за сохранение.

(2) помогло спасибо

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!

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

I need to export excel from viewlist, I used this code

Excel.Application app = new Excel.Application();
            //app.Visible = true;
            Excel.Workbook wb = app.Workbooks.Add(1);
            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

            int i = 1;
            int i2 = 1;
            foreach (ListViewItem lvi in lvLogs.Items)
            {
                i = 1;
                foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
                {
                    ws.Cells[i2, i] = lvs.Text;
                    i++;
                }
                i2++;
            }


            wb.SaveAs(@"C:1myExcel.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing);
            wb.Close(false, Type.Missing, Type.Missing);

            app.Quit();

        }

Now I need to overwrite the excel file without any message and I need to do this action every 10 min.

effort

0 / 0 / 0

Регистрация: 17.06.2016

Сообщений: 43

1

Как сохранить файл эксел перезаписав старый без запроса на сохранение?

14.07.2016, 18:46. Показов 1552. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Надо сохранить из аксесса эксел файл поверх старого с тем же названием, чтобы пользователь не опрашивался на перезапись.
Делаю так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
    Dim fileobjexcel As Excel.Application
    Dim filexcel As Excel.Workbook
 
    Set fileobjexcel = New Excel.Application
 
    Set filexcel = fileobjexcel.ActiveWorkbook
    filexcel.SaveAs "имя файла", xlExcel7, , , , , , xlLocalSessionChanges
 
    fileobjexcel.Workbooks.Close
    Set fileobjexcel = Nothing

опрашивает на перезапись…



0



ltv_1953

Эксперт MS Access

17142 / 7008 / 1567

Регистрация: 21.06.2012

Сообщений: 13,112

14.07.2016, 18:52

2

Ну так убейте «имя файла», если он есть … .

Visual Basic
1
2
3
        On Error Resume Next
            Kill "имя файла"
        On Error GoTo 0



1



0 / 0 / 0

Регистрация: 17.06.2016

Сообщений: 43

14.07.2016, 18:53

 [ТС]

3

О, точно, буду уничтожать. Спасибо.
А без убийства никак?
Что за опции у «filexcel.SaveAs »



0



Эксперт MS Access

7267 / 4469 / 288

Регистрация: 12.08.2011

Сообщений: 13,513

15.07.2016, 02:24

4

Цитата
Сообщение от effort
Посмотреть сообщение

Что за опции у «filexcel.SaveAs «

Видимо у вас кнопочка на клавиатуре отломалась, вот эта:

Миниатюры

Как сохранить файл эксел перезаписав старый без запроса на сохранение?
 



0



0 / 0 / 0

Регистрация: 17.06.2016

Сообщений: 43

15.07.2016, 16:20

 [ТС]

5

С кнопкой все хорошо. Поисковик гугл тоже установлен и обновлен.
Тут написано что «Если установлено значение xlLocalSessionChanges, изменения локального пользователя автоматически принимаются.»
я надеялся, что автоматически принимаются = не запрашивает на сохранение, а он запрашивает.



0



mobile

Эксперт MS Access

26777 / 14456 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

15.07.2016, 16:26

6

effort, перед сохранением отключайте екселевские сообщения

Visual Basic
1
fileobjexcel.DisplayAlerts=False



3



0 / 0 / 0

Регистрация: 17.06.2016

Сообщений: 43

15.07.2016, 16:31

 [ТС]

7

Работает, спасибо!



0



Понравилась статья? Поделить с друзьями:
  • Excel return the value of a cell
  • Excel saveas excel save
  • Excel return sheet name
  • Excel save this world
  • Excel return array from function