ワークブックのオブジェクトを取得

処理を行うにあたっては、適切なワークブックのオブジェクトを取得しておくことが大事です。

アクティブのワークブックは事前にアクティブになっている必要があります。正しくないワークブックがアクティブになっている場合は、正しく動作しなくなるので、注意が必要です。
ファイル名からワークブックを取得する際は、開いていないと処理できないので、注意が必要です。

別のワークブックを開いて処理する際は、Excelファイルを開いて閉じるを参照してください。

【サンプルプログラム】

Sub Sample()
    Dim wb As Workbook
    Dim wb_name As String
    Dim idx As Integer
    
    ' VBA マクロを実行しているワークブックを取得
    Set wb = ThisWorkbook
    Debug.Print "ThisWorkbook.Name : " & wb.name
    Debug.Print "ThisWorkbook.Path : " & wb.Path
    
    ' アクティブになっているワークブックを取得
    Set wb = ActiveWorkbook
    Debug.Print "ActiveWorkbook.Name : " & wb.name
    Debug.Print "ActiveWorkbook.Path : " & wb.Path
    
    ' 開かれているすべてのワークブックを取得
    For idx = 1 To Workbooks.Count
        Set wb = Workbooks(idx)
        Debug.Print "Workbooks(" & idx & ").Name : " & wb.name
        Debug.Print "Workbooks(" & idx & ").Path : " & wb.Path
    Next
    
    ' ファイル名からワークブックを取得(ファイルパスではないので注意)
    ' 開かれていないとエラーになるので確認してから取得する
    wb_name = "新規 Microsoft Excel ワークシート.xlsx"
    If IsWorkbookExists(wb_name) = True Then
        Set wb = Workbooks(wb_name)
        Debug.Print "ワークブック名を指定 : " & wb.name
        Debug.Print "ワークブック名を指定 : " & wb.Path
    Else
        Debug.Print "指定のワークブックが開かれていません : " & wb_name
    End If
End Sub

【ワークブックが開かれているかを確認する関数】

' ------------------------------------------------------------
' 説明:Workbooks に指定した名前のブックが存在するか確認
' 引数:1:ワークシートブック名
' 戻値:存在する場合はTrue、存在しない場合はFalse
' 備考:存在するかしないかは、現在ワークブックが開かれているかになる
' ------------------------------------------------------------
Function IsWorkbookExists(ByVal wb_name As String) As Boolean
    Dim wb As Workbook
    For Each wb In Workbooks
        ' 小文字に変換して確認する
        If LCase(wb_name) = LCase(wb.name) Then
            IsWorkbookExists = True ' 存在する
            Exit Function
        End If
    Next
    IsWorkbookExists = False    ' 存在しない
End Function

コメント