Do not save excel macro

I am writing a macro and I need to disable the save function on the workbook that VBA has copied and pasted all the information into. Is this possible?

Martijn Pieters's user avatar

asked Sep 4, 2012 at 13:30

Hannah's user avatar

You can use the Workbook_BeforeSave event to achieve this, disabling the CommandBars won’t stop your users using a shortcut such as CTRL + S.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    MsgBox "You can't save this workbook!"
    Cancel = True

End Sub

answered Sep 4, 2012 at 13:38

Francis Dean's user avatar

Francis DeanFrancis Dean

2,3862 gold badges21 silver badges29 bronze badges

7

You can use the Application object to access the toolbar buttons directly:

Private Sub Workbook_Open() 
    Application.CommandBars("Worksheet Menu Bar").Controls("File").Controls("Save As...").Enabled = False 
    Application.CommandBars("Worksheet Menu Bar").Controls("File").Controls("Save").Enabled = False 
End Sub 

Deanna's user avatar

Deanna

23.8k7 gold badges72 silver badges155 bronze badges

answered Sep 4, 2012 at 13:35

Ryan McDonough's user avatar

Ryan McDonoughRyan McDonough

9,6663 gold badges55 silver badges76 bronze badges

0

One more side note; I had difficulties with the above codes because my organization uses HUNGARIAN version of Excel.
So in case you use NON ENGLISH EXCEL you must specify the Controls elements in your Excel’s local language … in my case what worked was:

Application.CommandBars("Worksheet Menu Bar").Controls("Fá&jl").Controls("Menté&s má&ské&nt...").Enabled = False
Application.CommandBars("Worksheet Menu Bar").Controls("Fá&jl").Controls("Menté&s").Enabled = False

answered May 27, 2020 at 8:08

Adam Kruzics's user avatar

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?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #2

Welcome to the Board!

Macros can be saved to the Personal Macro Workbook, but do not have to be. They can be saved it any Excel workbook. It sounds like you have saved them to the actual workbook.
If you want to create a Personal Macro Workbook, the easiest way is to record a new Macro, and select the «Personal Macro Workbook» as the location that you want to save it to. This will create that Personal Macro Workbook for you.

If you have not already done that on a new computer, you probably do not have a Personal Macro Workbook yet.

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #4

Try this:

1. Record a new macro
2. Elect it to save to your Personal Macro Workbook
3. Stop recording the macro
4. Go to View Macros, select the one you just saved, and choose the Edit Button
5. Add a simple new macro in there like this:

Code:

Sub Test()
    MsgBox "Good morning!"
End Sub

6. Close down Excel — it should ask you if you want to save changes to your Personal Macro Workbook — BE SURE TO SAY YES!
7. Re-open Excel
8. Go to View Macros
9. Change the Macros In option to the PERSONAL option

Do you see the Test macro listed there?

Joe4

Joe4

MrExcel MVP, Junior Admin


Joe4

Joe4

MrExcel MVP, Junior Admin


  • #8

Only other suggestion I have is to try removing/deleting all Personal Workbooks you currently have out there, and try starting again.

How do I turn off Save Changes prompt when I close a workbook in Excel?

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.

How do I turn off autosave in Visual Studio?

To edit your Workspace settings, you need to edit the settings. json file which resides at the . vscode folder of your solution. Vscode version 1.34 onwards just got to file menu and click on “Auto Save” to enable or disable Autosave.

How do I turn off save prompt in Excel?

Disable save prompt with VBA code in Excel

  1. Press Alt + F11 to open a Microsoft Visual Basic for Application window.
  2. Click Insert > Module to open a Module window, then copy the following VBA to the window. VBA: Close without saving directly.
  3. Click Run button or F5 key on the keyboard to run this code.

How do you disable save and save as using VBA?

To prevent Save As event, the address is Workbook object’s BeforeSave event. VBA has a predefined subroutine for this event: Workbook_BeforeClose. This subroutine has 2 arguments which can say you if user is in Save As menu and allows you to cancel the Save action.

Why does Excel close without asking to save?

If the save prompt appears when you close, the issue should be caused by Excel add-in. I suggest you exist safe mode, reopen Excel in normal mode, then go to File>Options>Add-ins>Manage COM add-ins or Excel add-ins, Go. Uncheck an add-in at a time, click OK, check if the issue happens.

Why does Excel keep asking me to save changes?

Excel maintains what is commonly called a “dirty flag.” This flag gets set whenever you do some sort of change to a workbook. Whenever you save the workbook, the flag is cleared. If the flag is set when you close the workbook, Excel asks if you want to save the workbook.

How do I autosave in Visual Studio?

It does an equivalent of Ctrl + Shift + S when Visual Studio loses focus, which saves all your files, including solution and projects. This extension can automatically save modified documents, projects, and the solution whenever Visual Studio loses focus.

Under what circumstances would you use the Save command versus the Save As command what would happen if you made changes to a file and wanted to save it under a new name and used the Save command?

The quick answer Use Save when you’re editing an existing document and you want to preserve your changes to it as you work. Save replaces the original file. A typical editing session for a given document might look like this: Open existing document, make changes, Save, make more changes, Save, Print, Close.

How do you protect Excel from Save As?

Protect an Excel file

  1. Select File > Info.
  2. Select the Protect Workbook box and choose Encrypt with Password.
  3. Enter a password in the Password box, and then select OK.
  4. Confirm the password in the Reenter Password box, and then select OK.

How to disable save prompt when close workbook?

3. Click Run button or F5 key on the keyboard to run this code. Then when you closing an Excel workbook, it will close directly and not saving the last change. If you want to close the Excel with saving the changes, you can use this VBA code. VBA: Close with saving.

How to programmatically close documents in Visual Studio?

Call the Close method of the ThisDocument class in your project to close the document associated with the customization. To use the following code example, run it from the ThisDocument class. This example passes the wdDoNotSaveChanges value to the SaveChanges parameter to close without saving changes or prompting the user.

How do you close a document in VSTO?

The way that you close a document that you specify by name is the same for VSTO Add-ins and document-level customizations. Specify the document name as an argument to the Documents collection, and then call the Close method. The following code example assumes that a document named NewDocument is open in Word.

How do you close a document in word?

To close a document that you specify by name. Specify the document name as an argument to the Documents collection, and then call the Close method. The following code example assumes that a document named NewDocument is open in Word.

What do I do if Excel isn’t responding and I haven’t saved?

Or you can make it with the guides below.

  1. Open Excel, and click “File” > “Info” > “Manage Workbook”. Click “Recover Unsaved Workbooks” from the drop-down menu.
  2. Select the unsaved file and click the “Open” button. Then, on the pop-up window, choose “Save As” to recover it.

Why does Excel ask me to save when I haven’t changed anything?

This behavior occurs when something in the file has changed. Many times the user doesn’t realize there are elements in the file that have been updated or calculated. Here are some examples of common scenarios: The file has been opened in a newer version and formulas have been calculated.

How do I turn off notifications in Excel?

Launch Excel. Choose “File” and then “Options.” Select “Customize Ribbon” and click the box to put a check mark next to the “Developer” option in the list of tabs on the right under Main Tabs, if the box is not already checked. Select “OK” to save your changes.

How do I force an Excel file to be locked by another user?

Go to Computer Management -> System Tools -> Shared Folders -> Open Files to find out who has a document locked. If the user can’t be contacted to disconnect themselves, you can forcefully do so by right clicking the locked file and selecting Close Open File (warning: the user might lose their changes).

How to save, close workbook and close Excel?

The TRUE parameter of ThisWorkbook.Close tells it to save changes. You want to save your workbook somehow before quitting the application. Ok I understand the True statement.

How to close Excel file from VBScript without being prompted?

I have a VB Script that opens an Excel file and runs a macro. I am trying to close this excel file (without saving any changes) without being prompted to save.

What to do when Excel file is unable to save?

If the user is unable to save the changes after editing in a locally saved spreadsheet (see Instance 2 above), then follow these steps: Upload the unsaved Excel file to Google Docs. Ensure that the file gets converted to Google Sheet format If the Excel file is found to have corruption, try out the Excel Open and Repair utility:

How to fix MS Excel in safe mode?

Solution 1: Restart Excel in Safe Mode 1 Create a shortcut of MS Excel on Desktop 2 Press and hold the Ctrl key while launching the program 3 Click ‘ Yes ‘ when a prompt appears to confirm

How do I enable the Save prompt in Excel?

Press Windows logo key and the R key to open the Run window. 2.In the Run box, type command: excel /safe and click OK. 3. When Excel is in safe mode, make some changes in the workbook, check if you will get the save prompt when closing the workbook.

What happens when you close the Excel application without saving?

If unsaved workbooks are open when you use this method, Excel displays a dialog box asking whether you want to save the changes. When this property is False, Excel doesn’t display the dialog box when you quit with unsaved workbooks; it quits without saving them.

Why does Excel not prompt to save on exit?

Hi, Software add-ins may cause your Excel 2016 app not to prompt saving on exit. For proper isolation, we suggest starting Excel in safe mode. To do so, press and hold Ctrl while you start the program, or by using the “/safe” (excel.exe /safe) option when you start the program using the Command prompt.

Why does excel not prompt to save on exit?

Which Excel functions are volatile?

The following Excel functions are volatile:

  • NOW.
  • TODAY.
  • RANDBETWEEN.
  • OFFSET.
  • INDIRECT.
  • INFO (depending on its arguments)
  • CELL (depending on its arguments)
  • SUMIF (depending on its arguments)

Why does Excel ask if I want to save changes when I didn’t make any changes?

Sometimes, Excel does something that affects the contents of the workbook just by virtue of the fact you opened it. This sets the dirty flag and thus triggers the request about saving. Two big culprits in making such automatic changes are the TODAY and NOW worksheet functions.

How do you close Excel without save prompt in VBA?

To avoid seeing this message, you can 1) Save the file first, 2) Change the DisplayAlerts property, 3) Use the SaveChanges argument of the Close method, or 4) set the Saved property to True. Note that this won’t save the changes, it will close the workbook without saving.

How do you open an Excel file without running a macro?

To run a workbook without triggering a startup macro, you need to open it from within Excel, rather than double-clicking the file in Windows. Open Excel, go to the File menu, click “Open” and locate your file. Hold down the “Shift” key while you click “Open,” and continue holding it until the workbook finishes loading.

How to suppress save changes prompt in Excel?

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.

How can I save an Excel file as a response?

By doing this step your Excel file will have all of the necessary formatting and columns setup for your form. While editing your form, go to the Responses tab, click Open in Excel on your form to download the Excel file. Save it, naming it anything you’d like. I suggest removing the (1-XX) portion of the file name.

How to force a workbook to save changes?

You can also use the SaveChanges argument of the Close method. To force a workbook to save changes, type the following code in a Visual Basic module of that workbook: 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.

What does it mean to save a workbook in Excel?

expression A variable that represents a Workbook object. A string that indicates the name of the file to be saved. You can include a full path; if you don’t, Microsoft Excel saves the file in the current folder. The file format to use when you save the file. For a list of valid choices, see the XlFileFormat enumeration.

How do I close an Excel file without closing it?

The shortcut to achieve this is to use CTRL + W. So with your last workbook open click CTRL + W. You will end up with this.

How do I close a specific workbook in VBA?

Steps to Close a Workbook

  1. Specify the workbook that you want to close.
  2. Use the close method with that workbook.
  3. In the code method, specify if you want to save the file or not.
  4. In the end, mention the location path where you want to save the file before closing.

How do you close a workbook in Excel macro?

VBA Close Workbook – Instructions

  1. Open an Excel Workbook.
  2. Press Alt+F11 to Open VBA Editor.
  3. Insert a Module from Insert Menu.
  4. Copy the above code for activating a range and Paste in the code window(VBA Editor)
  5. Save the file as macro enabled workbook.
  6. Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line.

Why does Excel ask if I want to save every time?

How do I force an Excel spreadsheet to close?

Another way to close all Excel files is with the “X” at the top right of the Excel window.

  1. If you simply click that “X”, it will close the active window only.
  2. To close all Excel files, press the Shift key, and click the X.

How do I close an Excel spreadsheet in Office 365?

Do one of the following:

  1. In the upper-right corner of the Excel window, click Close .
  2. Click the Microsoft Office Button , and then click Exit Excel.

How do you close a workbook?

Close the active workbook window

  1. Click the workbook window that you want to close.
  2. In the upper-right corner of the workbook window, click Close Window .

How do I automatically close an Excel file?

Open the workbook you need to make it auto saved and closed after a certain idle time. Then press the Alt + F11 keys together to open the Microsoft Visual Basic for Applications window. 4. Press the Alt + Q keys simultaneously to close the Microsoft Visual Basic for Applications window.

Do you want to save changes Excel?

With the macro in place, Excel will never ask you if you want to save changes upon exiting, even if legitimate changes were done to the workbook. Thus, you would need to remember to explicitly save anything in the workbook whenever you make changes. If you don’t, you may loose some of your work.

Is there a way to close the workbook in Excel?

And Close is the Workbook method to Close the Excel File. We will see the other examples to close the Workbook in different situations in the following examples. The following VBA code is to Close the Active Excel Workbook. This code will close the Workbook which is currently active. The following VBA code is to Close any Excel Workbook.

How to run the VBA code while opening or closing the workbook?

In this article, I will tell you how to run the VBA code while opening or closing the workbook every time. 1. Enable the workbook, press Alt + F11 keys to open the Microsoft Visual Basic for Applications window. 2. Double click ThisWorkbook in Project – VBAProject pane to open the ThisWorkbook (Code) window. 2.

How do you close a file in VBA?

Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code: This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.

How to force a workbook to close without saving any 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.

Обычно, когда мы нажимаем кнопку «Сохранить» или «Сохранить как», наши измененные данные в книге сразу же сохраняются. Но иногда ваш файл Excel не разрешается изменять и сохранять другим пользователям, когда они читают файл. В этой статье описан метод VBA для отключения параметров «Сохранить и сохранить как» в Excel.

Отключить параметры «Сохранить и сохранить как» с помощью кода VBA


Отключить параметры «Сохранить и сохранить как» с помощью кода VBA

Вы можете запустить приведенный ниже код VBA, чтобы отключить параметры «Сохранить и сохранить как» в Excel.

1. В книге вам необходимо отключить функции «Сохранить и сохранить как», нажмите другой + F11 клавиши одновременно, чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, дважды щелкните Эта рабочая тетрадь на левой панели скопируйте и вставьте VBA 1 ниже в окно кода, а затем щелкните Сохраните кнопка. Смотрите скриншот:

VBA 1: отключить параметры «Сохранить и сохранить как» в Excel

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ThisWorkbook.Saved = True
End Sub

3. В дебюте Сохранить как В окне выберите папку для сохранения книги, назовите книгу по своему усмотрению и выберите Excel Macro-Enabled Workbook из Сохранить как раскрывающийся список и, наконец, щелкните Сохраните кнопку.

4. Теперь скопируйте и вставьте VBA 2 ниже в Эта рабочая тетрадь окно кода. Смотрите скриншот.

VBA 2: отключить параметры «Сохранить и сохранить как» в Excel

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim xName As String
xName = "CancelBeforeSave"

If Not Evaluate("=ISREF('" & xName & "'!A1)") Then
    Sheets.Add(after:=Worksheets(Worksheets.count)).Name = xName & ""
    Sheets(xName & "").Move after:=Worksheets(Worksheets.count)
    Sheets(xName & "").Visible = False
    Exit Sub
End If
    Cancel = True
End Sub

5. Нажмите Сохраните кнопку, чтобы сохранить код, а затем закройте книгу.

Книга была сохранена как книга Excel с поддержкой макросов с Сохраните и Сохранить как функции отключены.

Внимание: Кажется, что изменения сохраняются в текущем листе каждый раз, когда вы изменяете и сохраняете книгу. Но после закрытия и повторного открытия книги вы обнаружите, что изменения не удалось сохранить.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (27)


Оценок пока нет. Оцените первым!

Понравилась статья? Поделить с друзьями:
  • Do not round numbers excel
  • Do not pay attention to every word
  • Do not listen to a word i say song
  • Do not just listen to the word do what it says
  • Do not distribute excel