ユーザが選択したファイル名を取得する(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」の四つ。
この四つを、前述のように引数で呼び分ける。
引数は、
このMsoFileDialogType
列挙体が使えるので簡単。
「ファイル選択」ダイアログを使うには
たとえば、
Dim fpDialog As FileDialog Set fpDialog = Application.FileDialog(msoFileDialogFilePicker)
とすれば、変数fpDialog
に「File Picker」タイプのFileDialog
オブジェクトを突っ込むことができる。あとは、FileDialog
オブジェクトのプロパティ、メソッドを利用するだけ。
超カンタン!
ユーザにファイル選択をさせるまでの流れ
簡単に道筋だけ示しておく。
Application.FileDialog
プロパティに引数msoFileDialogFilePicker
を渡して「File Picker」タイプのFileDialog
オブジェクトを取得する- ボックスのタイトル、デフォルトのフォルダパス、ファイルフィルタ、複数選択の可否などの諸設定を施す
- ボックスを表示する
およそこのようなもの。ボックスの設定については他にもあるが、実用上は上記のものだけで困ることはないと思う。
おわりに
今回はここまで。
フォルダ選択の場合だと、通常の使い方だと複数選択させる場面も少ないので、多くは単純に取得したフォルダパスを取得するだけで良いため、さほど苦労することはない。
しかし、ファイル選択となると、複数選択が必要な場面も多いだろう。また、フォルダの場合は「種類」を気にする必要はないが、ファイルの場合だとユーザのミスを防ぐためにもファイルフィルタを設定した方が良い。
フォルダ選択もファイル選択も似たようなものと感じるが、実際にはファイル選択させるのはかなりめんどくさい。
そのあたりは次回以降……。