【VBA】ブックを開く|OpenBook
作成日:2022-12-02
更新日:2025-10-04

指定ブックを開き、開いたブックのWorkBookオブジェクトを返す
' Open a workbook by path or File object
' パス文字列 または FSOのFileオブジェクトでブックを開く
Public Function OpenBook(ByVal file As Variant) As Workbook
Dim path As String
' 型判定(文字列 or Fileオブジェクト)
Select Case TypeName(file)
Case "String"
path = CStr(file)
Case "File"
path = file.Path
Case Else
Err.Raise vbObjectError + 1000, "OpenBook", _
"引数はファイルパス文字列かFSO.Fileを指定してください"
End Select
' 存在確認
If Dir(path, vbNormal) = "" Then
Err.Raise vbObjectError + 1001, "OpenBook", _
"指定ファイルが存在しません: " & path
End If
' 実際に開く
Set OpenBook = Workbooks.Open(path)
End FunctionTypeNameで引数の型をチェックErr.Raiseで発生箇所(Source)を"OpenBook"として明示Dirでファイル存在確認 → これで「ファイルなし」のケースに対応
Referenced Insights
- Microsoft Docs: Workbooks.Open method (Excel)
- Microsoft Docs: TypeName function (VBA)
| Variant|バリアント |
| TypeName|型名 |
| File Object|ファイルオブジェクト |
| Error Handling|エラーハンドリング |
| Workbook Open|ブックを開く |
Keep the function strict
in type checking
and safe in file handling.
in type checking
and safe in file handling.
2022-12-02
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[VBA]copyfile 【VBA】ブックを複製する|fso.CopyFile -

[VBA]Dirで存在確認 【VBA】フォルダとファイルの存在確認|FSOよりもDir -

[VBA]extract the filenamefrom a full path 【VBA】フルパスからファイル名と拡張子を取得する|fso.GetFileName/GetBaseName/GetExtensionName -

[VBA]Make Directory MkDir 【VBA】フォルダを作る|MkDir(フォルダがすでに存在していればエラーになる) -

[VBA]Resizerows and columns 【VBA】Resize changes the size of a cell range|範囲のリサイズ -

[VBA]Log WriterLet’s log this. 【VBA】ログをファイル出力するクラス|LogWriter