结合来自不同文件的三个数据集

我有三个文件A.csv,B.xls和C.xls都在同一个目录中

我想从每个文件中取7个最左边的列,忽略顶部标题行,但采用所有其他行,并使用VBA将它们放在一个工作表(组合工作表)中。

在Sheet1中,我已经将文件名添加到单元格C3到C5中的文件以及C1中的目录path。

activeworkbook的名字是Book2.xlsm

下面是我迄今使用的代码来尝试和实现这一点:

Sub combineSheets() Dim directory As String, fileName As String Dim fileRng As Range Dim fileCell As Range directory = Sheet1.Range("C1").Value Set fileRng As Sheets("Sheet1").Range("C3") Set fileRng As Range(fileRng,fileRng.End(xlDown)) For Each fileCell in fileRng fileName = fileCell.Value 'Application.DisplayAlerts = False Workbooks.Open (directory & fileName) Workbooks(fileName).Select Sheet1.Select Range("A2").Select Range(Selection, Selection.Offset(Selection.End(xlDown).Row - 2, 7)).Select 'need code to work out how to add on the bottom Selection.Copy Destination:=Workbooks("Book2.xlsm").Sheets("combined").Range("A2") 'Application.DisplayAlerts = True Next Workbooks("Book2.xlsm").Sheet1.Select End Sub 

你几乎已经有了,努力 – 只是几个语法问题。 我已经重新构build了您的示例以提高效率,您可以使用F8逐步查看代码,看看它在做什么。

此外,基于你的例子,我假设你的数据没有空白行,如果它的确需要使用Range(“A”&Rows.Count).End(xlUp) 。

试试这个:(附加一些笔记)

 Sub combineSheets() Dim fileName As Range '// Use 'As' to dimension (Dim) something, use '=' to Set something. Dim WB As Workbook Set WB = ActiveWorkbook '// Loop through the filenames For Each fileName In Range("C3", Range("C3").End(xlDown)).Cells '// Open workbook with value in C1 and filename Workbooks.Open Range("C1").Value & fileName.Value '// Copy to first workbook With ActiveWorkbook.Sheet1 .Range("A2", .Range("A2").End(xlDown).Offset(-2, 7)).Copy Destination:= _ WB.Sheets("combined").Range("A2").End(xlDown).Offset(1, 0) End With '// Copy finished so close workbook ActiveWorkbook.Close False '// Go to next filename Next fileName '// Re-activate first workbook WB.Activate '// Release WB object from memory (note the '=') Set WB = Nothing End Sub