从多个Excel文件(动态范围)复制并粘贴到主工作表(动态范围)

时间:2014-01-04 21:57:36

标签: excel vba excel-vba dynamic range

你能帮我解决一下这段代码吗?我想将数据从多个文件传输到一个主表。我在最后但在代码的一行

中收到错误
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

1 个答案:

答案 0 :(得分:0)

尝试注释掉或删除显示的行:

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

此外,当您将目标范围Cells(erow,1)设置为其值(空白)而不是其地址时。所以将该行更改为:

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