ray88’s diary

お仕事で困ったとき用の自分用の覚書

他のブックの内容を取得する

Sub openLinkedBook()

    Dim wb As Workbook
    Dim targetPath As String
    
    '参照するブックのパスを設定
    targetPath = "C:\Users\デスクトップ\売上確定情報.xlsx"
    
    'リンクを更新せずにブックを開く
    '開こうとするブックに他のブックを参照する式があった場合のエラー対策
    Set wb = Workbooks.Open(fileName:=targetPath, UpdateLinks:=0)
    
    '1つ目のワークシーtのセルA1を参照する
    MsgBox wb.Worksheets(1).Range("A1").Value
    
    wb.Close
    Set wb = Nothing
    
End Sub

■応用編・フォルダ内の全てのファイルの特定のセルを参照する

Sub openBooks()
    Dim wb As Workbook
    Dim folderPath As String
    Dim targetPath As String
    Dim strFolderPath As String
    Dim strFileName As String
    
    '対象フォルダパスを指定
    strFolderPath = "C:\Users\デスクトップ\テスト"
    
    '参照するブックのパスを設定
    strFileName = Dir(strFolderPath & "\" & "*.xlsx")    
    
    Do While strFileName <> ""
        targetPath = strFolderPath & "\" & strFileName
        
        'リンクを更新せずにブックを開く
        '開こうとするブックに他のブックを参照する式があった場合のエラー対策
        Set wb = Workbooks.Open(fileName:=targetPath, UpdateLinks:=0)
        
        '1つ目のワークシーtのセルA1を参照する
        MsgBox wb.Worksheets(1).Range("A1").Value
    
        wb.Close
        Set wb = Nothing        
        strFileName = Dir()
    Loop
    
End Sub