我有三个文件A.csv,B.xls和C.xls都在同一个目录中
我想从每个文件中取出最左边的7列,忽略顶部标题行,但是使用VBA将所有其他行放在一张(组合表单)中,并将它们放在彼此之下。
在Sheet1中,我已将文件名添加到单元格C3到C5中的文件,以及C1中的目录路径。
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
答案 0 :(得分:1)
你几乎拥有它,努力工作 - 只是一些语法问题。我重新构建了您的示例以提高效率,您可以使用F8逐步查看代码,看看它在做什么。
此外,根据您的示例,我假设您的数据中没有空白行,如果确实如此,则需要使用Range(“A”和Rows.Count)之类的内容。 (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