Filedialog filter vba excel

Хитрости »

17 Июнь 2015              147350 просмотров


Диалоговое окно выбора файлов/папки

Часто при работе с файлами и написании кодов начинающие «кодить» в VBA сталкиваются с необходимостью предоставить пользователю возможность самостоятельного выбора файлов: либо всех в указанной папке, либо каких-то отдельных. Конечно, можно жестко в коде написать нечто вроде: «C:DocumentsFilesКнига1.xls», но это требует не только наличия именно диска С, но и полной структуры папок и имен файлов. Это очень неудобно в большинстве случаев и куда чаще необходимо дать пользователю возможность самому указать имя файла. Записывать в ячейку листа полный путь и имя весьма непрактично и часто для неискушенного пользователя вызывает только «отторжение» от программы. В статье Просмотреть все файлы в папке я приводил пример кода, который просматривает все файлы в указанной папке и папка при этом выбирается сами пользователем из привычного по работе с Windows диалога. Там используется диалог выбора папок. Именно на этом я и хочу сделать акцент в этой статье — рассказать про некоторые способы вызова подобных диалогов для выбора файлов или папки. Так же обращу внимание на некоторые вещи, которые следует учитывать при использовании того или иного типа диалогов.

  • Диалог выбора файлов Applicaton.GetOpenFileName
  • Диалог выбора файлов FileDialog(msoFileDialogFilePicker)
  • Диалог выбора папки FileDialog(msoFileDialogFolderPicker)
  • Диалог выбора папки через Shell
  • Диалог сохранения файла SaveAs

Если рассматривать наиболее простые варианты, то их два. Выбрать файлы можно через Applicaton.GetOpenFileName или через Application.FileDialog. Отличия в них есть, но я заострю внимание на главном: GetOpenFileName будет работать в любой версии Excel, а класс FileDialog только начиная с Excel 2002, т.к. именно в этой версии впервые был использован класс FileDialog. Это стоит учитывать при разработке.

Диалог выбора файлов Applicaton.GetOpenFileName

Параметры:

Application.GetOpenFilename([FileFilter], [FilterIndex], [Title], [ButtonText], [MultiSelect])
По сути я часто использую именно его, т.к. это универсальный метод и в нем есть все, что лично мне необходимо: выбрать определенные типы файлов позволяет, возможность запрета выбора нескольких файлов сразу есть.

FileFilter Указываются типы файлов, которые будут отображаться в диалоговом окне выбора. Например, если указать «Excel files(*.xls*),*.xls*», то возможно будет выбрать только файлы Excel(с расширением, начинающимся на .xls — .xls, .xlsx, .xlsb, .xlsm и т.д.). Если указать «Text files(*.txt),*.txt», то можно будет выбрать только текстовые файлы с расширением .txt. Так же можно указать более одного типа расширений: «Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt». По умолчанию тип файлов в диалоговом окне будет принадлежать первому указанному типу файлов(*.xls*). Но можно указать любой из перечисленных типов при помощи аргумента FilterIndex. Так же можно указать выбор любых типов файлов: «All files(*.*),*.*»
FilterIndex Если аргументом FileFilter указано более одного типа файлов(расширений), то этот аргумент указывает какой именно тип использовать. Например, следующая строка по умолчанию назначает выбор текстовых типов файлов:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , True)

Атрибут FilterIndex

Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открытие документа»)
ButtonText Данный аргумент доступен только для ПК под управлением Macintosh(MAC). Назначает текст для кнопки диалогового окна Открыть. Для владельцев Windows этот текст всегда будет «Открыть»
MultiSelect Указывает, может быть выбран только один файл или несколько:

  • True — можно будет выбрать более одного файла для обработки(через Shift или Ctrl или простым выделением мышью внутри окна)
  • False — можно будет выбрать только один файл

По умолчанию принимает значение False
Выбора только одного файла:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , False)

Выбор нескольких файлов:

avFiles = Application.GetOpenFilename _
    ("Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", 2, _
     "Выбрать текстовые или Excel файлы", , True)

Пример применения диалога Application.GetOpenFilename

Sub ShowGetOpenDialod()
    Dim avFiles
    'по умолчанию к выбору доступны файлы Excel(xls,xlsx,xlsm,xlsb)
    avFiles = Application.GetOpenFilename _
                ("Excel files(*.xls*),*.xls*", 1, "Выбрать Excel файлы", , False)
    If VarType(avFiles) = vbBoolean Then
        'была нажата кнопка отмены - выход из процедуры
        Exit Sub
    End If
    'avFiles - примет тип String
    MsgBox "Выбран файл: '" & avFiles & "'", vbInformation, "www.excel-vba.ru"
End Sub

В данном случае совершенно неважно указан ли выбор только одного файла или нескольких. Может поменяться только способ обработки полученного результата. Если параметр MultiSelect установлен в False, то переменная avFiles примет тип String, т.е. это будет одна строка. Предположим, что была выбрана книга Excel. Тогда открыть её можно будет как обычно это делается при использовании переменной:

Если же параметр MultiSelect установлен в True, то переменная avFiles примет тип Array — массив строк, в котором будут записаны все пути и имена выбранных файлов. Обрабатывать в таком случае следует циклом:

'avFiles - примет тип Array
    For Each x In avFiles
        Workbooks.Open x
    Next

В приложенном к статье файле приведены две процедуры с использованием этого типа диалога и обработкой файлов с параметром MultiSelect, установленным в True и False.


 
Диалог выбора файлов FileDialog(msoFileDialogFilePicker)

У этого диалога тоже есть параметры и они очень схожи с таковыми в Application.GetOpenFilename:
Ниже в статье примера кода с применением всех описанных параметров

AllowMultiSelect Указывает, может быть выбран только один файл или несколько:

  • True — можно будет выбрать более одного файла для обработки(через Shift или Ctrl или простым выделением мышью внутри окна)
  • False — можно будет выбрать только один файл
Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открытие документа»)
Filters Перечисляются типы файлов, которые будут отображаться в диалоговом окне выбора. Для добавления типа файла(расширения) необходимо использовать метод Add:
.Filters.Add([Description],[Extensions],[Position])

  • Description — описание типа файлов. Произвольный текст, указывающий тип файлов. Например «Рисунки» или «Файлы Excel».
  • Extensions — расширения файлов. Непосредственно перед расширением обязательно должна стоять звездочка и точка: *.xls. Иначе диалог выдаст ошибку. Для перечисления нескольких расширений используется разделитель в виде точки-с-запятой: «*.xls*;*.xla*» или «*.xls;*.xlsx;*.xlsm». Звездочка после расширения заменяет любой набор символов или ни одного. Например, при указании «*.xls*» будет возможным выбрать любые файлы, расширение которых начинается на .xls: .xls,.xlsx,.xlsm,.xlsb и т.д., но нельзя будет выбрать файлы с расширением .xla,.xlam и тем более .doc или .txt. Если необходимо осуществить выбор любого типа файлов, то необходимо просто очистить фильтр и не добавлять никакие типы: .Filters.Clear
  • Position — указывает, каким по счету в списке будет тип файлов. На рисунке ниже первым идет тип «Excel files», а вторым «Text files»:
    Атрибут FilterIndex
  • Тип файлов, который будет показан по умолчанию при вызове диалога определяется свойством FilterIndex диалога FileDialog.
    Важный момент: диалог, вызванный в одном сеансе Excel сохраняет добавленные ранее типы файлов. Поэтому перед назначением новых типов необходимо выполнить очистку фильтра:
    .Filters.Clear

Каждый новый тип файлов добавляется новым Add:

.Filters.Add "Excel files", "*.xls*;*.xla*", 1 'добавляем возможность выбора файлов Excel
.Filters.Add "Text files", "*.txt", 2 'добавляем возможность выбора текстовых файлов
FilterIndex Назначает тип файлов, который будет выбран по умолчанию из всех перечисленных в коллекции Filters при вызове диалога
InitialFileName Этим параметром можно задать начальную папку, на которой будет открыт диалог:

.InitialFileName = "С:Temp"

Если при этом еще добавить имя файла, то в поле диалога Имя файла будет так же отображено это имя:

.InitialFileName = "С:TempКнига1.xlsx"

Я лично не рекомендую указывать имя файла, т.к. после показа диалога этот файл автоматически будет выбран, что не всегда бывает правильным. Но все зависит от задач. Если пользователь не выберет самостоятельно ни одного файла, то ответом диалога будет именно файл с указанным именем(Книга1.xlsx). Если такого файла не окажется в папке, то диалог выдаст предупреждение, что такого файла нет.

InitialView Данный параметр определяет внешний вид и структуру окна диалога. Доступно 9 вариантов:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewTiles
  • msoFileDialogViewWebView

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

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

For Each x In .SelectedItems
    Workbooks.Open x
Next

Так же можно отбирать только отдельные файлы по индексам или организовать цикл иначе:

For lf = 1 to .SelectedItems.Count
    x = .SelectedItems(lf)
    Workbooks.Open x
Next

Нумерация строк в SelectedItems всегда начинается с 1

Show Пожалуй, самый важный метод в диалоге — отвечает за показ диалога. При этом метод Show возвращает ответ в виде целого числа:

  • -1 — выбор файлов был сделан и нажата кнопка Открыть
  • 0 — была нажата кнопка отмены

Это можно(точнее нужно!) использовать, чтобы не продолжать выполнение кода, если нажата кнопка Отмены:

If .Show = 0 Then Exit Sub 'была нажата кнопка отмены

Пример вызова диалога выбора файлов:

Sub ShowFileDialog()
    Dim oFD As FileDialog
    Dim x, lf As Long
    'назначаем переменной ссылку на экземпляр диалога
    Set oFD = Application.FileDialog(msoFileDialogFilePicker)
    With oFD 'используем короткое обращение к объекту
    'так же можно без oFD
    'With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .Title = "Выбрать файлы отчетов" 'заголовок окна диалога
        .Filters.Clear 'очищаем установленные ранее типы файлов
        .Filters.Add "Excel files", "*.xls*;*.xla*", 1 'устанавливаем возможность выбора только файлов Excel
        .Filters.Add "Text files", "*.txt", 2 'добавляем возможность выбора текстовых файлов
        .FilterIndex = 2 'устанавливаем тип файлов по умолчанию - Text files(Текстовые файлы)
        .InitialFileName = "С:TempКнига1.xlsx" 'назначаем папку отображения и имя файла по умолчанию
        .InitialView = msoFileDialogViewDetails 'вид диалогового окна(доступно 9 вариантов)
        If .Show = 0 Then Exit Sub 'показывает диалог
        'цикл по коллекции выбранных в диалоге файлов
        For lf = 1 To .SelectedItems.Count
            x = .SelectedItems(lf) 'считываем полный путь к файлу
            Workbooks.Open x 'открытие книги
            'можно также без х
            'Workbooks.Open .SelectedItems(lf)
        Next
    End With
End Sub

 
Диалог выбора папки

Диалог выбора папки необходим в случаях, когда файлов в папке много и обработать нужно все эти файлы. Пример такой обработки я уже выкладывал в статье Просмотреть все файлы в папке. Здесь проще всего использовать появившийся в 2002 Excel диалог Application.FileDialog. Его параметры практически такие же, как у Application.FileDialog(msoFileDialogFilePicker) только их меньше доступно для применения:

Title Текст заголовка диалогового окна. Если указать «Выбрать папку с отчетами», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Открыть папку»)
InitialFileName Этим параметром можно задать начальную папку, на которой будет открыт диалог:

.InitialFileName = "С:Temp"
InitialView Данный параметр определяет внешний вид и структуру окна диалога. Доступно 9 вариантов:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewTiles
  • msoFileDialogViewWebView

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

SelectedItems Возвращает коллекцию с одним элементом, в котором содержится путь к выбранной папке. Нумерация строк в SelectedItems всегда начинается с 1, но т.к. выбор нескольких папок невозможен, то всегда указывается 1: x = .SelectedItems(1)
ButtonName Назначает текст кнопки, которой подтверждается выбор папки. Может содержать не более 51 знака(чего как правило достаточно).
Show Метод, который вызывает показ диалога с выбранными параметрами. Возвращает ответ в виде целого числа:

  • -1 — папка выбрана и нажата кнопка Открыть
  • 0 — была нажата кнопка отмены

Это можно(точнее нужно!) использовать, чтобы не продолжать выполнение кода, если нажата кнопка Отмены:

If .Show = 0 Then Exit Sub 'была нажата кнопка отмены

Пример вызова диалога выбора папки:

Sub ShowFolderDialog()
    Dim oFD As FileDialog
    Dim x, lf As Long
    'назначаем переменной ссылку на экземпляр диалога
    Set oFD = Application.FileDialog(msoFileDialogFolderPicker)
    With oFD 'используем короткое обращение к объекту
    'так же можно без oFD
    'With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Выбрать папку с отчетами" '"заголовок окна диалога
        .ButtonName = "Выбрать папку"
        .Filters.Clear 'очищаем установленные ранее типы файлов
        .InitialFileName = "C:Temp" '"назначаем первую папку отображения
        .InitialView = msoFileDialogViewLargeIcons 'вид диалогового окна(доступно 9 вариантов)
        If .Show = 0 Then Exit Sub 'показывает диалог
        'цикл по коллекции выбранных в диалоге файлов
        x = .SelectedItems(1) 'считываем путь к папке
        MsgBox "Выбрана папка: '" & x & "'", vbInformation, "www.excel-vba.ru"
    End With
End Sub

 
Диалог выбора папки через Shell

Диалог Application.FileDialog(msoFileDialogFolderPicker) всем хорош и удобен, кроме одного: как я уже упоминал, он стал доступен из VBA только начиная с 2002 Excel. Плюс, описанные выше диалоги не работают в Outlook — он просто лишен хоть какой-либо реализации выбора папок или файлов. Поэтому дополню статью еще одним вариантом показа диалога выбора папки — с помощью объекта Shell. Этот вариант выбора папки будет работать и в Outlook и в любом другом приложении.

Shell.BrowseForFolder([Hwnd], [sTitle], [iOptions], [vRootFolder])

Hwnd Дескриптор окна, к которому будет относится диалог. Как правило указывается 0
sTitle Поясняющий текст, который будет отображен в диалоге. Подобие заголовка окна. Может быть любым текстом, например «Выбрать папку с отчетами»
iOptions Дополнительные параметры для диалога. Рекомендуется использовать 0. Но можно попробовать и пару других вариантов. Например, если указать 20, то в диалоговом окне появится дополнительное текстовое поле, в котором будет отображено имя выбранной папки.
vRootFolder Аналогично InitialFileName в рассмотренных выше диалогах. Задает начальную папку, на которой диалог будет открыт после запуска.

Диалог выбора папки - Shell
Пример вызова диалога выбора папки через Shell:

Sub GetFolderDialog_Shell()
    On Error Resume Next
    Dim objShellApp As Object, objFolder As Object, ulFlags
    Dim x As String
    Set objShellApp = CreateObject("Shell.Application")
    'ulFlags - числовой код, определяющий вид отображаемого окна и некоторые параметры
    '    ulFlags = 0     - наиболее часто применяемый. Лучше использовать всегда именно 0
    '    ulFlags = 1     - не отображать Корзину
    '    ulFlags = 2     - не включать сетевые папки
    '    ulFlags = 20    - добавляется тестовое поле с отображением имени выбранной папки
    '    ulFlags = 16    - отображать EditBox для ввода полного пути с клавиатуры
    '    ulFlags = 16384 - можно так же выбирать файлы.
    'Некоторые константы можно комбинировать. Например если указать 1 + 16384 - то можно будет выбирать файлы
 
    ulFlags = 0
    Set objFolder = objShellApp.BrowseForFolder(0, "Выбрать папку с отчетами", ulFlags, "C:Temp")'"
    x = objFolder.Self.Path 'записываем в переменную путь к папке
    If Err.Number <> 0 Then
        MsgBox "Папка не выбрана!", vbInformation, "www.excel-vba.ru"
    Else
        MsgBox "Выбрана папка: '" & x & "'", vbInformation, "www.excel-vba.ru"
    End If
End Sub

Конечно, диалог подобный выглядит довольно убого, особенно на современных операционных системах. Но он работает в любых версиях офиса и в любом приложении, в том числе в Outlook. Порой это бывает полезней красоты.

Скачать пример:

  Tips_Macro_GetOpenFileFolder.xls (100,0 KiB, 3 740 скачиваний)


 
Диалог сохранения файла SaveAs

Еще один вид диалогового окна — запрос имени и места сохранения файла.
Параметры:

Application.GetSaveAsFilename([InitialFileName], [FileFilter], [FilterIndex], [Title], [ButtonText])
Универсальный диалог, работающий во всех версиях Excel, начиная с 2000

InitialFileName Можно указать путь и имя файла, которые будут использованы в качестве шаблона для сохранения. По умолчанию в диалоге отображается папка, которая была использована в последний раз в текущем сеансе Excel. Если диалог вызывается впервые, то будет показана для сохранения файлов по умолчанию(задается из самого Excel: Файл(File)Параметры(Options)Сохранение(Save)Расположение локальных файлов по умолчанию(Default local file location)).
Показываем диалог со стартовой папкой на той книге, в которой сам макрос, без указания имени сохраняемой книги:

sToSavePath = Application.GetSaveAsFilename(InitialFileName:=ThisWorkbook.Path)

Показываем диалог со стартовой папкой на той книге, в которой сам макрос и именем сохраняемой книги «SaveAs.xlsm»:

sToSavePath = Application.GetSaveAsFilename(InitialFileName:="SaveAs.xlsm", FileFilter:="Excel files (*.xlsm), *.xlsm")

Здесь следует обратить внимание на один важный момент: если необходимо помимо стартовой папки указать еще и имя файла, то в обязательном порядке надо указывать так же аргумент FileFilter. Если его не указывать, то InitialFileName просто откроет указанную папку, т.к. не поймет файлы какого типа надо отображать. Либо вместо «SaveAs.xlsm» надо будет указывать «SaveAs.*», что я лично настоятельно не рекомендую делать.
Несмотря на возможность указать имя файла его можно изменить прямо в диалоговом окне, что тоже порой правильнее. Например, чтобы убедиться в том, что имя файла указано пользователем.

FileFilter Указываются типы файлов, которые будут отображаться в диалоговом окне выбора. Должен совпадать с тем типом, с которым собираемся сохранять файл. Например, если указать «Excel files(*.xls*),*.xls*», то возможно будет выбрать только тип файлов Excel(с расширением, начинающимся на .xls — .xls, .xlsx, .xlsb, .xlsm и т.д.). Если указать «Text files(*.txt),*.txt», то только текстовые файлы с расширением .txt. Так же можно указать более одного типа расширений: «Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt». По умолчанию тип файлов в диалоговом окне будет принадлежать первому указанному типу файлов(*.xls*). Но можно указать любой из перечисленных типов при помощи аргумента FilterIndex. Так же можно указать выбор любых типов файлов: «All files(*.*),*.*»
FilterIndex Если аргументом FileFilter указано более одного типа файлов(расширений), то этот аргумент указывает какой именно тип использовать. Например, следующая строка по умолчанию назначает выбор и сохранение файла в текстовый:

avFiles = Application.GetSaveAsFilename _
    (InitialFileName:=ThisWorkbook.Path, FileFilter:="Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", FilterIndex:=2)

Атрибут FilterIndex

Title Текст заголовка диалогового окна. Если указать «Выбрать текстовые или Excel файлы», то именно этот текст будет в заголовке. Если не указывать, то будет текст по умолчанию(нечто вроде «Сохранение документа»)
ButtonText Данный аргумент доступен только для ПК под управлением Macintosh(MAC). Назначает текст для кнопки диалогового окна Сохранить. Для владельцев Windows этот текст всегда будет «Сохранить»

Что еще важно знать: сам по себе вызов диалога GetSaveAsFilename ничего не сохраняет — он только создает путь для сохраняемого файла. Сохранять придется принудительно после выбора места и имени.
Пример применения диалога Application.GetSaveAsFilename

Sub ShowGetSaveAsDialod()
    Dim sToSavePath
    sToSavePath = Application.GetSaveAsFilename( _
             InitialFileName:=ThisWorkbook.Path, _
             FileFilter:="Excel files(*.xls*),*.xls*,Text files(*.txt),*.txt", _
             FilterIndex:=2, _
             Title:="Сохранить файл")
    'если нажали Отмена - завершаем процедуру ничего не сохраняя
    If VarType(sToSavePath) = vbBoolean Then
        Exit Sub
    End If
    'непосредственно сохранение файла
    ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=ThisWorkbook.FileFormat
End Sub

Здесь тоже есть нюанс — метод SaveAs имеет два важных аргумента:
1. Filename — путь и имя сохраняемого файла. Здесь должно быть все понятно. Указываем то, что выбрали в диалоге.
2. FileFormat — формат сохраняемого файла. При этом не текстовое представление(как в диалоге «xls» или «txt»), а одна из предустановленных констант формата файла. Вот основные константы:

Константа Excel Числовая константа Расшифровка
xlOpenXMLWorkbookMacroEnabled 51 xlsm — книга Excel
xlOpenXMLWorkbookMacroEnabled 52 xlsm — книга Excel с поддержкой макросов
xlExcel12 50 xlsb — двоичная книга Excel (с поддержкой макросов)
xlOpenXMLAddIn 55 xlam — надстройка Excel
xlOpenXMLTemplate 54 xltx — шаблон Excel
xlOpenXMLTemplateMacroEnabled 53 xltm — шаблон Excel с поддержкой макросов
xlExcel8 56 xls — книга Excel(97 — 2003)
xlAddIn 18 xla — надстройка Excel(97 — 2003)
xlTemplate 17 xlt — шаблон Excel(97 — 2003)
xlCurrentPlatformText -4158 txt — текстовый файл с разделителями табуляции
xlUnicodeText 42 txt — текстовый файл в кодировке Юникод
xlCSV 6 csv — CSV(разделитель запятая)
xlCSVMSDOS 24 csv — CSV(MS — DOS)
XlFileFormat 62 csv — CSV UTF-8(разделитель запятая)
xlTypePDF 0 pdf — файл в формате PDF

Пример использования констант в диалогах Application.GetSaveAsFilename
Сохраняем файл с форматом xlsm — файл с поддержкой макросов. Для этого ищем в таблице выше расширение xlsm и берем либо константу Excel либо числовую константу:

Sub ShowGetSaveAsDialod()
    Dim sToSavePath
    sToSavePath = Application.GetSaveAsFilename( _
             InitialFileName:=ThisWorkbook.Path & "Report.xlsm", _
             FileFilter:="Excel files(*.xlsm),*.xlsm")
    'если нажали Отмена - завершаем процедуру ничего не сохраняя
    If VarType(sToSavePath) = vbBoolean Then
        Exit Sub
    End If
    'непосредственно сохранение файла
    'используем встроенную константу Excel
    ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=xlOpenXMLWorkbookMacroEnabled
    'используем числовую константу
    'ThisWorkbook.SaveAs Filename:=sToSavePath, FileFormat:=52
End Sub

Любой метод: либо числовая константа, либо встроенная работают одинаково. Вопрос лишь в том, что лично для Вас будет удобнее и нагляднее.

Так же см.:
Работа с диалогами
Как запретить сообщения?


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

I have a macro that asks a user to choose multiple files for data analysis. User selects a Excel or CSV file first (XLSX, XLS, CSV), then asks for a second file but CSV only. The intent of the tool is to combine the two data files into one.

In one Sub, I ask the user to select any compatible XLSX, XLS, or CSV files using the FileDialog code:

Dim myObj As Object
Dim myDirString As String
Set myObj = Application.FileDialog(msoFileDialogFilePicker)
With myObj
    .InitialFileName = "C:Users" & Environ$("Username") & "Desktop"
    .Filters.Add "Custom Excel Files", "*.xlsx, *.csv, *.xls"
    .FilterIndex = 1
    If .Show = False Then MsgBox "Please select Excel file.", vbExclamation: Exit Sub
    myDirString = .SelectedItems(1)
End With

It seems to filter appropriately:

Custom Excel Files

After this data analysis in complete, then the user runs a second sub to select another file, but it must be a CSV file only. So I use this code to request CSV:

Dim yourObj3 As Object
Dim yourDirString3 As String
Set yourObj3 = Application.FileDialog(msoFileDialogFilePicker)
With yourObj3
    .InitialFileName = "C:Users" & Environ$("Username") & "Desktop"
    .Filters.Add "CSV Files", "*.csv"
    .FilterIndex = 1
    If .Show = False Then MsgBox "Please select CSV file.", vbExclamation: Exit Sub
    yourDirString3 = .SelectedItems(1)
End With

The problem is the FileDialog box remembers the first filter (Custom XLS) and they need to click the drop down to see the appropriate filter for CSV only…

Select CSV

So this would certainly be confusing to the user…I’m guessing I need to «clear» our that first filter after the user completes the first macro. Any suggestions on that code to clear (or reset) the first filter?

Tried adding this below it when I found what I thought was a similar question FileDialog persists previous filters:

With .Filters
.Clear 
End With

But results in Compile error: Invalid or unqualified reference

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

FileDialogFilters object (Office)

vbaof11.chm255000

vbaof11.chm255000

office

Office.FileDialogFilters

a74663cf-ad63-e41a-8d5e-e51e8a20c173

01/09/2019

medium

FileDialogFilters object (Office)

A collection of FileDialogFilter objects that represent the types of files that can be selected in a file dialog box that is displayed by using the FileDialog object.

Example

Use the Filters property of the FileDialog object to return a FileDialogFilters collection. The following code returns the FileDialogFilters collection for the File Open dialog box.

Application.FileDialog(msoFileDialogOpen).Filters

Use the Add method to add FileDialogFilter objects to the FileDialogFilters collection.

The following example uses the Clear method to clear the collection and then adds filters to the collection. The Clear method completely empties the collection; however, if you don’t add any filters to the collection after you clear it, the «All files (.)» filter is added automatically.

Sub Main() 
 
    'Declare a variable as a FileDialog object. 
    Dim fd As FileDialog 
 
    'Create a FileDialog object as a File Picker dialog box. 
    Set fd = Application.FileDialog(msoFileDialogFilePicker) 
 
    'Declare a variable to contain the path 
    'of each selected item. Even though the path is aString, 
    'the variable must be a Variant because For Each...Next 
    'routines only work with Variants and Objects. 
    Dim vrtSelectedItem As Variant 
 
    'Use a With...End With block to reference the FileDialog object. 
    With fd 
 
        'Change the contents of the Files of Type list. 
        'Empty the list by clearing the FileDialogFilters collection. 
        .Filters.Clear 
 
        'Add a filter that includes all files. 
        .Filters.Add "All files", "*.*" 
 
        'Add a filter that includes GIF and JPEG images and make it the first item in the list. 
        .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1 
 
        'Use the Show method to display the File Picker dialog box and return the user's action. 
        'The user pressed the button. 
        If .Show = -1 Then 
 
            'Step through eachString in the FileDialogSelectedItems collection. 
            For Each vrtSelectedItem In .SelectedItems 
 
                'vrtSelectedItem is aString that contains the path of each selected item. 
                'Use any file I/O functions that you want to work with this path. 
                'This example displays the path in a message box. 
                MsgBox "Path name: " & vrtSelectedItem 
 
            Next vrtSelectedItem 
        'The user pressed Cancel. 
        Else 
        End If 
    End With 
 
    'Set the object variable to Nothing. 
    Set fd = Nothing 
 
End Sub

When changing the FileDialogFilters collection, remember that each application can only create an instance of a single FileDialog object. This means that the FileDialogFilters collection resets to its default filters whenever you call the FileDialog method with a new dialog box type. The following example iterates through the default filters of the SaveAs dialog box and displays the description of each filter that includes a Microsoft Excel file.

Sub Main() 
 
    'Declare a variable as a FileDialogFilters collection. 
    Dim fdfs As FileDialogFilters 
 
    'Declare a variable as a FileDialogFilter object. 
    Dim fdf As FileDialogFilter 
 
    'Set the FileDialogFilters collection variable to 
    'the FileDialogFilters collection of the SaveAs dialog box. 
    Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters 
 
    'Iterate through the description and extensions of each 
    'default filter in the SaveAs dialog box. 
    For Each fdf In fdfs 
 
        'Display the description of filters that include 
        'Microsoft Excel files 
        If InStr(1, fdf.Extensions, "xls", vbTextCompare) > 0 Then 
            MsgBox "Description of filter: " & fdf.Description 
        End If 
    Next fdf 
 
End Sub

[!NOTE]
A run-time error occurs if the Filters property is used in conjunction with the Clear, Add, or Delete methods when applied to a Save As FileDialog object. For example, Application.FileDialog(msoFileDialogSaveAs).Filters.Clear will result in a run-time error.

See also

  • FileDialogFilters object members
  • Object Model Reference

[!includeSupport and feedback]

application filedialog featured

Often in VBA we need to ask the users to select files or directories before we execute the actual functionality of our macro. Welcome to the VBA Open file dialog post. Today we will learn how to use the Application.FileDialog, to understand the various msoFileDialogFilePicker file dialog picking options and how to properly manage these dialogs.

Here is a simple example of a VBA File Dialog:

Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
   Debug.Print fDialog.SelectedItems(1) 'The full path to the file selected by the user
End If

Application FileDialog function

Before we start let’s understand the Application.FileDialog function.

The Application.FileDialog has the following syntax:

Application.FileDialog( fileDialogType as MsoFileDialogType )

Parameter

MsoFileDialogType
An enumeration defining the type of file dialog to open. It has the following values:

Value Description
msoFileDialogOpen Open dialog box
msoFileDialogSaveAs Save As dialog box
msoFileDialogFilePicker File picker dialog box
msoFileDialogFolderPicker Folder picker dialog box

Properties and functions

FileDialog properties

Property Description
AllowMultiSelect Allow to select more than one file or folder
ButtonName Text displayed on the action button of a file dialog box
DialogType Change the MsoFileDialogType (see above)
Filter Set a file filter to filter file types user can select
InitialFileName The initial path to be opened e.g. C:
InitialView The initial file view. Can be one of the following:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewWebView
SelectedItems Collection of type FileDialogSelectedItems with all selected items
Title Title of the Open file dialog window

Select files – msoFileDialogFilePicker

select file filedialogThe msoFileDialogFilePicker dialog type allows you to select one or more files.

Select single files

The most common select file scenario is asking the user to select a single file. The code below does just that:

Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
'Optional: FileDialog properties
fDialog.AllowMultiSelect = False
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
fDialog.Filters.Add "All files", "*.*"

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
   Debug.Print fDialog.SelectedItems(1)
End If

'Result: C:somefile.xlsx

Select multiple files

Quite common is a scenario when you are asking the user to select one or more files. The code below does just that. Notice that you need to set AllowMultiSelect to True.

Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
'IMPORTANT!
fDialog.AllowMultiSelect = True

'Optional FileDialog properties
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
fDialog.Filters.Add "All files", "*.*"

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
  For Each it In fDialog.SelectedItems
    Debug.Print it
  Next it
End If

'Results:
'C:somefile.xlsx
'C:somefile1.xlsx
'C:somefile2.xlsx

Select folder – msoFileDialogFilePicker

select folder application.filedialogSelecting a folder is more simple than selecting files. However only a single folder can be select within a single dialog window.

Select folder example

The dialog below will ask the user to select a folder:

Set fDialog = Application.FileDialog(msoFileDialogFolderPicker) 'Important we use msoFileDialogFolderPicker instead of (...)FilePicker

'Optional: Properties
fDialog.title = "Select a folder"
fDialog.InitialFileName = "C:"

If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

The msoFileDialogFolderPicker dialog allows you to only select a SINGLE folder and obviously does not support file folders

Open file – msoFileDialogOpen

file open application.filedialogOpening files is much more simple as it usually involves a single file. The only difference between the behavior between Selecting and Opening files are button labels.

Open file example

The dialog below will ask the user to select a file to open:

Dim fDialog As FileDialog, result As Integer, it As Variant
Set fDialog = Application.FileDialog(msoFileDialogOpen)
    
'Optional: FileDialog properties
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
    
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "All files", "*.*"
fDialog.Filters.Add "Excel files", "*.xlsx"
  
If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

Save file – msoFileDialogSaveAs

saveas application.filedialogSaving a file is similarly easy, and also only the buttons are differently named.

The save file dialog will in fact not save any files! It will just allow the user to select a filename for the file. You need to open the files for reading / writing yourself. Check out my post on how to write files in VBA

Save file example

The dialog below will ask the user to select a path to which a files is to be saved:

Dim fDialog As FileDialog, result As Integer, it As Variant
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)

'Optional: FileDialog properties
fDialog.title = "Save a file"
fDialog.InitialFileName = "C:"

If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

The msoFileDialogSaveAs dialog does NOT support file filters

FileDialog Filters

One of the common problems with working with the Application.FileDialog is setting multiple file filters. Below some common examples of how to do this properly. To add a filter for multiple files use the semicolor ;:

Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogOpen)
'...
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "All files", "*.*"
fDialog.Filters.Add "Excel files", "*.xlsx;*.xls;*.xlsm"
fDialog.Filters.Add "Text/CSV files", "*.txt;*.csv"
'...

Be sure to clear your list of filters each time. The FileDialog has its nuisances and often filters are not cleared automatically. Hence, when creating multiple dialogs you might see filters coming from previous executed dialogs if not cleared and re-initiated properly.

The open file dialog will in fact not open any files! It will just allow the user to select files to open. You need to open the files for reading / writing yourself. Check out my posts:

  • Read file in VBA
  • Write file in VBA

There may be times when you need to ask the user to select a file to open. This can be done using the open file dialog. Keep in mind that the open file dialogs doesn’t actually open anything. It returns the path of the file or files selected.

You can download the workbook for this article here.

Jump To:

  • Example 1
  • Example 2
  • Custom Title
  • Start Folder Path, InitialFilePath
  • Filter File Types, Filters


Example 1, Select Single File:

In this example an open file dialog is displayed and the user is asked to select a file to open. The path of the file selected by the user is then printed in cell A2. Note that the open file dialog doesn’t actually open any files, it only returns the path the user has selected:

Sub Example1()
Dim intChoice As Integer
Dim strPath As String

'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
    'print the file path to sheet 1
    Cells(2, 1) = strPath
End If
End Sub

Result:

Excel VBA Open File Dialog Example 1
After selecting the file “test.txt” from the directory “D:Temp”, the path is printed in cell A2:

Excel VBA Example 1 Result
The line below tells the program to only allow the user to select one file:

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

The line below makes the open file dialog visible to the user:

intChoice = Application.FileDialog(msoFileDialogOpen).Show

If the user cancels the dialog, intChoice will return “0”. The line below returns the path selected by the user:

strPath = Application.FileDialog( _
    msoFileDialogOpen).SelectedItems(1)


Example 2, Select Multiple Files:

In the example below an open file dialog is opened and asks the user to select files to open. Unlike Example 1 the user is permitted to select multiple files in this example. The path of all the files selected by the user is printed in column A. Note that the open file dialog doesn’t actually open any files, it only returns the path the user has selected:

Sub Example2()
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer

'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    For i = 1 To Application.FileDialog(msoFileDialogOpen _
        ).SelectedItems.Count
        strPath = Application.FileDialog(msoFileDialogOpen _
        ).SelectedItems(i)
        'print the file path to sheet 1
        Cells(i + 1, 1) = strPath
    Next i
End If

Result:

Excel VBA Open File Dialog Example 2 Select Multiple Files
After selecting the 3 files, “Test1.txt”, “Test2.txt” and “Test3.txt” from the folder “D:Temp” their paths are printed in Column A:

Excel VBA Example 2 Result


Custom Title:

By default the title of the Open File Dialog is “Open File”:

Excel VBA Open File Dialog Title Default

Using the .Title property you can set a custom title for the dialog. In the example below the title “Random Title For Dialog” will be used:

Sub Example3()
Dim intChoice As Integer

'change the display name of the open file dialog
Application.FileDialog(msoFileDialogOpen).Title = _
    "Random Title For Dialog"
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'your code here
End If
End Sub

Result:

Excel VBA Open File Dialog, Custom Title


Start Folder Path, InitialFileName:

Lets say there is a specific folder we would want the dialog to start in. This could be set by the InitialFileName property. In the example below the open file dialog will start in the directoryD:TempFolder to Start“:

Sub Example4()
Dim intChoice As Integer

'Select the start folder
Application.FileDialog(msoFileDialogOpen _
    ).InitialFileName = "D:TempFolder to Start"
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'your code here
End If
End Sub

Result:

Excel VBA Open File Dialog, Start Folder


Filter File Types, Filters:

In the example below there are multiple file types in our folder, .txt, .xlsx, .docx:

Excel, VBA, Open FIle DialogMultiple File Types in Folder
But when the open file dialog appears, we only want the user to see the .txt files. This can be achieved by applying a filter:

Sub Example5()
Dim intChoice As Integer

'Remove all other filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
    "Text Files Only", "*.txt")
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'your code here
End If
End Sub

Result:

Excel VBA, Open File Dialog Filter

The line below removes all other filter options from the filter list:

Call Application.FileDialog(msoFileDialogOpen).Filters.Clear

The line below adds a custom filter. The name of the custom filter is “Text Files Only”. The expressions “*.txt” means that we only want the files that end in “.txt” to appear in the dialog:

Call Application.FileDialog(msoFileDialogOpen _
    ).Filters.Add("Text Files Only", "*.txt")

You can download the workbook for this article here.

See Also:

  • Excel VBA, Reading Text Files.
  • Find and List All Files and Folders in a Directory

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Понравилась статья? Поделить с друзьями:
  • File will not print in word
  • File which created in ms excel is called
  • File was not saved excel
  • File types microsoft word can open
  • File types for word