Pulling data from a closed workbook macro

前端 未结 1 1235
心在旅途
心在旅途 2020-12-06 14:26

I\'ve been having issues concerning pulling data from a closed workbook by using a macro.

\"enter

相关标签:
1条回答
  • 2020-12-06 15:17

    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").

    enter image description here

    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
    
    0 讨论(0)
提交回复
热议问题