自分用メモ(VBA ファイル読み込み)

注意事項

概要

後で自分がコピペする用のメモ。
VBAでエクセルファイルを読み込む関数。

環境:
 Excel for Mac 16.16.24
 VBA 7.1

Sub OpenTest()

  Dim filePath As String, fileName As String
  filePath = "/XXX/YYY/ZZZ/"
  fileName = "XXXXXXXXX.xlsx"

  Dim readBook As Workbook
  Dim mainBook As Workbook
  Set mainBook = ActiveWorkbook '今のアクティブウインドウを記録

  'ファイルの存在確認
  Dim exists As String
  exists = Dir(filePath & fileName)
  If exists = "" Then
    MsgBox "ファイルが存在しません : " & fileName & vbCrLf & filePath, vbExclamation
    Exit Sub
  End If

  '既に開いているかチェック
  Dim tmpWB As Workbook
  For Each tmpWB In Workbooks

    Dim compResult As Integer
    compResult = StrComp(tmpWB.Name, exists, vbTextCompare)
    If compResult = 0 Then
      MsgBox "既に開いています : " & exists, vbExclamation
      Exit Sub
    End If
  Next tmpWB

  'ファイルを開く
  Application.ScreenUpdating = False '画面更新を止める
  Set readBook = Workbooks.Open(filePath & fileName, ReadOnly:=True)
  ActiveWindow.Visible = False '非表示にする
  mainBook.Activate 
  ActiveWindow.Visible = True
  Application.ScreenUpdating = True

  'ファイルを閉じる
  Application.DisplayAlerts = False 
  readBook.Close
  Application.DisplayAlerts = True

End Sub