ユーザが選択したファイル名を取得する(1)

ユーザが選択したファイルのパスを取得する

Application.FileDialogオブジェクトを使います。

FileDialogオブジェクトとは

おなじみ、Office デベロッパー センターのFileDialog Objectの項には、

Remarks

Use the FileDialog property to return a FileDialog object. The FileDialog property is located in each individual Office application's Application object. The property takes a single argument, DialogType, that determines the type of FileDialog object that the property returns.

ODC "FileDialog Object"の項より

とある。Applicationオブジェクトのプロパティで、一つの引数(DialogType)を渡すと、その引数に応じたFileDialogオブジェクトを返してくれる、ということらしい。

ちなみにFileDialogオブジェクトの種類については、

  • Open dialog box: lets users select one or more files that you can then open in the host application by using the Execute method.
  • SaveAs dialog box: lets users select a single file that you can then save the current file as by using the Execute method.
  • File Picker dialog box: lets users select one or more files. The file paths that the user selects are captured in the FileDialogSelectedItems collection.
  • Folder Picker dialog box: lets users select a path. The path that the user selects is captured in the FileDialogSelectedItems collection.

とあるように、「Open」、「SaveAs」、「Folder Picker」、「File Picker」の四つ。

この四つを、前述のように引数で呼び分ける。

引数は、

f:id:akashi_keirin:20190921094634j:plain

このMsoFileDialogType列挙体が使えるので簡単。

「ファイル選択」ダイアログを使うには

たとえば、

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

とすれば、変数fpDialogに「File Picker」タイプのFileDialogオブジェクトを突っ込むことができる。あとは、FileDialogオブジェクトのプロパティ、メソッドを利用するだけ。

超カンタン!

ユーザにファイル選択をさせるまでの流れ

簡単に道筋だけ示しておく。

  • Application.FileDialogプロパティに引数msoFileDialogFilePickerを渡して「File Picker」タイプのFileDialogオブジェクトを取得する
  • ボックスのタイトル、デフォルトのフォルダパス、ファイルフィルタ、複数選択の可否などの諸設定を施す
  • ボックスを表示する

およそこのようなもの。ボックスの設定については他にもあるが、実用上は上記のものだけで困ることはないと思う。

おわりに

今回はここまで。

フォルダ選択の場合だと、通常の使い方だと複数選択させる場面も少ないので、多くは単純に取得したフォルダパスを取得するだけで良いため、さほど苦労することはない。

しかし、ファイル選択となると、複数選択が必要な場面も多いだろう。また、フォルダの場合は「種類」を気にする必要はないが、ファイルの場合だとユーザのミスを防ぐためにもファイルフィルタを設定した方が良い。

フォルダ選択もファイル選択も似たようなものと感じるが、実際にはファイル選択させるのはかなりめんどくさい。

そのあたりは次回以降……。

つづきはコチラ

akashi-keirin.hatenablog.com

akashi-keirin.hatenablog.com