PDA

View Full Version : Excel 2013 VBA Import Dynamic Range from other Workbook



guyveio
06-02-2016, 09:06 AM
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

mdmackillop
06-02-2016, 11:04 AM
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