Vba excel окно сохранения

0 / 0 / 0

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

Сообщений: 29

1

Открыть диалог сохранения файла

17.03.2012, 21:33. Показов 30817. Ответов 9


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

Здравствуйте, господа программисты!
Скажите, пожалуйста, как средствами VBA можно открыть меню на сохранение программно созданной книги документа (изображение «сохранение).jpg » в прикрепленном файле)
У меня сделано вот так:
1) В исходной книге копируются 2 необходимых листа.
2) Выбранные листы помещаются в новую книгу, она сохраняется по указанному пути под фиксированным именем.
Файл прикрепил.
_____________________
Если у вас есть идеи и предложения, подскажите, пожалуйста, как можно программно вывести меню Eхcel (показанное в рисунке) на сохранение, в котором пользователь мог бы изменить пусть к папке, куда он хочет сохранить созданные документы и задать желаемое имя.

Миниатюры

Открыть диалог сохранения файла
 



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

17.03.2012, 22:37

2

Лучший ответ Сообщение было отмечено как решение

Решение

Простейший случай

Visual Basic
1
Application.Dialogs(xlDialogSaveAs).Show

С предлагаемым именем и типом файла

Visual Basic
1
Application.Dialogs(xlDialogSaveAs).Show "предлагаемое_имя", xlExcel9795

С анализом действия пользователя

Visual Basic
1
2
If Not Application.Dialogs(xlDialogSaveAs).Show("предлагаемое_имя", xlExcel9795) Then _
    MsgBox "Книга не сохранена!", vbExclamation



5



0 / 0 / 0

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

Сообщений: 29

17.03.2012, 23:24

 [ТС]

3

Казанский, СПАСИБО Большое, первый из предложенных Вами вариантов, — то,что нужно ! а я то думал, там сочинение будет
а Вы не знаете,как закрыть/скрыть от пользователя созданную книгу или хотя бы её не высвечивать ? Чтобы только окно сохранения было видно и основная книга (откуда все копируется) ?



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

18.03.2012, 01:10

4

В простейшем случае — перед командой копирования листов поставить

Visual Basic
1
Application.ScreenUpdating = False



0



strike383

616 / 0 / 1

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

Сообщений: 93

17.01.2014, 16:29

5

Visual Basic
1
2
If Not Application.Dialogs(xlDialogSaveAs).Show(Date & ".xlsx") Then _
        MsgBox "Книга не сохранена!", vbExclamation

А подскажите пожалуйста, как сюда добавить путь сохранения



0



0 / 0 / 0

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

Сообщений: 4

17.04.2018, 12:41

6

Цитата
Сообщение от Казанский
Посмотреть сообщение

«предлагаемое_имя», xlExcel9795

А как указать расширение сохраняемого файла PDF?



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

17.04.2018, 14:43

7

seryga123, с помощью прямого вызова диалога — по-видимому, никак: сохранение в PDF производится не с помощью метода SaveAs, которому соответствует диалог Application.Dialogs(xlDialogSaveAs) , а с помощью метода ExportAsFixedFormat, соответствующего диалога которому я не нашел: https://msdn.microsoft.com/ru-… ment-lists
Поэтому сначала вызываем диалог выбора файла, потом сохраняем:

Visual Basic
1
2
3
4
5
6
7
Dim x
  x = Application.GetSaveAsFilename("c:tempmyfile", "PDF files (*.pdf), *.pdf") 'путь и предлагаемое имя файла
  If x <> False Then
    ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=x _
      , Quality:=xlQualityStandard, IncludeDocProperties:=True _
      , IgnorePrintAreas:=False, OpenAfterPublish:=True
  End If



0



0 / 0 / 0

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

Сообщений: 4

17.05.2018, 09:46

8

Казанский, а не подскажите как в имя добавить переменную?
Я имею ввиду что-то вроде:

Код

 Application.Dialogs(xlDialogSaveAs).Show "name1" & "name2" & a, 51



0



15136 / 6410 / 1730

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

Сообщений: 9,999

17.05.2018, 10:15

9

seryga123, да, так. Вы попробовали?



0



0 / 0 / 0

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

Сообщений: 4

17.05.2018, 10:17

10

Да, конечно пробывал, но не работает!



0



Содержание

  1. Метод Application.GetSaveAsFilename (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Примечания
  6. Пример
  7. Поддержка и обратная связь
  8. Свойство Application.FileDialog (Excel)
  9. Синтаксис
  10. Параметры
  11. Примечания
  12. Пример
  13. Поддержка и обратная связь
  14. Свойство Application.DisplayAlerts (Excel)
  15. Синтаксис
  16. Примечания
  17. Пример
  18. Поддержка и обратная связь
  19. Application.GetSaveAsFilename method (Excel)
  20. Syntax
  21. Parameters
  22. Return value
  23. Remarks
  24. Example
  25. Support and feedback
  26. Метод Workbook.SaveAs (Excel)
  27. Синтаксис
  28. Параметры
  29. Замечания
  30. Пример
  31. Поддержка и обратная связь

Метод Application.GetSaveAsFilename (Excel)

Отображает стандартное диалоговое окно Сохранить как и получает у пользователя имя файла без фактического сохранения файлов.

Синтаксис

выражение. GetSaveAsFilename (InitialFilename, FileFilter, FilterIndex, Title, ButtonText)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
InitialFilename Необязательный Variant Указывает предлагаемое имя файла. Если этот аргумент пропущен, Microsoft Excel использует имя активной книги.
FileFilter Необязательный Variant Строка, указывающая условия фильтрации файлов. Максимальная длина составляет 255 символов, в противном случае метод возвращает ошибку 2015.
FilterIndex Необязательный Variant Указывает номер индекса условий фильтрации файлов по умолчанию от 1 до числа фильтров, указанных в FileFilter. Если этот аргумент пропущен или его значение превышает число имеющихся фильтров, используется первый фильтр файлов.
Title Необязательный Variant Указывает заголовок диалогового окна. Если этот аргумент пропущен, используется заголовок по умолчанию.
ButtonText Необязательный Variant Только для Macintosh.

Возвращаемое значение

Примечания

Эта строка, передаваемая в аргументе FileFilter, состоит из пар строк фильтра файлов, после которых идет спецификация фильтра файлов MS-DOS с подстановочным знаком, где каждая часть и каждая пара разделяются запятыми. Каждая отдельная пара указана в раскрывающемся списке Тип файлов. Например, следующая строка указывает два фильтра файлов — text и addin:

«Text Files (*.txt), *.txt, Add-In Files (*.xla), *.xla»

Чтобы использовать разные выражения с подстановочными знаками MS-DOS для одного типа фильтра файлов, разделяйте выражения с подстановочными знаками точкой с запятой. Пример: «Visual Basic Files (*.bas; *.txt), *.bas;*.txt» .

Этот метод возвращает выбранное имя файла или имя, введенное пользователем. Возвращаемое имя может содержать путь. Возвращается значение False, если пользователь отменяет использование диалогового окна.

Этот метод может менять текущий диск или папку.

При использовании InitialFilename с расширением и применении фильтра это расширение должно соответствовать расширению фильтра, в противном случае действующее значение InitialFilename, отображенное в диалоговом окне, является пустой строкой.

Пример

В этом примере отображается диалоговое окно Сохранить как с фильтром, настроенным на текстовые файлы. Если пользователь выбирает имя файла, в примере отображается это имя файла в окне сообщения.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Свойство Application.FileDialog (Excel)

Возвращает объект FileDialog, представляющий экземпляр диалогового окна файла.

Синтаксис

выражение.FileDialog (fileDialogType)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
fileDialogType Обязательный MsoFileDialogType Тип диалогового окна работы с файлами.

Примечания

Значение MsoFileDialogType может быть одной из этих констант:

  • msoFileDialogFilePicker. Позволяет пользователю выбрать файл.
  • msoFileDialogFolderPicker. Позволяет пользователю выбрать папку.
  • msoFileDialogOpen. Позволяет пользователю открыть файл.
  • msoFileDialogSaveAs. Позволяет пользователю сохранить файл.

Пример

В этом примере приложение Microsoft Excel открывает диалоговое окно с файлом, позволяющее пользователю выбрать один или несколько файлов. После выбора этих файлов Excel отображает путь к каждому файлу в отдельном сообщении.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Свойство Application.DisplayAlerts (Excel)

Имеет значение True, если Microsoft Excel отображает определенные оповещения и сообщения во время выполнения макроса. Для чтения и записи, Boolean.

Синтаксис

выражение.DisplayAlerts

выражение: переменная, представляющая объект Application.

Примечания

Значение по умолчанию — True. Установите для этого свойства значение False, чтобы отключить вывод сообщений и оповещений во время выполнения макроса; когда сообщение требует ответа, Microsoft Excel выбирает ответ по умолчанию.

Если для этого свойства задано значение False, при завершении кода для этого свойства в Excel устанавливается значение True, если не выполняется код для нескольких процессов.

При использовании метода SaveAs для книг при перезаписи существующего файла в диалоговом окне подтверждения сохранения используется значение по умолчанию Нет, но если для свойства DisplayAlerts задано значение False, в Excel выбирается ответ Да. Ответ Да перезаписывает существующий файл.

При использовании метода SaveAs для сохранения книги, содержащей проект Visual Basic для приложений (VBA) в формате файлов Excel 5.0/95, в диалоговом окне Microsoft Excel по умолчанию используется значение Да, но если для свойства DisplayAlerts задано значение False, в Excel выбирается ответ Отмена. Книгу, содержащую проект VBA, невозможно сохранить в формате файлов Excel 5.0/95.

Пример

В этом примере показано, как закрыть книгу Book1.xls и не предлагать пользователю сохранить изменения. Изменения файла Book1.xls не сохраняются.

В этом примере показано, как отключить сообщение, которое появляется при инициации канала DDE для приложения, которое не запущено.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Application.GetSaveAsFilename method (Excel)

Displays the standard Save As dialog box and gets a file name from the user without actually saving any files.

Syntax

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

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
InitialFilename Optional Variant Specifies the suggested file name. If this argument is omitted, Microsoft Excel uses the active workbook’s name.
FileFilter Optional Variant A string specifying file filtering criteria. Max length is 255 characters, otherwise the method returns Error 2015.
FilterIndex Optional Variant Specifies the index number of the default file filtering criteria, from 1 to the number of filters specified in FileFilter. If this argument is omitted or greater than the number of filters present, the first file filter is used.
Title Optional Variant Specifies the title of the dialog box. If this argument is omitted, the default title is used.
ButtonText Optional Variant Macintosh only.

Return value

This string passed in the FileFilter argument consists of pairs of file filter strings followed by the MS-DOS wildcard file filter specification, with each part and each pair separated by commas. Each separate pair is listed in the Files of type drop-down list box. For example, the following string specifies two file filters—text and addin:

«Text Files (*.txt), *.txt, Add-In Files (*.xla), *.xla»

To use multiple MS-DOS wildcard expressions for a single file filter type, separate the wildcard expressions with semicolons; for example, «Visual Basic Files (*.bas; *.txt), *.bas;*.txt» .

This method returns the selected file name or the name entered by the user. The returned name may include a path specification. Returns False if the user cancels the dialog box.

This method may change the current drive or folder.

When InitialFilename is used with an extension and a filter is applied, this extension must match the filter extension, otherwise the effective InitialFilename displayed in the dialog box will be an empty string.

Example

This example displays the Save As dialog box, with the file filter set to text files. If the user chooses a file name, the example displays that file name in a message box.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Workbook.SaveAs (Excel)

Сохраняет изменения в книге в другом файле.

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Синтаксис

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

Выражение Переменная, представляющая объект Workbook .

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Необязательный Variant Строка, указывающая имя сохраняемого файла. Можно включить полный путь; В противном случае Microsoft Excel сохранит файл в текущей папке.
FileFormat Необязательный Variant Формат файла, используемый при сохранении файла. Список допустимых вариантов см. в перечислении XlFileFormat . Для существующего файла форматом по умолчанию является последний указанный формат файла; Для нового файла по умолчанию используется формат используемой версии Excel.
Password Необязательный Variant Строка с учетом регистра (не более 15 символов), указывающая пароль защиты, который будет присвоен файлу.
WriteResPassword Необязательный Variant Строка, указывающая пароль резервирования записи для этого файла. Если файл сохраняется с паролем и пароль не предоставляется при открытии файла, он открывается только для чтения.
ReadOnlyRecommended Необязательный Variant Значение true для отображения сообщения при открытии файла, в котором рекомендуется открыть файл только для чтения.
CreateBackup Необязательный Variant Значение True для создания файла резервной копии.
AccessMode Необязательный XlSaveAsAccessMode Режим доступа к книге.
ConflictResolution Необязательный XlSaveConflictResolution Значение XlSaveConflictResolution , определяющее, как метод разрешает конфликт при сохранении книги. Если задано значение xlUserResolution, отображается диалоговое окно разрешения конфликтов.

Если задано значение xlLocalSessionChanges, изменения локального пользователя принимаются автоматически.

Если задано значение xlOtherSessionChanges, изменения из других сеансов автоматически принимаются вместо изменений локального пользователя.

Если этот аргумент опущен, отобразится диалоговое окно разрешения конфликтов. AddToMru Необязательный Variant Значение true , чтобы добавить эту книгу в список недавно использовавшихся файлов. Значение по умолчанию — False. TextCodepage Необязательный Variant Игнорируется для всех языков в Microsoft Excel.

ПРИМЕЧАНИЕ. Когда Excel сохраняет книгу в одном из форматов CSV или текста, указанных с помощью параметра FileFormat , он использует кодовую страницу, соответствующую языку системного языкового стандарта, используемого на текущем компьютере. Этот системный параметр доступен на вкладке панель управления>Регион и расположение языка> в разделе Текущее расположение. TextVisualLayout Необязательный Variant Игнорируется для всех языков в Microsoft Excel.

ПРИМЕЧАНИЕ. Когда Excel сохраняет книгу в одном из форматов CSV или текста, указанных с помощью параметра FileFormat , эти форматы сохраняются в логическом макете. Если текст слева направо (LTR) внедрен в текст справа налево (RTL) в файле или наоборот, логическая разметка сохраняет содержимое файла в правильном порядке чтения для всех языков в файле без учета направления. Когда приложение открывает файл, каждый запуск символов LTR или RTL отображается в правильном направлении в соответствии с диапазонами значений символов на кодовой странице (если только приложение, предназначенное для отображения точного макета памяти файла, например отладчик или редактор, не используется для открытия файла). Local Необязательный Variant Значение True сохраняет файлы на языке Microsoft Excel (включая параметры панели управления). Значение False (по умолчанию) сохраняет файлы на языке Visual Basic для приложений (VBA) (как правило, на английском языке США, если проект VBA, из которого выполняется Workbooks.Open, не является старым проектом VBA с интернационализацией XL5/95).

Замечания

Используйте надежные пароли, содержащие строчные и прописные буквы, цифры и знаки. В ненадежных паролях не используются сочетания таких элементов.

  • Надежный пароль: Y6dh!et5
  • Ненадежный пароль: House27

Используйте надежный пароль, который можно запомнить, чтобы не пришлось его записывать.

Пример

В этом примере создается новая книга, запрашивается имя файла, а затем она сохраняется.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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

Application.GetSaveAsFilename method (Excel)

vbaxl10.chm133143

vbaxl10.chm133143

excel

Excel.Application.GetSaveAsFilename

2ad52070-22d7-a755-9267-daaa5edbbb0d

04/04/2019

high

Application.GetSaveAsFilename method (Excel)

Displays the standard Save As dialog box and gets a file name from the user without actually saving any files.

Syntax

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

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
InitialFilename Optional Variant Specifies the suggested file name. If this argument is omitted, Microsoft Excel uses the active workbook’s name.
FileFilter Optional Variant A string specifying file filtering criteria. Max length is 255 characters, otherwise the method returns Error 2015.
FilterIndex Optional Variant Specifies the index number of the default file filtering criteria, from 1 to the number of filters specified in FileFilter. If this argument is omitted or greater than the number of filters present, the first file filter is used.
Title Optional Variant Specifies the title of the dialog box. If this argument is omitted, the default title is used.
ButtonText Optional Variant Macintosh only.

Return value

Variant

Remarks

This string passed in the FileFilter argument consists of pairs of file filter strings followed by the MS-DOS wildcard file filter specification, with each part and each pair separated by commas. Each separate pair is listed in the Files of type drop-down list box. For example, the following string specifies two file filters—text and addin:

"Text Files (*.txt), *.txt, Add-In Files (*.xla), *.xla"

To use multiple MS-DOS wildcard expressions for a single file filter type, separate the wildcard expressions with semicolons; for example, "Visual Basic Files (*.bas; *.txt), *.bas;*.txt".

This method returns the selected file name or the name entered by the user. The returned name may include a path specification. Returns False if the user cancels the dialog box.

This method may change the current drive or folder.

When InitialFilename is used with an extension and a filter is applied, this extension must match the filter extension, otherwise the effective InitialFilename displayed in the dialog box will be an empty string.

Example

This example displays the Save As dialog box, with the file filter set to text files. If the user chooses a file name, the example displays that file name in a message box.

fileSaveName = Application.GetSaveAsFilename( _ 
 fileFilter:="Text Files (*.txt), *.txt") 
If fileSaveName <> False Then 
 MsgBox "Save as " & fileSaveName 
End If

[!includeSupport and feedback]

If you are coding in VBScript, Excel and you need to extract the filename that a user uses when saving a file, the GetSaveAsFilename() method can be useful for you.

This can be quite helpful when you want the end-user to select a file from their required file location using a GUI like a Save as dialog box. 

In this tutorial, we will demonstrate with a few coding examples how to use the Application.Getsaveasfilename method in Excel

What does the GetSaveAsFilename Method do in Excel?

The GetSaveAsFilename() method in Excel does two things:

  • Displays a customized Save As dialog box
  • Extracts the filename the user specifies in the ‘Filename’ input field of the dialog box.

It does not, however, actually save the file even when the user presses the Save button. You will need to use a separate function if you want the file to be saved.

Now what do we mean by a ‘customized Save As dialog box’ ?

This means you can specify what title you want in the Save As dialog box, as well as specify an initial filename (that the user can change according to his/ her requirement).

You can also specify filters for the types of files the user will be allowed to save as. For example, you might want to give the user options to save as only text (.txt) and Excel (.xlsx) files.

It is important to note here that the GetSaveAsFilename() method may change the current drive or folder.

Syntax for the GetSaveAsFilename Method in Excel

The syntax for the GetSaveAsFilename() method is as follows:

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

Here, expression is an application object variable.

The arguments of this function are all optional. Here’s what they represent:

  • InitialFilename is the default filename that appears in the ‘Filename’ input field when the dialog box appears. It is usually used to provide the user with a suggested file name. If this argument is omitted, Microsoft Excel uses the name of the active workbook.
File name in the save as dialog box
  • FileFilter is a string with which you can specify the file filtering criteria, like which types of files the user will be allowed to save the file with. This string can have a maximum of 255 characters.
  • FilterIndex is the number of file filters that you want to use.
  • Title is the title you want to be displayed in the title bar of the Save As dialog box. If this argument is omitted, the default title ‘Save As’ is used.
Title to show in the save as dialog box

Example VBA Codes Using GetSaveAsFilename in Excel

Let us take a look at some example codes to understand how the GetSaveAsFilename method is used and applied.

VBA Code to Get Filename with Path from a Save As Dialog Box

The first sample code lets you extract the file name specified by the user in the ‘Filename’ field of the Save As dialog box and then use it to display the name of the file in a message box.

Sub Example1()
Dim varResult As Variant
ResultVar = Application.GetSaveAsFilename()
If ResultVar <> False Then
MsgBox "Filename entered: " & ResultVar
End If
End Sub

When you run the above code, you should see a Save As dialog box that will let you enter a filename. 

Dialog boz that allows entering file name

When you click Save, you should see a message box with the filename you entered along with the entire file path displayed. 

Message box that shows the entire path

Note that this code will only cause the Save As dialog box to be displayed. Pressing the Save button will not actually save the file.

Explanation of the Code

Let us understand the above code (Example1) line by line:

Line 1: This line declares a variable varResult of type Variant. The Variant data type can be used to define variables that contain any type of data.

Dim varResult As Variant

Line 2: This line displays the Save As dialog box.

ResultVar = Application.GetSaveAsFilename()

Line 3: This line first checks if the user has entered a filename and there are no errors. If so, then it takes the entire path of the file, along with the filename the user specified, and displays it in a message box.

If ResultVar <> False Then
MsgBox "Filename entered: " & ResultVar
End If

VBA Code to Display Save As Dialog Box with File Filters

This sample code lets you specify a specific file filter, so that the user is only allowed to save a file of the specified file type.

Let’s say you want to only give the user the option to save their file as a text file. Here’s the code, you will need for that:

Sub Example2()
Dim varResult As Variant
ResultVar = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
If ResultVar <> False Then
ActiveWorkbook.SaveAs ResultVar
End If
End Sub

When you run this code you will see the Save As dialog box displaying just one option in the ‘Save as type’ dropdown list – ‘Text Files’, and when you subsequently save the file, you will get the file saved as a ‘.txt’ file. 

Save as Dialog with the option to choose file type

Explanation of the Code

Let us understand the above code (Example2) line by line:

Line 1: This line declares a variable varResult of type Variant.

Dim varResult As Variant

Line 2: This line displays the Save As dialog box, providing the user the option to save the file as a text file only. The string ‘Text files’ will be displayed in the drop down list for the ‘Save as type’ field and the filename specified by the user will be appended with the extension ‘.txt’.

ResultVar = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")

Line 3: This line first checks if the user has entered a filename and there are no errors. If so, then it saves the active workbook with the file name specified by the user as a text file.

The SaveAs() method is what actually saves the file when the ‘Save’ button is pressed.

Without this line, only the Save As dialog box would be displayed but nothing would get saved when the user presses the Save button.

If ResultVar <> False Then
ActiveWorkbook.SaveAs ResultVar
End If

You can also use the GetSaveAsFilename method to specify multiple filters.

For example, say you want to give the user the option to save their file as either a text file (*.txt) or an Excel file (*.xlsx). In that case, you can replace line 2 in the above code with the following line:

ResultVar = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt, Excel Files (*.xlsx), *.xlsx")

Here’s what the dialog box would then look like:

Only the specified options show up in the save as dialog box

VBA Code to Display Save As Dialog box from a Specified Start Location

This last sample code lets you specify a particular location, drive or directory from where you want the Save As dialog box to start. Let’s say you want the dialog box to start from the D: drive. Here’s the code, you will need for that:

Sub Example3()
Dim varResult As Variant
ResultVar = Application.GetSaveAsFilename(InitialFileName:="D:")
If ResultVar <> False Then
MsgBox "Filename entered: " & ResultVar
End If
End Sub

Note that the InitialFileName argument just provides the location from which the Save As dialog box starts.

The user will have the option to change this location, drive or directory as needed.

Automatically picks up the save location drive

In this tutorial we demonstrated, with the help of a few sample VBScript codes, how to use the GetSaveAsFilename() method.

This method allows the user to enter the name and location of a file using the Save As dialog box. We hope you found this helpful.

Other articles you may also like:

  • Using Application.EnableEvents in VBA in Excel (Explained with Examples)
  • Why does Excel Open on Startup (and How to Stop it)
  • How to Start Excel in Safe Mode (3 Easy Ways)
  • SetFocus in Excel VBA – How to Use it?
  • How to Open Excel Files Using VBA
  • Subscript Out of Range Error in VBA – How to Fix!

I am trying to follow the tutorial here http://software-solutions-online.com/excel-vba-save-file-dialog-getsaveasfilename/ and have typed up my code to be:

varResult = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xlsx), *.xlsx")

Now when I compile the syntax I get an error of:

Method or Data Membor Not Found

On this specific element GetSaveAsFilename

I am running this in Access 2013 to save an Excel 2013 .xlsx — what should I change so this will prompt the user for a save name and location?

asked Dec 25, 2017 at 4:45

IcyPopTarts's user avatar

IcyPopTartsIcyPopTarts

4941 gold badge12 silver badges25 bronze badges

2

This particular method won’t work in Access VBA. (VBA isn’t 100% interchangeable between the Office products.)

Sample in Access VBA:

Sub TestFileDialog()
'requires Reference to "Microsoft Office xx.x Object Library"
    Dim strFilename As String
    With Application.FileDialog(msoFileDialogSaveAs)
        If .Show Then
            strFilename = .SelectedItems(1)
        Else
            MsgBox "No filename specified!", vbExclamation
            Exit Sub
        End If
    End With

    'do something with strFilename

End Sub

This should be adaptable to saving your Excel object from Access.

answered Dec 25, 2017 at 5:02

ashleedawg's user avatar

ashleedawgashleedawg

20k8 gold badges73 silver badges104 bronze badges

Another question, “Save as…” dialog box in MSAccess vba: how? on this website has some useful pointers that could help you; I had a similar problem and this solved it for me! Like ashleedawg said, VBA syntax isn’t exactly the same across different applications.

You may also try using the Application.FileDialog msoFileDialogSaveAs but make sure to include the library which contains these symbols into your project. Most likely, Access will generate a prompt informing you to add the library reference to the project.
the only issue would be that you can’t apply file type filters. If that is something which is important to do, take a look at this guide on the microsoft forums. Display Open and Save As Dialog Boxes in Access with API Functions.

answered Feb 22, 2018 at 16:08

tanvi's user avatar

tanvitanvi

5481 gold badge11 silver badges31 bronze badges

3

Понравилась статья? Поделить с друзьями:
  • Vba excel окно для ввода данных
  • Vba excel ожидание 5 секунд
  • Vba excel одну ячейку на несколько
  • Vba excel одномерный массив в столбец
  • Vba excel одномерные массивы