ダイアログボックスでExcelファイルを開く

実務では予めファイル名が決まっておらず、一覧から選択したい時があるよね?



え?そうなの?知らん!



そうなんだ!今日はダイアログボックスを表示してその中からExcelファイルを開く処理を動画付きで勉強していくよ!



よろしくお願いしまーす!



今日使う実例と動画はこちらになります。
Sub GetOpenFileName()
Dim bkPath_FileName As String
ChDir "C:\"
bkPath_FileName = Application.GetOpenFileName("Excelファイル,*.xlsx", , "Excelファイルを選択")
If bkPath_FileName = "False" Then Exit Sub
Workbooks.Open bkPath_FileName
End Sub
ダイアログボックスとは、下記のようにユーザー(PC使用者)に何らかの入力を求める時に表示されつウィンドウのことです。


今日はこのダイアログボックスを使ってExcelファイルを開く方法を勉強していきましょう。
ファイルを開く方法はいくつかありますが、今回紹介するApplicationオブジェクトのGetOpenFilenameメソッドが最も一般的です。書式は下記になります。
Application.GetOpenFileName(FileFilter,FilterIndex,Title)
実例では、7行目で
- FileFilterに“Excelファイル,*.xlsx”と指定してExcelファイルのみ表示されるようにしています。
- FilterIndexは指定無し
- Tilteに”Excelファイルを選択”を指定し、ダイアログボックスの上部に反映されていることがわかります。
注意しないといけないのは、ダイアログボックスでファイルを選択し、”開く”ボタンをクリックしてもGetOpenFilenameメソッドは選択したファイルのフルネームを返すだけで自動的には開かれません。
Excelファイルを開くには実例の11行目にあるようにWorkbooksコレクションのOpenメソッドを実行しましょう。
ワークブックを開く操作に関しては、前回の記事を参考にしてください。


GetOpenFilenameメソッドでダイアログボックスを表示したときカレントフォルダのファイルが表示されます。
実例の5行目でChDirステートメントを使って事前にカレントフォルダ指定して開きたいExcelファイルが存在するCドライブの直下が表示されるようにしています。
ChDir “C:\”
これをすることでGetOpenFilenameメソッドでダイアログボックスを表示した後にフォルダーの移動をする必要がなくなります。
GetOpenFilenameでExcelファイルを開く まとめ
今日はGetOpenFilenameメソッドでExcelファイルを開く方法を動画付きで解説しました。
次回はcsvファイルなどテキストファイルをGetOpenFilenameメソッドで開く方法を解説したいと思います。
VBA初級から抜け出すための知恵と、実務で活用できるスキルが学べる1冊です!激しくオススメ!


コメント