【VBA】ブックに対する処理

VBA

ブックに対する処理


ブックのオープン

処理フロー

  • 同じフォルダにあるbook1.xlsxを開く
  • 開く前に以下のチェックをする
    1. ファイルが存在するか
    2. すでに開いていないか
  • 開いたブックをアクティブにしない
Sub BookOpen()

    Dim filePath As String
    Dim fileName As String
    Dim fullPath As String

    filePath = ThisWorkbook.Path
    fileName = "book1.xlsx"
    fullPath = filePath & "\" & fileName

    If Dir(fullPath) <> "" Then
        For Each wb In Workbooks
            If wb.Name = fileName Then
                MsgBox ("すでに開いています")
                Exit Sub
            End If
        Next wb

        Application.ScreenUpdating = False
        Workbooks.Open (fullPath)
        ThisWorkbook.Activate
        Application.ScreenUpdating = True

    Else
        MsgBox ("ファイルが存在しません")
    End If

End Sub

ブックの読み取り専用オープンとクローズ

同じディレクトリにあるファイル 参照先.xlsx を読み取り専用で開いて閉じる

Sub ReadOnlyOpen()

    Dim filePath As String
    Dim fileName As String
    Dim fullPath As String
    Dim workBook As workBook

    filePath = ThisWorkbook.Path
    fileName = "参照先.xlsx"
    fullPath = filePath & "\" & fileName

    Application.ScreenUpdating = False

    Workbooks.Open (fullPath), ReadOnly:=True, UpdateLinks:=0
    Set workBook = Workbooks.Open(fullPath)

    ThisWorkbook.Activate
    workBook.Close

    Application.ScreenUpdating = True

End Sub

ファイルを開かずに値を参照する

同じディレクトリにあるファイル 参照先.xlsx の値を参照する

  • 参照先の指定の仕方は ExecuteExcel4Macro("'ファイルパス[ファイル名]シート名'!セル番地")

処理フロー

  • 参照先.xlsx のセルA1の値を取得する
  • 取得した値をメッセージボックスで表示する
  • 取得した値をVBA実行ファイルのセルA1に転記する
Sub GetValue()

    Dim filePath As String
    Dim fileName As String
    Dim sheetName As String
    Dim targetPath As String

    filePath = ThisWorkbook.Path
    fileName = "参照先.xlsx"
    sheetName = "Sheet1"
    targetPath = "'" & filePath & "\[" & fileName & "]" & sheetName & "'!"

    MsgBox ExecuteExcel4Macro(targetPath & "R1C1")
    Cells(1, 1) = ExecuteExcel4Macro(targetPath & "R1C1")

End Sub

VBA

Posted by junichi