简体   繁体   中英

Copy from Multiple Excel Files (dynamic ranges) and Paste in master Sheet (Dynamic range)

Can you please hep me with this code. I want to transfer data from multiple files to one master sheet. I am getting error in last but one line of the code

Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\Users\Nadeem\Desktop\2013\2G\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then      'zmaster is the master file in same folder
Exit Sub
End If

Workbooks.Open (Filepath & MyFile)
Range("A2").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Copy   'Copy Dynamic range
'ActiveWorkbook.Application.CutCopyMode = False
'ActiveWorkbook.Close SaveChanges:=False

Application.Workbooks("zmaster.xlsm").Worksheets("Sheet1").Activate 'Added this line
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row   'Paste in Dynamic Range
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1).Address)

MyFile = Dir

Loop
End Sub

Try commenting out or deleting the line shown:

Workbooks.Open (Filepath & MyFile)
Range("A2").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Copy   'Copy Dynamic range
'ActiveWorkbook.Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=False

Also, when you set the destination range Cells(erow,1) evaluates to its value (which is blank) instead of its address. So change that line to:

ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1).Address)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM