Excel saved as copy of

Содержание

  1. Создание резервных копий ценных файлов
  2. How to: Programmatically save workbooks
  3. Save a workbook without changing the path
  4. To save a workbook associated with a document-level customization
  5. To save the active workbook in a VSTO Add-in
  6. Save a workbook with a new path
  7. To save a workbook associated with a document-level customization
  8. To save the active workbook in a VSTO Add-in
  9. Save a copy of the workbook
  10. To save a workbook associated with a document-level customization
  11. To save the active workbook in a VSTO Add-in
  12. To verify that the save was successful
  13. Robust programming
  14. Как создать резервную копию книги с сегодняшней датой
  15. Как это работает
  16. Код макроса
  17. Как работает этот код
  18. Как использовать
  19. SaveCopyAs Method of Workbook Object VBA
  20. VBA Reference
  21. 120+ Project Management Templates
  22. Why we need SaveCopyAS in Workbook using VBA?
  23. VBA SaveCopyAS Workbook – Syntax
  24. VBA SaveCopyAS Workbook:Example 1
  25. Excel VBA Save Workbook: Easily Save Excel Files With These 3 Macro Examples
  26. How To Save An Excel Workbook Using the Workbook.Save VBA Method
  27. How To Save An Excel Workbook Using The Workbook.SaveAs VBA Method
  28. How To Save An Excel Workbook With A New Name Using The Workbook.SaveAs Method
  29. Part #1: Dim workbook_Name As Variant
  30. Part #2: workbook_Name = Application.GetSaveAsFilename
  31. Part #3: If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name End If
  32. The Workbook.SaveAs Method: Parameters
  33. Argument #1: Filename
  34. Argument #2: FileFormat
  35. Argument #3: Password
  36. Argument #4: WriteResPassword
  37. Argument #5: ReadOnlyRecommended
  38. Argument #6: CreateBackup
  39. Argument #7: AccessMode
  40. Argument #8: ConflictResolution
  41. Argument #9: AddToMru
  42. Argument #12: Local
  43. How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method
  44. Part #1: ActiveWorkbook.SaveCopyAs
  45. Part #2: Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name
  46. Item #1: ActiveWorkbook.Path
  47. Items #2 And #4: “Copy ” and ” “
  48. Item #3: Format(Now, “yy-mm-dd”)
  49. Item #5: ActiveWorkbook.Name
  50. How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method: An Example
  51. How To Name A Workbook Using The Application.GetSaveAsFilename Method
  52. The Application.GetSaveAsFilename Method: Purpose
  53. The Application.GetSaveAsFilename Method: Syntax
  54. The Application.GetSaveAsFilename Method: Arguments
  55. Argument #1: InitialFilename
  56. Argument #2: FileFilter
  57. Argument #3: FilterIndex
  58. Argument #4: Title
  59. Argument #5: ButtonText
  60. Conclusion

Создание резервных копий ценных файлов

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

Если у вас Excel 2010, то кроме стандартного автосохранения у вас должна работать система версий — каждый раз при автосохранении Excel делает отдельную копию вашего текущего файла и (даже!) при выходе из программы и отрицательном ответе на вопрос «Сохранить изменения в файле?» все равно сохраняет временную копию. Добраться до этих временных копий можно через вкладку Файл — Сведения — Версии (File — Properties — Versions) :

Для своих проектов я в итоге пришел к другому решению — написал макрос, который сохраняет текущую книгу в заданную папку, добавляя к имени книги текущую дату и время в формате ДД-ММ-ГГ ЧЧ-ММ (например Мой проект 12-10-12 07-35). Периодически запуская этот макрос на ключевых этапах работы с файлом, я получаю список из энного количества файлов-версий рабочей книги и, соответственно, легко могу откатиться к нужному варианту в прошлом.

Откройте редактор Visual Basic, выбрав на вкладке Разработчик — Редактор Visual Basic (Developer — Visual Basic Editor) или нажав ALT+F11. Вставьте через меню Insert — Module новый пустой модуль и скопируйте туда текст этого макроса:

Естественно, путь к папке (C:TEMP) и имя файла (Мой проект) надо заменить на свои.

Если ваша папка для сохранения находится на сетевом диске, то ее адрес можно прописать, используя IP-адрес сервера, например:

Еще одно, возможно, полезное дополнение в том, что имя файла может быть не постоянным, а браться из заданной ячейки листа, где его либо вводит пользователь, либо оно автоматически формируется формулами (например, функцией СЦЕПИТЬ и т.д.). Тогда необходимо будет чуть подправить следующую строку:

Предполагается, что имя файла берется с листа Лист1 из ячейки А1.

Источник

How to: Programmatically save workbooks

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code

There are several ways to save a workbook. You can save a workbook without changing the path. If the workbook has not been saved before, you should save the workbook by specifying a path. Without an explicit path, Microsoft Office Excel saves the file in the current folder with the name it was given when it was created. You can also save a copy of the workbook without modifying the open workbook in memory.

Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Excel. For more information, see Features available by Office application and project type.

Save a workbook without changing the path

To save a workbook associated with a document-level customization

Call the Save method of the ThisWorkbook class.

To save the active workbook in a VSTO Add-in

Call the Save method to save the active workbook. To use the following code example, run it in the ThisAddIn class in a VSTO Add-in project for Excel.

Save a workbook with a new path

You can save the specified workbook to a new location or with a new name, optionally specifying a file format, a password, an access mode, and more.

You might want to set the DisplayAlerts property to False before saving the workbook with a new path because saving in some formats requires interaction. Setting this property to False causes Excel to use all defaults.

To save a workbook associated with a document-level customization

Call the SaveAs method of the ThisWorkbook class. To use the following code example, run it in the ThisWorkbook class.

To save the active workbook in a VSTO Add-in

Call the SaveAs method to save the active workbook to a new path. To use the following code example, run it in the ThisAddIn class in a VSTO Add-in project for Excel.

Save a copy of the workbook

You can save a copy of the workbook to a file without modifying the open workbook in memory. This is useful when you want to create a backup copy without modifying the location of the workbook.

To save a workbook associated with a document-level customization

Call the SaveCopyAs method of the ThisWorkbook class. To use the following code example, run it in the ThisWorkbook class.

To save the active workbook in a VSTO Add-in

Call the SaveCopyAs method to save a copy of the active workbook. To use the following code example, run it in the ThisAddIn class in a VSTO Add-in project for Excel.

To verify that the save was successful

You can use some of the DocumentProperties like the Last Save Time to verify that the save was successful.

Robust programming

Interactively canceling any of the methods that save or copy the workbook raises a run-time error in your code. For example, if your procedure calls the SaveAs method but does not disable prompts from Excel, and your user clicks Cancel when prompted, Excel raises a run-time error.

Источник

Как создать резервную копию книги с сегодняшней датой

Что делает макрос: Макрос позволяет создать резервную копию книги и сохраняет ваш файл в папке с сегодняшней датой.

Как это работает

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

Путь определяем с помощью свойства Path объекта ThisWorkbook.
Второй частью нового файла является исходное имя файла. Мы используем свойство Name объекта ThisWorkbook.
Текущую дату берем с помощью функции Date. Вы заметите, что мы форматируем дату (Format (Date, «мм-дд-гг»)). Это происходит потому, что по умолчанию функция даты возвращает мм / дд / гггг. Мы используем дефис вместо слэша, иначе это вызовет ошибку при попытке сохранить файл (Windows не позволяет использовать «/» в именах файлов.)

Код макроса

Как работает этот код

Используем одну единственную строку, которая с помощью метода SaveCopyAs создает новый имя файла и использует метод для сохранения файла.

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код во вновь созданном модуле.

Источник

SaveCopyAs Method of Workbook Object VBA

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word Templates

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates

‘SaveCopyAs’ method of workbook object is used to saves a copy of the workbook as a file but does not modify or change the open workbook. Please find the more information about SaveCopyAs Workbook method.

Why we need SaveCopyAS in Workbook using VBA?

Sometimes we may want to save the workbook with changes and we don’t want to modify the opened workbook. So only we need to use ‘SaveCopyAs’ method of workbook object.

VBA SaveCopyAS Workbook – Syntax

Here is the example syntax to saves a copy of Workbook using VBA.

Workbooks(“Your Workbook Name”).SaveCopyAs(

Where Filename: It is an Optional parameter. It will specifies the workbook name to save the copy. But to avoid problems always better to declare the filename. Because if it uses the current file name to save the file in the current folder since the workbook might be open.

VBA SaveCopyAS Workbook:Example 1

Please find the below example, It will show you saveCopyas workbook method.

Источник

Excel VBA Save Workbook: Easily Save Excel Files With These 3 Macro Examples

If you’ve worked with Excel before, you’re probably quite familiar with 2 basic commands for saving workbooks:

It may not surprise you to know that, when working with VBA, you can carry out these same activities.

In fact, knowing how to save Excel workbooks using VBA is essential. As you work with Visual Basic for Applications, you’ll notice that saving workbooks is one of the most important things your macros can do.

Due to the importance of knowing how to save workbooks using VBA, this Excel tutorial focuses on this particular topic:

How to save an Excel workbook using VBA.

In addition to providing some examples of VBA code that you can use to save workbooks, I explain the basics surrounding 4 VBA methods that you’re likely to encounter and use constantly while saving workbooks. The following table of contents shows the specific topics that I explain in this Excel tutorial:

Table of Contents

This Excel tutorial doesn’t cover the topic of saving an Excel workbook as PDF using VBA. I explain how to export an Excel file to PDF using macros, and provide several code examples, here.

Let’s start taking a look at the basic ways to save an Excel workbook using VBA.

How To Save An Excel Workbook Using the Workbook.Save VBA Method

The most basic method to save Excel workbooks using VBA is the Workbook.Save method. Workbook.Save saves the relevant workbook.

In other words, the Workbook.Save method is, roughly, the VBA equivalent of the Save command in Excel.

The syntax of the Workbook.Save method is as follows:

Where “expression” is the relevant Workbook object you want to save.

Let’s take a look at an example to make this clearer. The following macro, named “Save_Workbook”, saves the current active workbook:

This Excel VBA Save Workbook Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Save_Workbook macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Notice that the macro has only 1 statement which follows the general syntax of the Workbook.Save method explained above:

In this case, ActiveWorkbook is a simplified reference to the Application.ActiveWorkbook property. This property returns a Workbook object, as required by the Workbook.Save method. The workbook that is returned by the ActiveWorkbook property is, more precisely, the workbook in the current active window.

In summary, the sample Save_Workbook macro above simply saves the current active Excel workbook.

Just as when working directly with Excel, the Save method is an important command/method that is relatively easy and straightforward to execute. However, it doesn’t allow you to determine much in connection with the way the relevant Excel workbook is saved. The workbook is saved and that’s pretty much it.

When working directly in Excel, you use the Save As command if you want to be able to determine more about the way the actual saving of a workbook takes place. Things work in a similar fashion within Visual Basic for Applications.

More precisely, when working with Visual Basic for Applications, you can use the SaveAs method for these purposes. So let’s take a look at:

How To Save An Excel Workbook Using The Workbook.SaveAs VBA Method

The arguments or parameters of a method are what allows you to determine the characteristics of the action that a particular method performs.

As explained above, the Workbook.Save method doesn’t have any parameters. As a consequence, you can’t really determine much about how the relevant workbook is saved.

The Workbook.SaveAs method is different. Its 12 parameters allow you to further determine several aspects about the way in which an Excel workbook is saved. In other words, Workbook.SaveAs is more flexible and complex than Workbook.Save.

Workbook.SaveAs is, roughly speaking, the VBA equivalent of the Save As command in Excel. Therefore, it allows you to save a workbook in a particular file. The complete syntax of the Workbook.SaveAs method is as follows:

expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode,ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

“expression” is, just as in the case of the Workbook.Save method above, the relevant Workbook object.

All of the parameters (which appear within parentheses) of the SaveAs method are optional. However, in order to understand what this method can help you with, I explain these parameters below.

However, as usual, I use a practical macro example for purposes of illustrating how Workbook.SaveAs works. So let’s start by taking a look at the basic VBA code of the macro example:

How To Save An Excel Workbook With A New Name Using The Workbook.SaveAs Method

The following piece of VBA code saves the current active workbook with a new name provided by the user.

If workbook_Name <> False Then

The following screenshot shows the VBA code behind the example macro (called “Save_Workbook_NewName”) which is included in the Excel workbook that accompanies this Excel VBA Save Workbook Tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

This macro can be divided in the following 3 parts:

Let’s take a quick look at each of these parts to understand how the Save_Workbook_NewName macro works:

Part #1: Dim workbook_Name As Variant

This statement simply declares a variable named workbook_Name. The variable is of the Variant data type.

Even though Variant variables are sometimes undesirable, in this particular case that’s not necessarily the case. A Variant variable allows the GetSaveAsFilename (which I introduce below) to be quite flexible.

As implied by its name, and made evident by the following parts of the macro, the purpose of the workbook_Name variable is to store the new name of the saved Excel workbook.

Part #2: workbook_Name = Application.GetSaveAsFilename

This statement assigns a value to the workbook_Name variable. Which value is actually assigned is determined by the Application.GetSaveAsFilename method, which I explain thoroughly below.

At its most basic level, the GetSaveAsFilename method, does the following 2 things:

    Step #1: Displays the Save As dialog box.

You’re probably quite familiar with this dialog box, as it’s the one Excel displays when you execute the Save As command.

Step #2: Once the user has provided a file name through the Save As dialog box, GetSaveAsFilename gets that particular name.

This is the name that the whole statement we’re analyzing assigns to the variable workbook_Name.

Note that the Application.GetSaveAsFilename method doesn’t actually save a file. It simply gets a name.

To actually save the file using the name provided by the GetSaveAsFilename method, you usually rely on the Workbook.SaveAs method. This method is used in the last part of the Save_Workbook_NewName macro:

Part #3: If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name End If

This is an If… Then… Else statement. These type of statements conditionally execute a particular group of statement depending on whether a condition is met or not. The statement begins with the word If. The whole block finishes with the End If statement.

In the case of the Save_Workbook_NewName macro, the If… Then… Else statement proceeds as follows:

Step #1: Test Whether workbook_Name <> False.

The first part of the If… Then… Else statement carries out a logical test. This logical test seeks to confirm whether the variable workbook_Name has a value that is different from (<>) the logical value False.

If the value of workbook_Name isn’t False, the logical test (workbook_Name <> False) evaluates to True. In such a case, the statements within the If… Then… Else are executed.

However, if the value of workbook_Name is equal to the Boolean value False, the logical test evaluates to False. In this case, the conditional statements aren’t executed.

For purposes of this logical test, the value of the variable workbook_Name is that assigned in the previous part. Therefore, the value depends on the input given by the user when the Save As dialog box is displayed. More precisely:

  • If the user cancels the Save As dialog box, the value of workbook_Name is False.
  • If the user provides a file name through the Save As dialog box, the value of the workbook_Name variable is (generally) that assigned by the user.
  • If the user provides a file name:
    • The logical test carried out by the first part of the If… Then… Else statement is True; and
    • The conditional statements that follow are executed.
  • If the user cancels the Save As dialog box (by, for example, clicking on the Cancel button):
    • The logical test is False; and
    • The conditional statements within the If… Then… Else statement aren’t executed.

Step#2: Execute The Statement ActiveWorkbook.SaveAs Filename:=workbook_Name If The Tested Condition Is True.

You already know that, roughly speaking, the logical test workbook_Name <> False returns True if the user has assigned a file name through the Save As dialog box.

In such case, the following statement is executed:

This is where the Workbook.SaveAs method comes into play. This statement does the following:

  • Step #1: Uses the Application.ActiveWorkbook property to return the workbook in the current active window.
  • Step #2: Saves the active workbook in a file whose name is that given by the user through the Save As dialog displayed by the GetSaveAsFilename method.

In this particular case, only 1 argument of the Workbook.SaveAs method is used: Filename. The Filename argument, as implied by its name, allows you to specify the name of the saved workbook.

I explain more about the Filename argument, and the other arguments of the SaveAs method, in the sections below.

If the tested condition isn’t true, no further statements are executed. In other words, the workbook isn’t saved when the used has cancelled the Save As dialog box.

The Workbook.SaveAs Method: Parameters

The following table introduces the 10 most important optional parameters of the Workbook.SaveAs method:

Position Name Description
1 Filename Name of saved workbook.
2 FileFormat File format for saved workbook.
3 Password Protection password for saved workbook
4 WriteResPassword Write-reservation password for saved workbook.
5 ReadOnlyRecommended Determines whether workbook is saved as read-only recommended.
6 CreateBackup Determines whether a backup file of the saved workbook is created.
7 AccessMode Determines the access mode of the saved workbook.
8 ConflictResolution Applies only if saved workbook is shared.

Determines how conflicts that show up when saving are resolved.

9 AddToMru Determines whether saved workbook is added to list of recently used files.
12 Local Determines whether the workbook is saved against the language of Excel (usually local) or VBA (usually US-English).

2 parameters of the SaveAs method (#10, TextCodepage and #11, TextVisualLayout) aren’t included in the table above nor explained below. According to Microsoft’s Official Documentation (at the time of writing), both of these parameters are ignored.

Let’s take a closer look at each of the individual arguments of Workbook.SaveAs:

Argument #1: Filename

As implied by its name, you use the Filename argument of the Workbook.SaveAs method to specify the name of the saved workbook.

When working with the Filename argument, you can either:

  • Specify the full file path; or
  • Don’t specify the file path.

If you don’t specify the file path, Excel saves the workbook in the current folder.

For most users, specifying the file path isn’t very convenient. You (or the user) need to specify accurate file paths, names and extensions. The approach is tedious and error prone.

This is the main reason why the Application.GetSaveAsFilename used in the Save_Workbook_NewName is so helpful: it allows the user to browse the different folders and easily specify the full file path and name of the saved Excel workbook.

The initial basic version of the Save_Workbook_NewName macro uses the Filename argument, as shown in the screenshot below:

Argument #2: FileFormat

You can use the FileFormat argument of the Workbook.SaveAs method to specify the file format of the saved file.

If you don’t use the FileFormat argument, Excel determines the file format as follows:

  • In the case of workbooks that already exist, the workbook is saved using the same file format as the last time.
  • If the workbook is new, the workbook is saved using the format of the Excel version you’re using.

Even though this parameter (as all other arguments of the SaveAs method) is optional, you may want to develop the habit of using it.

You specify a particular file format using the XlFileFormat enumeration. The Microsoft Developer Network lists more than 50 different possible values.

In practice, you’re unlikely to need/use so many different formats. In fact, some of the formats that are listed at the Microsoft Developer Network are not supported in the more recent versions of Excel.

Therefore, I provide a basic overview and breakdown of the XlFileFormat values that you may actually encounter. Even though this list is much shorter than that at the Microsoft Developer Network, you’re still likely to use only a subset of the values I explain below.

The following are the 4 main file formats in Excel 2007-2013:

  • 50: xlExcel12.
  • 51: xlOpenXMLWorkbook.
  • 52: xlOpenXMLWorkbookMacroEnabled.
  • 56: xlExcel8.

As a general rule, it’s better to use the FileFormat values (numbers) instead of the names. The reason for this is that this avoids some compilation problems whenever you execute the relevant macro in an older version of Excel that may not recognize the name.

So let’s a look at some of the values that the FileFormat argument can take:

Value Name Description
Add-Ins And Templates
17 xlTemplate / xlTemplate8 Template / Template 8.

Generally used in versions between Excel 97 and Excel 2003.

18 xlAddIn / xlAddIn8 Excel 1997 to 2003 Add-In.
53 xlOpenXMLTemplateMacroEnabled Macro-Enabled Open XML template.
54 xlOpenXMLTemplate Open XML template.
55 xlOpenXMLAddIn Open XML Add-In.
Text Files
-4158 xlCurrentPlatformText Text file format for platform in which workbook is saved.
2 xlSYLK Symbolic Link Format file.

Only the active sheet is saved.

6 xlCSV CSV (comma-separated values) text file format.
9 xlDIF Data Interchange Format file.

Only saves the current active sheet.

19 xlTextMac Mac text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMac saves only the active sheet.

20 xlTextWindows Windows text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestWindows saves only the active sheet.

21 xlTextMSDOS MSDOS text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMSDOS saves only the active sheet.

22 xlCSVMac CSV file format for Mac platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMac saves only the active sheet.

23 xlCSVWindows CSV file format for Windows platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVWindows saves only the active sheet.

24 xlCSVMSDOS CSV file format for MS-DOS platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMSDOS saves only the active sheet.

36 xlTextPrinter Formatted text file.

Only saves the current active worksheet.

42 xlUnicodeText Unicode text file format.
Spreadsheets (Excel and Others)
-4143 xlWorkbookNormal Excel workbook file format.
39 xlExcel5 / xlExcel7 Excel versions from 1993 (Excel 5.0) and 1995 (Excel 7.0).
43 xlExcel9795 Excel versions from 1995 and 1997.

However, as explained by author Richard Mansfield in Mastering VBA for Microsoft Office 2013, this file format is generally compatible with Excel 95 and later versions.

46 xlXMLSpreadsheet XML spreadsheet file format.

Generally used in Excel 2003.

50 xlExcel12 Excel 2007 version.
51 xlOpenXMLWorkbook / xlWorkbookDefault Open XML workbook / Workbook default file format.
52 xlOpenXMLWorkbookMacroEnabled Macro-Enabled Open XML workbook.
56 xlExcel8 Excel version from 1997.
60 xlOpenDocumentSpreadsheet Open Document Spreadsheet file format.

OpenDocument Spreadsheet files can be opened using spreadsheet applications that use the OpenDocument Spreadsheet format. Examples of such applications are Google Sheets, Open Office Calc and Excel itself.

Formatting may be affected when saving or opening Open Document Spreadsheet files.

61 (&H3D) xlOpenXMLStrictWorkbook ISO Strict Open XML file format.
Clipboard Files
44 xlHtml HTML / webpage file format.

If you save the Excel workbook to a CSV or text file format, the following 2 things happen:

  • Excel selects the code page to use by checking the system locale configuration in the computer where the workbook is saved. The code page used is the one corresponding to the language for the system locale in use. In Windows 10, you can find these settings by going to Settings > Time & Language > Region & Language.
  • Excel saves the file in logical layout. This is relevant, in particular, when working with files containing bi-directional text, where text may be in different directions (left-to-right and right-to-left). Whenever text in one direction is embedded within text in the other direction, the logical layout saves the file in such a way that the reading order is correct for all languages being used, regardless of their directionality. Then, when such a file is opened later, all the text within the file is (generally) displayed in the appropriate direction. This direction is determined by the character value ranges of the code page being used.

Let’s go back to the sample Save_Workbook_NewName. The following screenshot shows how the VBA code of this macro looks like when I add the FileFormat argument and set its value to 52 (Macro-Enabled Open XML workbooks).

Argument #3: Password

The Password argument of the Workbook.SaveAs method allows you to (as you may expect) enter a password to protect the saved Excel workbook.

The Password argument has the following 3 main characteristics:

  • Is a string.
  • Is case-sensitive.
  • Its maximum length is 15 characters.

The following screenshot shows the VBA code behind the Save_Workbook_NewName macro with a password. In this case, the password is “Excel Tutorial”.

If you save a workbook using a macro such as the above, next time anyone (you or another user) tries to open the Excel workbook, Excel displays the Password dialog.

If the wrong password is entered, Excel doesn’t open the workbook. Instead, it displays a warning.

Argument #4: WriteResPassword

The WriteResPassword parameter of the Workbook.SaveAs method is, in some ways, similar to the Password argument that I explain above. However, Password and WriteResPassword differ in one essential characteristic:

They protect different things.

As explained above, Password protects the workbook. If you (or the relevant user) fail to provide the correct password, Excel doesn’t open the workbook.

WriteResPassword protects the write-reservation characteristic of the workbook. To see what this is, and how it works in practice, I add the WriteResPassword argument to the Save_Workbook_NewName macro. The password for these purposes is “Excel Course”.

The dialog box that Excel displays to ask for the WriteResPassword is slightly different than the one it uses when asking for the Password. Notice how it informs that the user who has saved the workbook reserved it and provides 2 options:

  • You can enter the password and Excel grants you write access.
  • Otherwise, you can open the workbook as read-only.

If I choose to open the workbook as read-only, Excel does precisely so. In that case, it warns in a few places that the workbook is read-only and changes aren’t saved.

If you enter the wrong WriteResPassword, Excel reacts in the same way as it does when you enter the wrong Password (as shown above). In other words, it doesn’t open the workbook and displays the following message:

Argument #5: ReadOnlyRecommended

The ReadOnlyRecommended argument provides you with a less strict way (when compared with the WriteResPassword above) to protect the Excel workbook you’re saving.

More precisely, if you set a particular workbook to be read-only recommended, Excel displays a message making such recommendation whenever the file is opened.

Setting a workbook to be read-only recommended doesn’t actually protect or reserve the workbook in the same way as the Password or the WriteResPassword do. Any user can open a read-only recommended Excel workbook normally (not as read-only) by, for example:

  • Clicking “No” in the dialog box above.
  • Setting the IgnoreReadOnlyRecommended argument of the Workbooks.Open argument to True when opening the workbook using VBA.

To determine that an Excel workbook is read-only recommended, you simply set the ReadOnlyRecommended argument to True.

Argument #6: CreateBackup

The CreateBackup argument of the Workbook.SaveAs method allows you to determine whether a backup of the workbook being saved is created.

If you want to create a backup of the saved Excel workbook, set the CreateBackup argument to True.

Argument #7: AccessMode

The AccessMode argument allows you to specify the access mode for the saved workbook. This argument can take the following 3 values:

  • 1: Stands for xlNoChange. In this case, the default access mode is used.
  • 2: Represents xlShared. In this case, the access mode is share list.
  • 3: Value for xlExclusive. In this scenario, access mode is exclusive mode.

The following screenshot shows the VBA code of the Save_Workbook_NewName macro with the AccessMode parameter set to xlNoChange:

Argument #8: ConflictResolution

ConflictResolution applies when you’re working with shared workbooks. More precisely, this argument allows you to determine how conflicts (while saving the Excel workbook) are resolved.

You can set the ConflictResolution parameter to any of the following 3 values:

  • 1: Stands for xlUserResolution. In this case, Excel displays a dialog box asking the user to resolve the conflict. This is the default setting in case you omit the ConflictResolution argument.
  • 2: Represents xlLocalSessionChanges. If you choose this value, the changes made by the local user are accepted always.
  • 3: The value for xlOtherSessionChanges. This is the opposite from the above: the changes made by the local user are rejected always.

The following screenshot shows the code of the Save_Workbook_NewName macro with the ConflictResolution parameter set to the default xlUserResolution.

Argument #9: AddToMru

MRU stands for Most Recently Used. This makes reference to Excel’s list of most recently used files which, generally, you find on the Backstage View.

The AddToMru argument of the Workbook.Save method allows you to determine whether the saved workbook is added to this most recently used list.

If AddToMru is set to True, the Excel workbook is added to the list. The default value of AddToMru is, however, False.

In the following image, you can see the VBA code behind the sample Save_Workbook_NewName macro with AddToMru set to True:

As mentioned above, I’m not covering in detail the TextCodePage and TextVisualLayout arguments (arguments #10 and #11).

Argument #12: Local

The last argument of the Workbook.SaveAs method is Local. As implied by its name, Local refers to language and localization aspects of the saved workbook.

More precisely, the Local parameter allows you to determine whether the saved workbook is saved against the language of:

  • Excel, as generally determined from the control panel setting; or
  • VBA, which is usually US-English. The basic exception to this rule of VBA’s language being US-English occurs when the VBA project that executes the Workbook.SaveAs method is an internationalized XL5/95 VBA project. My guess is that you’re unlikely to work with such projects often.

To determine how Excel proceeds in connection with this topic, you can set the Local argument to True or False.

  • True: Saves the workbook against Excel’s language.
  • False: Saves the Excel workbook against VBA’s language.

In the following image, you can see the sample Save_Workbook_NewName with the Local parameter set to True:

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method

The Save and SaveAs methods explained above are the basic methods you’ll need to save Excel workbooks using VBA.

However, both of these methods save and modify the current open Excel workbook. You may encounter some situations where this isn’t the outcome you desire.

In other words, you’ll probably be in situations where you want a macro to simply:

  • Save a copy of the current Excel workbook, but…
  • Don’t actually modify the current file in the memory of the computer.

These type of situations are great for using the Workbook.SaveCopyAs VBA method. This method does precisely this. It takes the workbook and:

  • Saves a copy to a file.
  • Doesn’t modify it in memory.

The syntax of the SaveCopyAs method is, once again, relatively simple:

Just as with the other methods explored in this Excel tutorial, “expression” represents a Workbook object. “Filename”, the only parameter of the SaveCopyAs method is the full file path, name and extension of the copy that you’re saving.

Since you’re likely to use this method on the active workbook most of the time, you’ll probably end up using the following syntax often:

Another commonly used alternative is to use the ThisWorkbook property instead of ActiveWorkbook. The main difference between ThisWorkbook and ActiveWorkbook is that:

  • ActiveWorkbook refers to the current active workbook.
  • ThisWorkbook refers to the workbook where the macro is actually stored.

Let’s take a look at an example of a macro that uses the Workbook.SaveCopyAs method to save a copy of the current active workbook:

The screenshot below shows a macro called “Save_Copy_Workbook”.

This macro has a single (quite long) statement. This goes as follows:

ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice that the structure I use in the Save_Copy_Workbook macro follows the basic syntax of the Workbook.SaveCopyAs method explained above. However, let’s split the statement in 2 parts in order to understand better what’s going on, and what can this particular method do for you:

Part #1: ActiveWorkbook.SaveCopyAs

This is the reference to the SaveCopyAs method. It follows the basic syntax explained above.

“ActiveWorkbook” makes reference to the Application.Workbook property. This property returns a Workbook object representing the current active workbook. This active workbook is the one which is manipulated by the SaveCopyAs method.

In other words, the statement simply tells Excel to proceed as follows:

  • Step #1: Take the current active workbook.
  • Step #2: Save a copy of the current active workbook, without actually modifying it in memory.

Part #2: Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

This part of the statement specifies the only argument of the Workbook.SaveCopyAs method:

This particular file name for the copy is slightly long but, basically, is built by concatenating 5 items. You use the ampersand (&) operator to concatenate the different items.

Item #1: ActiveWorkbook.Path

This makes reference to the Workbook.Path property. The Path property returns the complete path to the relevant workbook.

In the case of the example above, “ActiveWorkbook.Path” is used to get the path to the current active workbook.

Let’s assume, for example, that the current active workbook (called “Book1”) is saved in the D drive. In this case the path is, simply “D:”.

This sample path (D:) isn’t very long or complicated. However, in practice, you’re more likely to work with longer and more complicated paths that you are to work with just the D drive.

Items #2 And #4: “Copy ” and ” “

This are, simply, text strings. The first string specifies that the first word in the file name is “Copy”. The second string adds a space ( ).

Item #3: Format(Now, “yy-mm-dd”)

This particular statement uses 2 VBA built-in functions, as follows:

  • Now returns today’s date and the current time. Alternatively, you can use the Date function, which returns the current date.
  • Format takes the date returned by Now and formats it according to the date format “yy-mm-dd”.

In other words, this part of the argument is responsible for returning the date in which the copy is saved in the format yy-mm-dd.

For example, if the date in which you save the copy of the workbook is November 30 of 2015, this item returns 15-11-30.

Item #5: ActiveWorkbook.Name

This item uses the Workbook.Name property to get the name of the workbook.

For example, if the name of the workbook is “Best Excel Tutorial”, Workbook.Name returns exactly that.

In order to make everything clear regarding the Workbook.SaveCopyAs method, let’s take a look at an example:

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method: An Example

Let’s assume that the current active workbook is called “Best Excel Tutorial” and is saved in the D drive (D:). This is how the D drive looks like before I run the sample Save_Copy_Workbook macro:

The following screenshot shows how the same drive looks after I run the macro. Notice how, now, there’s a new Excel workbook. This is the copy created by the Save_Copy_Workbook Sub procedure.

Let’s go back to the Filename argument of the SaveCopyAs method used within the Save_Copy_Workbook macro:

Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice how, each of the 5 items explained above expresses itself in practice once the macro is run:

  • Item #1: The copy is saved in the same folder as the original workbook, as given by the Workbook.Path property.
  • Items #2 and #4: The first word in the actual workbook name is Copy, as determined by the string “Copy”. Also, there is a space between the date (15-11-19) and the original workbook’s name (Best Excel Tutorial) as specified by ” “.
  • Item #3: The date in which the workbook is saved (November 19 of 2015 in the example above) is added to the name in the format yy-mm-dd (15-11-19).
  • Item #5: The name of the original workbook (Best Excel Tutorial) is added at the end of the copy’s name.

The following image shows this:

How To Name A Workbook Using The Application.GetSaveAsFilename Method

I introduced the Application.GetSaveAsFilename method above. This method is used by one of the sample macros (Save_Workbook_NewName) for purposes of opening the Save As dialog box and allow users to easily browse and enter the path, name and file extension of the saved Excel workbook.

The screenshot below shows the VBA code of the Save_Workbook_NewName macro. Notice the presence of the Application.GetSaveAsFilename method.

The Application.GetSaveAsFilename method doesn’t actually save a file. However, GetSaveAsFilename is a helpful method to use whenever you have a macro that needs to get a file name from the user in order to, among others, save a workbook.

GetSaveAsFilename is useful when the procedure needs to receive/know the name of the file to save. This gives the user the possibility of specifying the file’s path and filename.

As I explain below, you can use the Application.GetSaveAsFilename method precisely for these purposes.

The GetSaveAsFilename method has a few parameters that allow you to customize some of its characteristics. Let’s take a closer look at the method itself and its arguments, starting with:

The Application.GetSaveAsFilename Method: Purpose

The Application.GetSaveAsFilename method does 2 things:

  1. Displays the Save As dialog box.
  2. Gets the file name entered by the user in the Save As dialog box.

GetSaveAsFilename doesn’t save a workbook by itself. That’s why, for example, the Save_Workbook_NewName macro above includes uses the Workbook.SaveAs method to actually save the Excel workbook.

The Application.GetSaveAsFilename Method: Syntax

The full syntax of the Application.GetSaveAsFilename method is as follows:

expression.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)

“expression” is used to represent the Application object. You’re, therefore, likely to usually use the following basic syntax for this method:

This is the syntax used in the version of the Save_Workbook_NewName method shown above.

All of the 5 arguments of the GetSaveAsFilename method are optional. Let’s take a look at them:

The Application.GetSaveAsFilename Method: Arguments

The following table provides a basic description of the 5 parameters of the Application.GetSaveAsFilename method. I explain each of them more thoroughly below.

Position Name Description
1 InitialFilename Specifies a suggested/default file name.
2 FileFilter Determines file filtering criteria.
3 FilterIndex Determines the default file filter.
4 Title Determines the title of the (usually called) Save As dialog box.
5 ButtonText Applies only in the Mac platform.

Determines the text of the (normally called) Save As button.

There are quite a few similarities between the GetSaveAsFilename method and the GetOpenFilename method (which I describe here). In terms of their arguments, the main differences are as follows:

  • GetSaveAsFilename has the InitialFilename argument. GetOpenFilename doesn’t.
  • GetOpenFilename has the MultiSelect argument. GetSaveAsFilename doesn’t.

Both of these differences make sense. For example, MultiSelect allows you to determine whether a user can select multiple file names at the same time. This makes sense in the context of opening files. But not in the context of saving files with the GetSaveAsFilename method.

Let’s take a look at each of the parameters introduced above:

Argument #1: InitialFilename

The InitialFilename of the Application.GetSaveAsFilename method allows you to set a suggested file name. This suggested file name is the one that appears, by default, in the File name box of the Save As dialog.

The Save As dialog box displayed above is the result of running the following version of the Save_Workbook_NewName macro. Notice that the InitialFilename argument is added and the suggested name is “Best Excel Tutorial”, as displayed in the image above.

Argument #2: FileFilter

The FileFilter argument of the Application.GetSaveAsFilename method allows you to determine the criteria for file filtering within the Save As dialog box.

These file filtering criteria determine what appears in the Save as type drop-down list box of the Save As dialog box. If you omit the FileFilter argument, the default (as shown in the image below) is All Files.

This isn’t ideal because it may lead to the saved Excel workbook being of an unrecognizable file type if the user doesn’t enter the file extension when saving the file.

However, my guess is that you’ll be in situations where specifying the file filtering criteria is more convenient or, even, necessary. In order to be able to determine which file filters appear in the Save As dialog box, you’ll need to follow the 4 guidelines below.

Don’t worry if the guidelines don’t seem that clear at first. I show you a practical example of VBA code after making the introduction and basic description.

Guideline #1: Each Filter Consists Of A Pair Of Strings.

Each filter you specify when using the FileFilter argument is made up of 2 strings separated by a comma. This looks, roughly, as follows:

String1 and String2 have different structures and purposes. More precisely:

  • String1: Is a descriptive string. This string determines what actually appears in the Save as type drop-down box of the Save As dialog box.
  • String2: Is the MS-DOS wildcard file-type filter specification. In other words, this string determines how the files are actually filtered depending on their file format.

You don’t need to follow many guidelines regarding the way in which the first string (String1) is specified. However, you do need to follow a more specific syntax when specifying the second string (String2). Let’s take a look at it:

Guideline #2: Syntax To Specify The File-Type Filter.

The second string that you use to specify a file filter is itself composed of 3 elements which are, generally speaking, as follows:

  • Element #1: An asterisk (*), used as a wildcard.
  • Element #2: A dot (.).
  • Element #3: An indication of the file extension used to filter the files. This particular element is usually composed of (where appropriate) an asterisk (*), used as a wildcard, and/or (if appropriate), some text.

The most basic filter is all files, which in practice means that there’s no filter. To specify a file-type filter than includes all files using the syntax above, you’d type asterisk dot asterisk (*.*).

Other examples of file-type filter specifications following this syntax are the following:

  • *.txt for text files.
  • *.xla for add-ins.
  • *.xlsx for Excel workbooks.
  • *.xlsm for Macro-Enable Excel workbooks.
  • *.xls for Excel 97 to Excel 2003 workbooks.
  • *.csv for CSV files.

Knowing these first 2 guidelines is enough for you to start using the FileFilter argument. However, they only explain how to specify a single filter according to a single file type.

However, when working with FileFilter, you can actually specify:

  • Several different filters; as well as
  • Several different file types for each filter.

The next 2 guidelines show how you can do each of these:

Guideline #3: Syntax To Specify Several Filters.

You can create more than a single filter with the FileFilter argument. In order to so, use commas (,) to separate the filters. In other words, separate each of the pair of strings that constitute a filter from the other pair of strings by using commas (,).

This looks, roughly, as follows:

Guideline #4: Syntax To Specify Several File Types In A Single Filter.

If you need to filter according to several different data types, you can use several filters by using the syntax explained above.

Alternatively, you can specify several data types for a particular single filter. To do this, separate the MS-DOS wildcard expressions that you use with semicolons (;). This looks roughly as follows:

Those are the 4 basic guidelines you need to bear in mind to start using the FileFilter argument. Let’s go back to the Save_Workbook_NewName macro and create some file filters:

The following screenshot shows (again) the VBA code behind Save_Workbook_NewName. Notice that the FileFilter argument has been inserted and its syntax follows all of the guidelines I explained above.

To make this clearer, let’s break the argument value into its different parts and highlight how it complies with all of the guidelines described above.

The complete argument is as follows:

“Excel Workbook,*.xlsx,Excel Macro-Enabled Workbook,*xlsm,Excel Templates,*.xltx;*.xltm”

Notice the following things:

    There are 3 filters. Each of the filters is separated from the other by commas (,).

Each filter is composed of 2 parts: a descriptive string and the relevant MS-DOS wildcard file-type filter specification. These 2 parts are separated by commas (,).

MS-DOS wildcard file-type filter specifications follow the syntax described above: (i) asterisk (*); (ii) dot (.); and (iii) file extension specification, without wildcard asterisks in this case.

The last filter uses 2 different file types. These file types are separated by a semicolon (;).

The following image shows how all of the above looks like in practice. Notice how, now, there are 3 different options within the Save as Type box of the Save As dialog box. These 3 filters are those created by the FileFilter argument of the Application.GetSaveAsFilename method.

Argument #3: FilterIndex

Notice how, in the image above, the default file filtering criteria is “Excel Workbook”. This is the first filter that was specified with the FileFilter argument.

You can, however, change the default file filtering criteria by using the FilterIndex argument. You do this by specifying the index number of the criteria you want to set as default.

As a consequence of the above, the FilterIndex argument can take any value between 1 (the first filter) and the number of filters you’ve specified with the FileFilter argument (3 in the example above).

If you set the FilterIndex value to a number higher than the amount of available filters (4 or higher in the case of the Save_Workbook_NewName macro), the first filter is used. In other words, the practical result of specifying an index number that is too high, is the same as that of omitting the FilterIndex parameter.

The following screenshot shows the code of the Save_Workbook_NewName macro with the FilterIndex parameter set to 2.

In the case of this macro, a FilterIndex value of 2 means that “Excel Macro-Enabled Workbook” is the new default filter.

Argument #4: Title

The Title argument of the Application.GetSaveAsFilename method allows you to modify the title of the (usually called) Save As dialog box. If you omit the argument, the default title (Save As) is maintained.

The following image shows how this argument can be used to change the title of the Save As dialog box when executing the Save_Workbook_NewName macro. In this case, the Title argument is set to “VBA Save Excel Workbook”.

When this macro is executed, the (previously called) Save As dialog looks as follows. Notice that the title has indeed changed to “VBA Save Excel Workbook”.

Argument #5: ButtonText

The ButtonText parameter is only applicable in the Mac platform. If you use this argument in Windows, it’s simply ignored.

For those cases where it is applicable, the ButtonText argument allows you to set the text that appears in the (usually known as) Save button.

Conclusion

Knowing how to save Excel workbooks using VBA is essential.

If you’ve read this Excel tutorial, you now know the basics of how to save workbooks using VBA. In fact, you’ve seen 3 different ways to achieve this:

  • Using the Workbook.Save method.
  • Using the Workbook.SaveAs method.
  • Using the Workbook.SaveCopyAs method.

Each of these cases is explained with the help of a real example of VBA code.

Источник

If you’ve worked with Excel before, you’re probably quite familiar with 2 basic commands for saving workbooks:

  • Save.
  • Save As.

Excel VBA Tutorial about how to save workbooks and filesIt may not surprise you to know that, when working with VBA, you can carry out these same activities.

In fact, knowing how to save Excel workbooks using VBA is essential. As you work with Visual Basic for Applications, you’ll notice that saving workbooks is one of the most important things your macros can do.

Due to the importance of knowing how to save workbooks using VBA, this Excel tutorial focuses on this particular topic:

How to save an Excel workbook using VBA.

In addition to providing some examples of VBA code that you can use to save workbooks, I explain the basics surrounding 4 VBA methods that you’re likely to encounter and use constantly while saving workbooks. The following table of contents shows the specific topics that I explain in this Excel tutorial:

This Excel tutorial doesn’t cover the topic of saving an Excel workbook as PDF using VBA. I explain how to export an Excel file to PDF using macros, and provide several code examples, here.

Let’s start taking a look at the basic ways to save an Excel workbook using VBA.

How To Save An Excel Workbook Using the Workbook.Save VBA Method

The most basic method to save Excel workbooks using VBA is the Workbook.Save method. Workbook.Save saves the relevant workbook.

In other words, the Workbook.Save method is, roughly, the VBA equivalent of the Save command in Excel.

The syntax of the Workbook.Save method is as follows:

expression.Save

Where “expression” is the relevant Workbook object you want to save.

Let’s take a look at an example to make this clearer. The following macro, named “Save_Workbook”, saves the current active workbook:

ActiveWorkbook.Save macro

This Excel VBA Save Workbook Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Save_Workbook macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Notice that the macro has only 1 statement which follows the general syntax of the Workbook.Save method explained above:

ActiveWorkbook.Save

In this case, ActiveWorkbook is a simplified reference to the Application.ActiveWorkbook property. This property returns a Workbook object, as required by the Workbook.Save method. The workbook that is returned by the ActiveWorkbook property is, more precisely, the workbook in the current active window.

In summary, the sample Save_Workbook macro above simply saves the current active Excel workbook.

Just as when working directly with Excel, the Save method is an important command/method that is relatively easy and straightforward to execute. However, it doesn’t allow you to determine much in connection with the way the relevant Excel workbook is saved. The workbook is saved and that’s pretty much it.

When working directly in Excel, you use the Save As command if you want to be able to determine more about the way the actual saving of a workbook takes place. Things work in a similar fashion within Visual Basic for Applications.

More precisely, when working with Visual Basic for Applications, you can use the SaveAs method for these purposes. So let’s take a look at:

How To Save An Excel Workbook Using The Workbook.SaveAs VBA Method

The arguments or parameters of a method are what allows you to determine the characteristics of the action that a particular method performs.

As explained above, the Workbook.Save method doesn’t have any parameters. As a consequence, you can’t really determine much about how the relevant workbook is saved.

The Workbook.SaveAs method is different. Its 12 parameters allow you to further determine several aspects about the way in which an Excel workbook is saved. In other words, Workbook.SaveAs is more flexible and complex than Workbook.Save.

Workbook.SaveAs is, roughly speaking, the VBA equivalent of the Save As command in Excel. Therefore, it allows you to save a workbook in a particular file. The complete syntax of the Workbook.SaveAs method is as follows:

expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode,ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

“expression” is, just as in the case of the Workbook.Save method above, the relevant Workbook object.

All of the parameters (which appear within parentheses) of the SaveAs method are optional. However, in order to understand what this method can help you with, I explain these parameters below.

However, as usual, I use a practical macro example for purposes of illustrating how Workbook.SaveAs works. So let’s start by taking a look at the basic VBA code of the macro example:

How To Save An Excel Workbook With A New Name Using The Workbook.SaveAs Method

The following piece of VBA code saves the current active workbook with a new name provided by the user.

Dim workbook_Name As Variant

workbook_Name = Application.GetSaveAsFilename

If workbook_Name <> False Then

ActiveWorkbook.SaveAs Filename:=workbook_Name

End If

The following screenshot shows the VBA code behind the example macro (called “Save_Workbook_NewName”) which is included in the Excel workbook that accompanies this Excel VBA Save Workbook Tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

VBA code with ActiveWorkbook.SaveAs

This macro can be divided in the following 3 parts:

Save workbook VBA code with sections

Let’s take a quick look at each of these parts to understand how the Save_Workbook_NewName macro works:

Part #1: Dim workbook_Name As Variant

This statement simply declares a variable named workbook_Name. The variable is of the Variant data type.

Even though Variant variables are sometimes undesirable, in this particular case that’s not necessarily the case. A Variant variable allows the GetSaveAsFilename (which I introduce below) to be quite flexible.

As implied by its name, and made evident by the following parts of the macro, the purpose of the workbook_Name variable is to store the new name of the saved Excel workbook.

Part #2: workbook_Name = Application.GetSaveAsFilename

This statement assigns a value to the workbook_Name variable. Which value is actually assigned is determined by the Application.GetSaveAsFilename method, which I explain thoroughly below.

At its most basic level, the GetSaveAsFilename method, does the following 2 things:

  • Step #1: Displays the Save As dialog box.

    You’re probably quite familiar with this dialog box, as it’s the one Excel displays when you execute the Save As command.

    Save As dialog displayed by GetSaveAsFilename

  • Step #2: Once the user has provided a file name through the Save As dialog box, GetSaveAsFilename gets that particular name.

    This is the name that the whole statement we’re analyzing assigns to the variable workbook_Name.

Note that the Application.GetSaveAsFilename method doesn’t actually save a file. It simply gets a name.

To actually save the file using the name provided by the GetSaveAsFilename method, you usually rely on the Workbook.SaveAs method. This method is used in the last part of the Save_Workbook_NewName macro:

Part #3: If workbook_Name <> False Then ActiveWorkbook.SaveAs Filename:=workbook_Name End If

This is an If… Then… Else statement. These type of statements conditionally execute a particular group of statement depending on whether a condition is met or not. The statement begins with the word If. The whole block finishes with the End If statement.

In the case of the Save_Workbook_NewName macro, the If… Then… Else statement proceeds as follows:

Step #1: Test Whether workbook_Name <> False.

The first part of the If… Then… Else statement carries out a logical test. This logical test seeks to confirm whether the variable workbook_Name has a value that is different from (<>) the logical value False.

If the value of workbook_Name isn’t False, the logical test (workbook_Name <> False) evaluates to True. In such a case, the statements within the If… Then… Else are executed.

However, if the value of workbook_Name is equal to the Boolean value False, the logical test evaluates to False. In this case, the conditional statements aren’t executed.

For purposes of this logical test, the value of the variable workbook_Name is that assigned in the previous part. Therefore, the value depends on the input given by the user when the Save As dialog box is displayed. More precisely:

  • If the user cancels the Save As dialog box, the value of workbook_Name is False.
  • If the user provides a file name through the Save As dialog box, the value of the workbook_Name variable is (generally) that assigned by the user.

In other words:

  • If the user provides a file name:
    • The logical test carried out by the first part of the If… Then… Else statement is True; and
    • The conditional statements that follow are executed.
  • If the user cancels the Save As dialog box (by, for example, clicking on the Cancel button):
    • The logical test is False; and
    • The conditional statements within the If… Then… Else statement aren’t executed.

Step#2: Execute The Statement ActiveWorkbook.SaveAs Filename:=workbook_Name If The Tested Condition Is True.

You already know that, roughly speaking, the logical test workbook_Name <> False returns True if the user has assigned a file name through the Save As dialog box.

In such case, the following statement is executed:

ActiveWorkbook.SaveAs Filename:=workbook_Name

This is where the Workbook.SaveAs method comes into play. This statement does the following:

  • Step #1: Uses the Application.ActiveWorkbook property to return the workbook in the current active window.
  • Step #2: Saves the active workbook in a file whose name is that given by the user through the Save As dialog displayed by the GetSaveAsFilename method.

In this particular case, only 1 argument of the Workbook.SaveAs method is used: Filename. The Filename argument, as implied by its name, allows you to specify the name of the saved workbook.

I explain more about the Filename argument, and the other arguments of the SaveAs method, in the sections below.

If the tested condition isn’t true, no further statements are executed. In other words, the workbook isn’t saved when the used has cancelled the Save As dialog box.

The Workbook.SaveAs Method: Parameters

The following table introduces the 10 most important optional parameters of the Workbook.SaveAs method:

Position Name Description
1 Filename Name of saved workbook.
2 FileFormat File format for saved workbook.
3 Password Protection password for saved workbook
4 WriteResPassword Write-reservation password for saved workbook.
5 ReadOnlyRecommended Determines whether workbook is saved as read-only recommended.
6 CreateBackup Determines whether a backup file of the saved workbook is created.
7 AccessMode Determines the access mode of the saved workbook.
8 ConflictResolution Applies only if saved workbook is shared.

Determines how conflicts that show up when saving are resolved.

9 AddToMru Determines whether saved workbook is added to list of recently used files.
12 Local Determines whether the workbook is saved against the language of Excel (usually local) or VBA (usually US-English).

2 parameters of the SaveAs method (#10, TextCodepage and #11, TextVisualLayout) aren’t included in the table above nor explained below. According to Microsoft’s Official Documentation (at the time of writing), both of these parameters are ignored.

Let’s take a closer look at each of the individual arguments of Workbook.SaveAs:

Argument #1: Filename

As implied by its name, you use the Filename argument of the Workbook.SaveAs method to specify the name of the saved workbook.

When working with the Filename argument, you can either:

  • Specify the full file path; or
  • Don’t specify the file path.

If you don’t specify the file path, Excel saves the workbook in the current folder.

For most users, specifying the file path isn’t very convenient. You (or the user) need to specify accurate file paths, names and extensions. The approach is tedious and error prone.

This is the main reason why the Application.GetSaveAsFilename used in the Save_Workbook_NewName is so helpful: it allows the user to browse the different folders and easily specify the full file path and name of the saved Excel workbook.

The initial basic version of the Save_Workbook_NewName macro uses the Filename argument, as shown in the screenshot below:

VBA code saves workbook with Filename argument

Argument #2: FileFormat

You can use the FileFormat argument of the Workbook.SaveAs method to specify the file format of the saved file.

If you don’t use the FileFormat argument, Excel determines the file format as follows:

  • In the case of workbooks that already exist, the workbook is saved using the same file format as the last time.
  • If the workbook is new, the workbook is saved using the format of the Excel version you’re using.

Even though this parameter (as all other arguments of the SaveAs method) is optional, you may want to develop the habit of using it.

You specify a particular file format using the XlFileFormat enumeration. The Microsoft Developer Network lists more than 50 different possible values.

In practice, you’re unlikely to need/use so many different formats. In fact, some of the formats that are listed at the Microsoft Developer Network are not supported in the more recent versions of Excel.

Therefore, I provide a basic overview and breakdown of the XlFileFormat values that you may actually encounter. Even though this list is much shorter than that at the Microsoft Developer Network, you’re still likely to use only a subset of the values I explain below.

The following are the 4 main file formats in Excel 2007-2013:

  • 50: xlExcel12.
  • 51: xlOpenXMLWorkbook.
  • 52: xlOpenXMLWorkbookMacroEnabled.
  • 56: xlExcel8.

As a general rule, it’s better to use the FileFormat values (numbers) instead of the names. The reason for this is that this avoids some compilation problems whenever you execute the relevant macro in an older version of Excel that may not recognize the name.

So let’s a look at some of the values that the FileFormat argument can take:

Value Name Description
Add-Ins And Templates
17 xlTemplate / xlTemplate8 Template / Template 8.

Generally used in versions between Excel 97 and Excel 2003.

18 xlAddIn / xlAddIn8 Excel 1997 to 2003 Add-In.
53 xlOpenXMLTemplateMacroEnabled Macro-Enabled Open XML template.
54 xlOpenXMLTemplate Open XML template.
55 xlOpenXMLAddIn Open XML Add-In.
Text Files
-4158 xlCurrentPlatformText Text file format for platform in which workbook is saved.
2 xlSYLK Symbolic Link Format file.

Only the active sheet is saved.

6 xlCSV CSV (comma-separated values) text file format.
9 xlDIF Data Interchange Format file.

Only saves the current active sheet.

19 xlTextMac Mac text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMac saves only the active sheet.

20 xlTextWindows Windows text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestWindows saves only the active sheet.

21 xlTextMSDOS MSDOS text file format. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlTestMSDOS saves only the active sheet.

22 xlCSVMac CSV file format for Mac platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMac saves only the active sheet.

23 xlCSVWindows CSV file format for Windows platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVWindows saves only the active sheet.

24 xlCSVMSDOS CSV file format for MS-DOS platform. Ensures that basic formatting (such as tab and line breaks) and characters are interpreted correctly.

xlCSVMSDOS saves only the active sheet.

36 xlTextPrinter Formatted text file.

Only saves the current active worksheet.

42 xlUnicodeText Unicode text file format.
Spreadsheets (Excel and Others)
-4143 xlWorkbookNormal Excel workbook file format.
39 xlExcel5 / xlExcel7 Excel versions from 1993 (Excel 5.0) and 1995 (Excel 7.0).
43 xlExcel9795 Excel versions from 1995 and 1997.

However, as explained by author Richard Mansfield in Mastering VBA for Microsoft Office 2013, this file format is generally compatible with Excel 95 and later versions.

46 xlXMLSpreadsheet XML spreadsheet file format.

Generally used in Excel 2003.

50 xlExcel12 Excel 2007 version.
51 xlOpenXMLWorkbook / xlWorkbookDefault Open XML workbook / Workbook default file format.
52 xlOpenXMLWorkbookMacroEnabled Macro-Enabled Open XML workbook.
56 xlExcel8 Excel version from 1997.
60 xlOpenDocumentSpreadsheet Open Document Spreadsheet file format.

OpenDocument Spreadsheet files can be opened using spreadsheet applications that use the OpenDocument Spreadsheet format. Examples of such applications are Google Sheets, Open Office Calc and Excel itself.

Formatting may be affected when saving or opening Open Document Spreadsheet files.

61 (&H3D) xlOpenXMLStrictWorkbook ISO Strict Open XML file format.
Clipboard Files
44 xlHtml HTML / webpage file format.

If you save the Excel workbook to a CSV or text file format, the following 2 things happen:

  • Excel selects the code page to use by checking the system locale configuration in the computer where the workbook is saved. The code page used is the one corresponding to the language for the system locale in use. In Windows 10, you can find these settings by going to Settings > Time & Language > Region & Language.
  • Excel saves the file in logical layout. This is relevant, in particular, when working with files containing bi-directional text, where text may be in different directions (left-to-right and right-to-left). Whenever text in one direction is embedded within text in the other direction, the logical layout saves the file in such a way that the reading order is correct for all languages being used, regardless of their directionality. Then, when such a file is opened later, all the text within the file is (generally) displayed in the appropriate direction. This direction is determined by the character value ranges of the code page being used.

Let’s go back to the sample Save_Workbook_NewName. The following screenshot shows how the VBA code of this macro looks like when I add the FileFormat argument and set its value to 52 (Macro-Enabled Open XML workbooks).

VBA code saves workbook with FileFormat argument

Argument #3: Password

The Password argument of the Workbook.SaveAs method allows you to (as you may expect) enter a password to protect the saved Excel workbook.

The Password argument has the following 3 main characteristics:

  • Is a string.
  • Is case-sensitive.
  • Its maximum length is 15 characters.

The following screenshot shows the VBA code behind the Save_Workbook_NewName macro with a password. In this case, the password is “Excel Tutorial”.

VBA code to save workbook with Password argument

If you save a workbook using a macro such as the above, next time anyone (you or another user) tries to open the Excel workbook, Excel displays the Password dialog.

Password dialog box generated by VBA

If the wrong password is entered, Excel doesn’t open the workbook. Instead, it displays a warning.

Excel warns about incorrect password

Argument #4: WriteResPassword

The WriteResPassword parameter of the Workbook.SaveAs method is, in some ways, similar to the Password argument that I explain above. However, Password and WriteResPassword differ in one essential characteristic:

They protect different things.

As explained above, Password protects the workbook. If you (or the relevant user) fail to provide the correct password, Excel doesn’t open the workbook.

WriteResPassword protects the write-reservation characteristic of the workbook. To see what this is, and how it works in practice, I add the WriteResPassword argument to the Save_Workbook_NewName macro. The password for these purposes is “Excel Course”.

VBA code to save workbook with WriteResPassword

The dialog box that Excel displays to ask for the WriteResPassword is slightly different than the one it uses when asking for the Password. Notice how it informs that the user who has saved the workbook reserved it and provides 2 options:

  • You can enter the password and Excel grants you write access.
  • Otherwise, you can open the workbook as read-only.

Password dialog for WriteResPassword generated by VBA

If I choose to open the workbook as read-only, Excel does precisely so. In that case, it warns in a few places that the workbook is read-only and changes aren’t saved.

Excel warns workbook is read-only

If you enter the wrong WriteResPassword, Excel reacts in the same way as it does when you enter the wrong Password (as shown above). In other words, it doesn’t open the workbook and displays the following message:

Incorrect WriteResPassword warning in Excel

Argument #5: ReadOnlyRecommended

The ReadOnlyRecommended argument provides you with a less strict way (when compared with the WriteResPassword above) to protect the Excel workbook you’re saving.

More precisely, if you set a particular workbook to be read-only recommended, Excel displays a message making such recommendation whenever the file is opened.

Excel message when opening read-only recommended workbook

Setting a workbook to be read-only recommended doesn’t actually protect or reserve the workbook in the same way as the Password or the WriteResPassword do. Any user can open a read-only recommended Excel workbook normally (not as read-only) by, for example:

  • Clicking “No” in the dialog box above.
  • Setting the IgnoreReadOnlyRecommended argument of the Workbooks.Open argument to True when opening the workbook using VBA.

To determine that an Excel workbook is read-only recommended, you simply set the ReadOnlyRecommended argument to True.

VBA code to save workbook with ReadOnlyRecommended

Argument #6: CreateBackup

The CreateBackup argument of the Workbook.SaveAs method allows you to determine whether a backup of the workbook being saved is created.

If you want to create a backup of the saved Excel workbook, set the CreateBackup argument to True.

VBA code saves workbook and creates backup

Argument #7: AccessMode

The AccessMode argument allows you to specify the access mode for the saved workbook. This argument can take the following 3 values:

  • 1: Stands for xlNoChange. In this case, the default access mode is used.
  • 2: Represents xlShared. In this case, the access mode is share list.
  • 3: Value for xlExclusive. In this scenario, access mode is exclusive mode.

The following screenshot shows the VBA code of the Save_Workbook_NewName macro with the AccessMode parameter set to xlNoChange:

VBA Sub procedure with Workbook.SaveAs and AccessMode

Argument #8: ConflictResolution

ConflictResolution applies when you’re working with shared workbooks. More precisely, this argument allows you to determine how conflicts (while saving the Excel workbook) are resolved.

You can set the ConflictResolution parameter to any of the following 3 values:

  • 1: Stands for xlUserResolution. In this case, Excel displays a dialog box asking the user to resolve the conflict. This is the default setting in case you omit the ConflictResolution argument.
  • 2: Represents xlLocalSessionChanges. If you choose this value, the changes made by the local user are accepted always.
  • 3: The value for xlOtherSessionChanges. This is the opposite from the above: the changes made by the local user are rejected always.

The following screenshot shows the code of the Save_Workbook_NewName macro with the ConflictResolution parameter set to the default xlUserResolution.

Example VBA code with ConflictResolution when saving

Argument #9: AddToMru

MRU stands for Most Recently Used. This makes reference to Excel’s list of most recently used files which, generally, you find on the Backstage View.

List of Most Recently Used workbooks in Excel

The AddToMru argument of the Workbook.Save method allows you to determine whether the saved workbook is added to this most recently used list.

If AddToMru is set to True, the Excel workbook is added to the list. The default value of AddToMru is, however, False.

In the following image, you can see the VBA code behind the sample Save_Workbook_NewName macro with AddToMru set to True:

AddToMru argument in VBA

As mentioned above, I’m not covering in detail the TextCodePage and TextVisualLayout arguments (arguments #10 and #11).

Argument #12: Local

The last argument of the Workbook.SaveAs method is Local. As implied by its name, Local refers to language and localization aspects of the saved workbook.

More precisely, the Local parameter allows you to determine whether the saved workbook is saved against the language of:

  • Excel, as generally determined from the control panel setting; or
  • VBA, which is usually US-English. The basic exception to this rule of VBA’s language being US-English occurs when the VBA project that executes the Workbook.SaveAs method is an internationalized XL5/95 VBA project. My guess is that you’re unlikely to work with such projects often.

To determine how Excel proceeds in connection with this topic, you can set the Local argument to True or False.

  • True: Saves the workbook against Excel’s language.
  • False: Saves the Excel workbook against VBA’s language.

In the following image, you can see the sample Save_Workbook_NewName with the Local parameter set to True:

Example VBA code wih Local argument

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method

The Save and SaveAs methods explained above are the basic methods you’ll need to save Excel workbooks using VBA.

However, both of these methods save and modify the current open Excel workbook. You may encounter some situations where this isn’t the outcome you desire.

In other words, you’ll probably be in situations where you want a macro to simply:

  • Save a copy of the current Excel workbook, but…
  • Don’t actually modify the current file in the memory of the computer.

These type of situations are great for using the Workbook.SaveCopyAs VBA method. This method does precisely this. It takes the workbook and:

  • Saves a copy to a file.
  • Doesn’t modify it in memory.

The syntax of the SaveCopyAs method is, once again, relatively simple:

expression.SaveCopyAs(Filename)

Just as with the other methods explored in this Excel tutorial, “expression” represents a Workbook object. “Filename”, the only parameter of the SaveCopyAs method is the full file path, name and extension of the copy that you’re saving.

Since you’re likely to use this method on the active workbook most of the time, you’ll probably end up using the following syntax often:

ActiveWorkbook.SaveCopyAs(Filename)

Another commonly used alternative is to use the ThisWorkbook property instead of ActiveWorkbook. The main difference between ThisWorkbook and ActiveWorkbook is that:

  • ActiveWorkbook refers to the current active workbook.
  • ThisWorkbook refers to the workbook where the macro is actually stored.

Let’s take a look at an example of a macro that uses the Workbook.SaveCopyAs method to save a copy of the current active workbook:

The screenshot below shows a macro called “Save_Copy_Workbook”.

VBA code to save copy of workbook

This macro has a single (quite long) statement. This goes as follows:

ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice that the structure I use in the Save_Copy_Workbook macro follows the basic syntax of the Workbook.SaveCopyAs method explained above. However, let’s split the statement in 2 parts in order to understand better what’s going on, and what can this particular method do for you:

VBA code saving Excel workbook copy

Part #1: ActiveWorkbook.SaveCopyAs

This is the reference to the SaveCopyAs method. It follows the basic syntax explained above.

“ActiveWorkbook” makes reference to the Application.Workbook property. This property returns a Workbook object representing the current active workbook. This active workbook is the one which is manipulated by the SaveCopyAs method.

In other words, the statement simply tells Excel to proceed as follows:

  • Step #1: Take the current active workbook.
  • Step #2: Save a copy of the current active workbook, without actually modifying it in memory.

Part #2: Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

This part of the statement specifies the only argument of the Workbook.SaveCopyAs method:

The Filename.

This particular file name for the copy is slightly long but, basically, is built by concatenating 5 items. You use the ampersand (&) operator to concatenate the different items.

Item #1: ActiveWorkbook.Path

This makes reference to the Workbook.Path property. The Path property returns the complete path to the relevant workbook.

In the case of the example above, “ActiveWorkbook.Path” is used to get the path to the current active workbook.

Let’s assume, for example, that the current active workbook (called “Book1”) is saved in the D drive. In this case the path is, simply “D:”.

This sample path (D:) isn’t very long or complicated. However, in practice, you’re more likely to work with longer and more complicated paths that you are to work with just the D drive.

Items #2 And #4: “Copy ” and ” “

This are, simply, text strings. The first string specifies that the first word in the file name is “Copy”. The second string adds a space ( ).

Item #3: Format(Now, “yy-mm-dd”)

This particular statement uses 2 VBA built-in functions, as follows:

  • Now returns today’s date and the current time. Alternatively, you can use the Date function, which returns the current date.
  • Format takes the date returned by Now and formats it according to the date format “yy-mm-dd”.

In other words, this part of the argument is responsible for returning the date in which the copy is saved in the format yy-mm-dd.

For example, if the date in which you save the copy of the workbook is November 30 of 2015, this item returns 15-11-30.

Item #5: ActiveWorkbook.Name

This item uses the Workbook.Name property to get the name of the workbook.

For example, if the name of the workbook is “Best Excel Tutorial”, Workbook.Name returns exactly that.

In order to make everything clear regarding the Workbook.SaveCopyAs method, let’s take a look at an example:

How To Save A Copy Of An Excel Workbook Using The Workbook.SaveCopyAs VBA Method: An Example

Let’s assume that the current active workbook is called “Best Excel Tutorial” and is saved in the D drive (D:). This is how the D drive looks like before I run the sample Save_Copy_Workbook macro:

D Drive before macro to save workbook copy

The following screenshot shows how the same drive looks after I run the macro. Notice how, now, there’s a new Excel workbook. This is the copy created by the Save_Copy_Workbook Sub procedure.

D Drive after saving copy of workbook using VBA

Let’s go back to the Filename argument of the SaveCopyAs method used within the Save_Copy_Workbook macro:

Filename:=ActiveWorkbook.Path & “Copy ” & Format(Now, “yy-mm-dd”) & ” ” & ActiveWorkbook.Name

Notice how, each of the 5 items explained above expresses itself in practice once the macro is run:

  • Item #1: The copy is saved in the same folder as the original workbook, as given by the Workbook.Path property.
  • Items #2 and #4: The first word in the actual workbook name is Copy, as determined by the string “Copy”. Also, there is a space between the date (15-11-19) and the original workbook’s name (Best Excel Tutorial) as specified by ” “.
  • Item #3: The date in which the workbook is saved (November 19 of 2015 in the example above) is added to the name in the format yy-mm-dd (15-11-19).
  • Item #5: The name of the original workbook (Best Excel Tutorial) is added at the end of the copy’s name.

The following image shows this:

D Drive showing items of VBA code for workbook name

How To Name A Workbook Using The Application.GetSaveAsFilename Method

I introduced the Application.GetSaveAsFilename method above. This method is used by one of the sample macros (Save_Workbook_NewName) for purposes of opening the Save As dialog box and allow users to easily browse and enter the path, name and file extension of the saved Excel workbook.

The screenshot below shows the VBA code of the Save_Workbook_NewName macro. Notice the presence of the Application.GetSaveAsFilename method.

VBA code to name an Excel workbook

The Application.GetSaveAsFilename method doesn’t actually save a file. However, GetSaveAsFilename is a helpful method to use whenever you have a macro that needs to get a file name from the user in order to, among others, save a workbook.

GetSaveAsFilename is useful when the procedure needs to receive/know the name of the file to save. This gives the user the possibility of specifying the file’s path and filename.

As I explain below, you can use the Application.GetSaveAsFilename method precisely for these purposes.

The GetSaveAsFilename method has a few parameters that allow you to customize some of its characteristics. Let’s take a closer look at the method itself and its arguments, starting with:

The Application.GetSaveAsFilename Method: Purpose

The Application.GetSaveAsFilename method does 2 things:

  1. Displays the Save As dialog box.
  2. Gets the file name entered by the user in the Save As dialog box.

GetSaveAsFilename doesn’t save a workbook by itself. That’s why, for example, the Save_Workbook_NewName macro above includes uses the Workbook.SaveAs method to actually save the Excel workbook.

The Application.GetSaveAsFilename Method: Syntax

The full syntax of the Application.GetSaveAsFilename method is as follows:

expression.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)

“expression” is used to represent the Application object. You’re, therefore, likely to usually use the following basic syntax for this method:

Application.GetSaveAsFilename

This is the syntax used in the version of the Save_Workbook_NewName method shown above.

All of the 5 arguments of the GetSaveAsFilename method are optional. Let’s take a look at them:

The Application.GetSaveAsFilename Method: Arguments

The following table provides a basic description of the 5 parameters of the Application.GetSaveAsFilename method. I explain each of them more thoroughly below.

Position Name Description
1 InitialFilename Specifies a suggested/default file name.
2 FileFilter Determines file filtering criteria.
3 FilterIndex Determines the default file filter.
4 Title Determines the title of the (usually called) Save As dialog box.
5 ButtonText Applies only in the Mac platform.

Determines the text of the (normally called) Save As button.

There are quite a few similarities between the GetSaveAsFilename method and the GetOpenFilename method (which I describe here). In terms of their arguments, the main differences are as follows:

  • GetSaveAsFilename has the InitialFilename argument. GetOpenFilename doesn’t.
  • GetOpenFilename has the MultiSelect argument. GetSaveAsFilename doesn’t.

Both of these differences make sense. For example, MultiSelect allows you to determine whether a user can select multiple file names at the same time. This makes sense in the context of opening files. But not in the context of saving files with the GetSaveAsFilename method.

Let’s take a look at each of the parameters introduced above:

Argument #1: InitialFilename

The InitialFilename of the Application.GetSaveAsFilename method allows you to set a suggested file name. This suggested file name is the one that appears, by default, in the File name box of the Save As dialog.

Excel Save As dialog with suggested file name

The Save As dialog box displayed above is the result of running the following version of the Save_Workbook_NewName macro. Notice that the InitialFilename argument is added and the suggested name is “Best Excel Tutorial”, as displayed in the image above.

VBA code to name workbook showing InitialFileName

Argument #2: FileFilter

The FileFilter argument of the Application.GetSaveAsFilename method allows you to determine the criteria for file filtering within the Save As dialog box.

These file filtering criteria determine what appears in the Save as type drop-down list box of the Save As dialog box. If you omit the FileFilter argument, the default (as shown in the image below) is All Files.

Excel Save as dialog with file filters

This isn’t ideal because it may lead to the saved Excel workbook being of an unrecognizable file type if the user doesn’t enter the file extension when saving the file.

However, my guess is that you’ll be in situations where specifying the file filtering criteria is more convenient or, even, necessary. In order to be able to determine which file filters appear in the Save As dialog box, you’ll need to follow the 4 guidelines below.

Don’t worry if the guidelines don’t seem that clear at first. I show you a practical example of VBA code after making the introduction and basic description.

Guideline #1: Each Filter Consists Of A Pair Of Strings.

Each filter you specify when using the FileFilter argument is made up of 2 strings separated by a comma. This looks, roughly, as follows:

String1,String2

String1 and String2 have different structures and purposes. More precisely:

  • String1: Is a descriptive string. This string determines what actually appears in the Save as type drop-down box of the Save As dialog box.
  • String2: Is the MS-DOS wildcard file-type filter specification. In other words, this string determines how the files are actually filtered depending on their file format.

You don’t need to follow many guidelines regarding the way in which the first string (String1) is specified. However, you do need to follow a more specific syntax when specifying the second string (String2). Let’s take a look at it:

Guideline #2: Syntax To Specify The File-Type Filter.

The second string that you use to specify a file filter is itself composed of 3 elements which are, generally speaking, as follows:

  • Element #1: An asterisk (*), used as a wildcard.
  • Element #2: A dot (.).
  • Element #3: An indication of the file extension used to filter the files. This particular element is usually composed of (where appropriate) an asterisk (*), used as a wildcard, and/or (if appropriate), some text.

The most basic filter is all files, which in practice means that there’s no filter. To specify a file-type filter than includes all files using the syntax above, you’d type asterisk dot asterisk (*.*).

Other examples of file-type filter specifications following this syntax are the following:

  • *.txt for text files.
  • *.xla for add-ins.
  • *.xlsx for Excel workbooks.
  • *.xlsm for Macro-Enable Excel workbooks.
  • *.xls for Excel 97 to Excel 2003 workbooks.
  • *.csv for CSV files.

Knowing these first 2 guidelines is enough for you to start using the FileFilter argument. However, they only explain how to specify a single filter according to a single file type.

However, when working with FileFilter, you can actually specify:

  • Several different filters; as well as
  • Several different file types for each filter.

The next 2 guidelines show how you can do each of these:

Guideline #3: Syntax To Specify Several Filters.

You can create more than a single filter with the FileFilter argument. In order to so, use commas (,) to separate the filters. In other words, separate each of the pair of strings that constitute a filter from the other pair of strings by using commas (,).

This looks, roughly, as follows:

String1Filter1,String2Filter1,String1Filter2,String2Filter2

Guideline #4: Syntax To Specify Several File Types In A Single Filter.

If you need to filter according to several different data types, you can use several filters by using the syntax explained above.

Alternatively, you can specify several data types for a particular single filter. To do this, separate the MS-DOS wildcard expressions that you use with semicolons (;). This looks roughly as follows:

String1,String2.1;String2.2

Those are the 4 basic guidelines you need to bear in mind to start using the FileFilter argument. Let’s go back to the Save_Workbook_NewName macro and create some file filters:

The following screenshot shows (again) the VBA code behind Save_Workbook_NewName. Notice that the FileFilter argument has been inserted and its syntax follows all of the guidelines I explained above.

VBA code to name saved workbook with file filters

To make this clearer, let’s break the argument value into its different parts and highlight how it complies with all of the guidelines described above.

The complete argument is as follows:

“Excel Workbook,*.xlsx,Excel Macro-Enabled Workbook,*xlsm,Excel Templates,*.xltx;*.xltm”

Notice the following things:

  1. There are 3 filters. Each of the filters is separated from the other by commas (,).

    VBA code to name saved workbook with 3 filters

  2. Each filter is composed of 2 parts: a descriptive string and the relevant MS-DOS wildcard file-type filter specification. These 2 parts are separated by commas (,).

    VBA code to name saved workbook with parts of filters

  3. MS-DOS wildcard file-type filter specifications follow the syntax described above: (i) asterisk (*); (ii) dot (.); and (iii) file extension specification, without wildcard asterisks in this case.

    VBA code with file type filters

  4. The last filter uses 2 different file types. These file types are separated by a semicolon (;).

    VBA code to name saved workbook with 2 file-type filters

The following image shows how all of the above looks like in practice. Notice how, now, there are 3 different options within the Save as Type box of the Save As dialog box. These 3 filters are those created by the FileFilter argument of the Application.GetSaveAsFilename method.

Excel Save As dialog with filters created in VBA

Argument #3: FilterIndex

Notice how, in the image above, the default file filtering criteria is “Excel Workbook”. This is the first filter that was specified with the FileFilter argument.

You can, however, change the default file filtering criteria by using the FilterIndex argument. You do this by specifying the index number of the criteria you want to set as default.

As a consequence of the above, the FilterIndex argument can take any value between 1 (the first filter) and the number of filters you’ve specified with the FileFilter argument (3 in the example above).

If you set the FilterIndex value to a number higher than the amount of available filters (4 or higher in the case of the Save_Workbook_NewName macro), the first filter is used. In other words, the practical result of specifying an index number that is too high, is the same as that of omitting the FilterIndex parameter.

The following screenshot shows the code of the Save_Workbook_NewName macro with the FilterIndex parameter set to 2.

VBA code to name saved workbook with filter index

In the case of this macro, a FilterIndex value of 2 means that “Excel Macro-Enabled Workbook” is the new default filter.

Save As dialog with filter index from VBA

Argument #4: Title

The Title argument of the Application.GetSaveAsFilename method allows you to modify the title of the (usually called) Save As dialog box. If you omit the argument, the default title (Save As) is maintained.

The following image shows how this argument can be used to change the title of the Save As dialog box when executing the Save_Workbook_NewName macro. In this case, the Title argument is set to “VBA Save Excel Workbook”.

VBA code to name saved workbook and Title argument

When this macro is executed, the (previously called) Save As dialog looks as follows. Notice that the title has indeed changed to “VBA Save Excel Workbook”.

Excel Save As dialog with title from VBA

Argument #5: ButtonText

The ButtonText parameter is only applicable in the Mac platform. If you use this argument in Windows, it’s simply ignored.

For those cases where it is applicable, the ButtonText argument allows you to set the text that appears in the (usually known as) Save button.

Excel Save As dialog with Save button

Conclusion

Knowing how to save Excel workbooks using VBA is essential.

If you’ve read this Excel tutorial, you now know the basics of how to save workbooks using VBA. In fact, you’ve seen 3 different ways to achieve this:

  • Using the Workbook.Save method.
  • Using the Workbook.SaveAs method.
  • Using the Workbook.SaveCopyAs method.

Each of these cases is explained with the help of a real example of VBA code.

Additionally, in the last section of this blog post, I explained the Application.GetSaveAsFilename method. Even though this method doesn’t actually save a file by itself, it allows you to display the Save As dialog so that the users of your macro can easily specify the path and file name of the workbook they’re saving.

Since updating to Office 2016, any time I try to us the Save As dialog with Excel, it adds a prefix of «Copy of»

I’d like to eliminate this is possible.

Most of the file locations are networked, but I checked and it still occurs on local files, seemingly ruling out a trust center issue.

There was a thread about this for an earlier version of Office that advised using a macro in the PERSONAL file in XLSTART, but that does not seem to work for me in 2016.

This was the macro posted in an earlier thread:

Private WithEvents App As Application

Private Sub App_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If InStr(1, Wb.Name, «Copy of «) = 1 Then
        Application.EnableEvents = False
        Cancel = True
        Wb.SaveAs Replace(Wb.FullName, «Copy of «, «»)
        Application.EnableEvents = True
    End If
End Sub

Private Sub Workbook_Open()
    Set App = Application
End Sub

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Workbook.SaveCopyAs method (Excel)

vbaxl10.chm199146

vbaxl10.chm199146

excel

Excel.Workbook.SaveCopyAs

84f58488-6a2b-7fef-1472-e1b9771a60b0

05/29/2019

medium

Workbook.SaveCopyAs method (Excel)

Saves a copy of the workbook to a file but doesn’t modify the open workbook in memory.

Syntax

expression.SaveCopyAs (FileName)

expression A variable that represents a Workbook object.

Parameters

Name Required/Optional Data type Description
FileName Required Variant Specifies the file name for the copy.

Example

This example saves a copy of the active workbook.

ActiveWorkbook.SaveCopyAs "C:TEMPXXXX.XLS"

[!includeSupport and feedback]

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

По работе на своём компе создаю/модернизирую/заполняю разные таблицы.  
По окончании какого-нибудь этапа КОПИЮ таблицы надо выкладывать на общий диск с паролем на изменение (ну, просто для страховки одних пользователей от действий других…).  
Конечно, можно воспользоваться стандартными средствами:    
— открыть папку назначения, скопировать (drag & drop’ ом) туда файл, открыть его и поставить пароль на открытие… Но уж больно это не удобно, т.к. надо после копирования закрыть свой рабочий файл (имена-то совпадают!!!).  
или  
— сказать Ёкселю «Сохранить как…» и указать с каким именем, куда и с какими паролями сохранить файл. А потом закрыть тот сетевой, видный для всех, файл и открыть свой рабочий. Это тоже не слишком удобно, т.к. требует много «мышкодвижений».  
А недавно поставил себе прогу «PDF-Exchange» и увидел там возможность «Сохранить копию как …».    
Оказалось очень удобно, т.к. при этом текущий открытый файл не закрывается, а просто его копия сохраняется в указанном месте с указанными свойствами (всё это задаётся в стандартных виндовых окнах).  
Вот и подумал, а вдруг гуру форума посоветуют как можно сделать макрос, осуществляющий аналогичную вункцию в Ёкселе?  
Очевидно, что макрос (ну, например, Save_Copy_As) должен лежать в личной книге макросов (Personal.xls)…  
А вот как «Сохранить как…», не закрывая текущего файла?

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Сразу оговариваю:  
макросы типа  
Sub Save_File_As()  
  ActiveWorkbook.SaveAs _  
        Filename:=»трам-пам-пам.xls», _  
        FileFormat:=xlNormal, _  
        Password:=»», _  
        WriteResPassword:=»», _  
        ReadOnlyRecommended:=True, _  
        CreateBackup:=False  
End Sub  
не подходят, т.к. это как раз и есть описанный мною выше второй случай…

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

tolikt

Пользователь

Сообщений: 367
Регистрация: 01.01.1970

tolikt

.SaveCopyAs чем не устраивает?

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

ThisWorkbook.Password = «1»  
ThisWorkbook.SaveCopyAs ‘полный путь, включая расширение файла. ДОЛЖЕН БЫТЬ В ДРУГОЙ ПАПКЕ, дабы не было конфликта при совпадении имен.  
ThisWorkbook.Password = «»

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Метод SaveCopyAs требует непосредственного указания пути и имени сохранения, а хотелось бы по вызову макроса выйти на стандартное окно выбора пути и имени сохранения …

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Да и к тому же метод SaveCopyAs не предполагает задания опций сохранения (пароль, предложение открыть только для чтения и т.п.)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

tolikt

Пользователь

Сообщений: 367
Регистрация: 01.01.1970

tolikt

Наверное, я что-то не понял…  
Т.к. думал, что пользователь класса Alex_ST уж сумеет как-то в макросе подогнать под себя SaveCopyAs через InputBox или ещё как-то…  
В чём хитрость-то?

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=Alex_ST}{date=01.06.2010 01:56}{thema=}{post}Метод SaveCopyAs требует непосредственного указания пути и имени сохранения, а хотелось бы по вызову макроса выйти на стандартное окно выбора пути и имени сохранения …{/post}{/quote}А кто мешает перед этим вывести диалог?  

     Dim sFileName As String, sExpansion As String  
BEGIN_:  
   sFileName = ThisWorkbook.Name  
   sExpansion = Right(sFileName, Len(sFileName) — InStrRev(sFileName, «.») + 1)  
   sFileName = Application.GetSaveAsFilename  
   If sFileName = «False» Then Exit Sub  

     sFileName = sFileName & IIf(Right(sFileName, Len(sExpansion)) <> sExpansion, sExpansion, «»)  
   If sFileName = ThisWorkbook.FullName Then  
   MsgBox «Нельзя сохранить файл под имененм открытого файла!», vbCritical + vbYesNo, «Ошибка»  
   GoTo BEGIN_  
   End If  
   ThisWorkbook.Password = «1»  
   ThisWorkbook.SaveCopyAs sFileName  
   ThisWorkbook.Password = «»

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=Alex_ST}{date=01.06.2010 01:59}{thema=}{post}Да и к тому же метод SaveCopyAs не предполагает задания опций сохранения (пароль, предложение открыть только для чтения и т.п.){/post}{/quote}Алекс, Вы хоть посмотрели, что я предложил? Вы сначала задаете книге пароль, затем сохраняете, затем убираете пароль.    

  Тоже самое можно сделать и с другими атрибутами(только чтение через GetAttr например).

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Я, конечно, естественно, смогу сделать InputBox для задания пути для SaveCopyAs, но, ИМХО, InputBox и окно задания пути сохранения файла — это «две большие разницы» …

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=Alex_ST}{date=01.06.2010 02:08}{thema=}{post}Я, конечно, естественно, смогу сделать InputBox для задания пути для SaveCopyAs, но, ИМХО, InputBox и окно задания пути сохранения файла — это «две большие разницы» …{/post}{/quote}Я Вам уже целый пример накатал — чем он не устраивает? Выбор через диалог, сохраняет куда укажешь и с паролем, да еще и предупреждает, если такой файл есть.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

The_Prist, вы с такой скоростью создаёте свои ответы пока я ввожу свои, что я их просто не успеваю читать…  
Ща буду разбираться… Беру тайм-аут на осмысливание.    
Скорее всего до завтра, т.к.у нас на работе сегодня отмечается «День Корпорации» (ввиду кризиса — на рабочих местах, а не на природе), поэтому, прошу пардону, с ответами немного торможу, хотя пока ещё вполне адекватен, но что будет дальше …

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

The_Prist,спасибо!  
Всё отлично работает. Завтра «дополирую» диалогами для задания пассворда …  
А как бы при сохранении копии задавать «Рекомендовать открытие только для чтения?»

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

К стати, не подскажите «на вскидку» как к имени файла при сохранении добавить перед расширением суффикс — дату и время сохранения? (ну, например, Имя_моего_рабочего_файла(01-06-2010 14-30).xls

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

SetAttr ThisWorkbook.FullName, vbReadOnly

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

К сожалению, свойство vbReadOnly при SaveCopyAs задать не удаётся…  
А нельзя ли его задать для уже созданного файла-копии?

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Алекс, ну чтоже ВЫ так? Я ж еще в начале писал — «Вы сначала задаете книге пароль, затем сохраняете, затем убираете пароль.  

  Тоже самое можно сделать и с другими атрибутами(только чтение через GetAttr например).»  

  Т.е. сначала Вы сохраняемой книги присваиваете все эти атрибуты, затем сохраняете, потом убираете.  

  Dim sFileName As String, sExpansion As String  
BEGIN_:  
sFileName = ThisWorkbook.Name  
sExpansion = Right(sFileName, Len(sFileName) — InStrRev(sFileName, «.») + 1)  
sFileName = Application.GetSaveAsFilename  
If sFileName = «False» Then Exit Sub  

  sFileName = sFileName & IIf(Right(sFileName, Len(sExpansion)) <> sExpansion, sExpansion, «»)  
If sFileName = ThisWorkbook.FullName Then  
MsgBox «Нельзя сохранить файл под имененм открытого файла!», vbCritical + vbYesNo, «Ошибка»  
GoTo BEGIN_  
End If  
ThisWorkbook.Password = «1»:SetAttr ThisWorkbook.FullName, vbReadOnly  
ThisWorkbook.SaveCopyAs sFileName  
ThisWorkbook.Password = «»:SetAttr ThisWorkbook.FullName, vbNormal

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Hugo

Пользователь

Сообщений: 23249
Регистрация: 22.12.2012

Alex_ST, про дату в названии есть в приёмах: http://www.planetaexcel.ru/tip.php?aid=72

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Спасибо. Разобрался.  
Только чтобы всё правильно работало нужно не атрибуты файла через  
SetAttr ActiveWorkbook.FullName, vbReadOnly устанавливать, т.к. это ничего не даёт , а    
ActiveWorkbook.Password = «ххх» задаёт пароль НА ОТКРЫТИЕ  

  Надо вот так:    
With ActiveWorkbook  
     .WritePassword = «1»  
     .ReadOnlyRecommended = True  
     .SaveCopyAs sFileName  
     .WritePassword = «»  
     .ReadOnlyRecommended = False  
End With  

   Если кому-нибудь интересно, то «причёсанный» вариант — в файле.

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

#20

08.02.2012 12:01:30

Приходится у себя на компе вести несколько учётных файлов, а их копии регулярно скидывать в разные директории на общем ресурсе.  
Достало постоянно выбирать куда и какой файл сохранять…  
Переделал макрос Save_Copy_As так, что путь последнего сохранения копии запоминается в самом файле в коллекции Names  
Два дня поюзал — понравилось!  

Код
Sub Save_Copy_As()   
'---------------------------------------------------------------------------------------   
' Procedure    : Save_Copy_As   
' Author       : Alex_ST   
' Topic_HEADER : Как макросом сохранить копию текущего файла?   
' Topic_URL    : http://www.planetaexcel.ru/forum.php?thread_id=16506   
' DateTime     : 08.02.12, 12:00   
' Purpose      : Сохранение копии активного файла   
' Notes        : Путь сохранения копий хранится в коллекции .Names книги (в именованном диапазоне)   
'---------------------------------------------------------------------------------------   
   Const sPath_in_Names = "Path4SaveCopyAs"   ' имя элемента коллекции .Names, в котором должен храниться путь для сохранения копий файла   
   Dim sSuff$: sSuff = " [" & Format(Now, "yyyy/mm/dd hh-mm'ss''") & "]"    ' суффикс к имени файла копии - дата и время сохренения копии файла   
   Dim FileName, sExp$, sDirPath$, sFullFilePath$, sNewPath$   
   Dim bReadOnlyRecommended As Boolean   
   With ActiveWorkbook   
      FileName = .Name   ' например, "Книга1.xls"   
      sExp = Right(FileName, Len(FileName) - InStrRev(FileName, ".") + 1)   ' расширение файла вместе с точкой (например, ".xls")   
      FileName = Left(FileName, Len(FileName) - Len(sExp)) & sSuff & sExp   ' например, "Книга1 [2012.02.06 15-24'39''].xls"   
      On Error Resume Next   
      sDirPath = .Names(sPath_in_Names).Value   ' считать из коллекции .Names значение, ранее сохраненное под именем sPath_in_Names   
      If Err Then .Names.Add sPath_in_Names, .Path & "": sDirPath = .Names(sPath_in_Names).Value   ' если считать не удалось, значит путь ранее не задавался и он для первого раза задаётся равным ActiveWorkbook.Path   
      sDirPath = Mid(sDirPath, 3, Len(sDirPath) - 3)   ' убрать из считанного значения в начале "= и в конце "   
      sDirPath = sDirPath & IIf(Right(sDirPath, 1) = "", "", "")  ' на всякий случай (если имя было задано в ручную и при этом не верно - без слэша)   
      .Names(sPath_in_Names).Value = sDirPath   ' запомнить путь сохранения копий в коллекции .Names под именем sPath_in_Names   
      sFullFilePath = sDirPath & FileName   ' полный путь сохранения вместе с полным именем копии   
REPEAT_:   
      FileName = Application.GetSaveAsFilename(InitialFileName:=sFullFilePath, _   
                                               FileFilter:="Excel Files (*" & sExp & "), *" & sExp & ", All Files (*.*),*.*", _   
                                               Title:="Сохранение копии файла")   'задать путь сохранения и имя копии файла в окне выбора   
      If VarType(FileName) = vbBoolean Then Exit Sub   ' если нажали "Отмена", то FileName = False, если "Сохранить" - полный путь к файлу вместе с его именем   
      If FileName = .FullName Then MsgBox "Здесь нельзя сохранить файл под таким именем!", 16, "Ошибка": GoTo REPEAT_   
      sDirPath = Left(FileName, InStrRev(FileName, ""))   ' путь к папке сохранения копий без имени файла   
      .Names(sPath_in_Names).Value = sDirPath   ' запомнить выбранный в диалоге путь в коллекции .Names под именем sPath_in_Names   
      bReadOnlyRecommended = .ReadOnlyRecommended   ' запомнить параметры исходного файла   
      .ReadOnlyRecommended = --(MsgBox("Рекомендовать открывать файл только для чтения?", 36) - 7)   ' MsgBox Argument 4==vbYesNo 32==vbQuestion, MsgBox Return Values: vbYes=6, vbNo=7   
      .SaveCopyAs FileName   
      .ReadOnlyRecommended = bReadOnlyRecommended   ' восстановить параметры исходного файла   
   End With   
End Sub

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#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