Consulting

Results 1 to 2 of 2

Thread: Excel 2013 VBA Import Dynamic Range from other Workbook

  1. #1
    VBAX Newbie
    Joined
    Jun 2016
    Posts
    1
    Location

    Excel 2013 VBA Import Dynamic Range from other Workbook

    Hi everybody!
    I am trying to import data from one workbook to another using the code below, but it returns the message "Run-time error `1004`: Application-defined or object-defined error".
    The number of columns is always the same and the rows can vary.

    Sub DATA()
    Dim Target_Workbook As Workbook
    Dim Source_Workbook As Workbook
    Dim LastRow As Long
    Dim StartCell As Range
    Dim LastCell As Range
    Target_Path = "C:\database.xls"
    Set Target_Workbook = Workbooks.Open(Target_Path)
    Set Source_Workbook = ThisWorkbook
    Set StartCell = Range("A2")
    LastRow = Target_Workbook.Sheets(1).Cells(Rows.Count, StartCell.Column).End(xlUp).Row - 1
    Target_data = Target_Workbook.Sheets(1).Range(Cells(2, 1), Cells(LastRow, 12))
    Source_Workbook.Sheets("MyData").Range(Cells(2, 1), Cells(LastRow, 12)) = Target_data
    Source_Workbook.Save
    Target_Workbook.Save
    Target_Workbook.Close False
    MsgBox "Task Completed"
    End Sub

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    I find your Source and Target confusing, I'm not sure if this is the right way round.
    Try
    Option Explicit
    
    
    Sub DATA()
        Dim Source_Workbook As Workbook
        Dim Source_Path As String
        Dim Target As Range, Source As Range
        
        Set Target = ThisWorkbook.Sheets(1).Cells(2, 1)
        
        Source_Path = "C:\database.xls"
        Set Source_Workbook = Workbooks.Open(Source_Path)
        With Source_Workbook.Sheets(1)
            Set Source = Range(.Cells(2, 1), .Cells(Rows.Count, 12).End(xlUp))
        End With
    
        Target.Resize(Source.Rows.Count, Source.Columns.Count).Value = Source.Value
        
        Source_Workbook.Close False
        ThisWorkbook.Close True
        MsgBox "Task Completed"
    End Sub
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •