VBA将数据从多个工作簿复制到Mastercopy Excel

时间:2019-03-07 14:05:13

标签: excel vba

我想从文件夹(包含相同的标题和布局)中的不同工作簿中提取数据(列A:I)到Mastercopy excel。

我的代码可以运行,但是它仅从不同工作簿的A:E复制数据。 这些工作簿中的每一个只有3行数据(行1:时间戳记A:E,行2:实际标题A:I,行3:要提取的实际值)。我怀疑它的第1行引起了问题,因为它只有A:E中的数据。关于如何克服这个问题的任何想法吗?任何建议都非常感谢。

Sub copyDataFromMultipleWorkbooksIntoMaster()

Dim FolderPath As String, Filepath As String, Filename As String

FolderPath = "C:\Users\AlexP\Desktop\Folder\Downloads\"

Filepath = FolderPath & "*.csv"

Filename = Dir(Filepath)

Dim lastrow As Long, lastcolumn As Long

Dim erow

Do While Filename <> ""
Workbooks.Open (FolderPath & Filename)

lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

Range(Cells(3, 1), Cells(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close

erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 9))

Filename = Dir

Loop

End Sub

1 个答案:

答案 0 :(得分:0)

如果您知道要从中提取数据的每个工作簿都使用A列到I列,那么将您的复制行更改为Range(Cells(3, 1), Cells(lastrow, 9)).Copy,这样就可以使它起作用。它不会那么有弹性,但是会起作用。

要使其具有弹性,请确保每个工作表在每一列的第一个单元格中都有内容,然后可以返回使用Columns.Count来定义复制的范围。