Pulling data from a closed workbook macro

陌路散爱 提交于 2019-11-27 15:21:52

First off, do not stick the path into a cell that you plan on overwriting. Instead, create a separate sheet containing vital input parameters (see example below; I'm calling that sheet "System").

The code below pulls data from the workbooks "Raw Data 1" to "Raw Data 3" from the source book.

  • Make sure you properly define your workbooks in variables (TargetWb and SourceWb).
  • When referencing a worksheet, always specify what workbook it is located in when using multiple workbooks (e.g. TargetWb.ActiveWorksheet, not just ActiveWorksheet)

.

Sub PullClosedData()

    Dim filePath As String
    Dim SourceWb As Workbook
    Dim TargetWb As Workbook

    Set TargetWb = ActiveWorkbook

    filePath = TargetWb.Sheets("System").Range("A1").Value
    Set SourceWb = Workbooks.Open(filePath)

    For i = 1 To 3
        SourceWb.Sheets("Raw Data " & i).Range("A1:J5000").Copy Destination:=TargetWb.Sheets("Raw Data " & i).Range("A1:J5000")
    Next i

    SourceWb.Close

    MsgBox "All done!"

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!