我在一个文件夹中有超过1000个Excel文件。我想将每个文件中的第一行复制到另一个Excel文件中。我是怎么做到的?
为了说明,我想这样做:
File_1.xls: row 1 -> File_Master.xls: row 1
File_2.xls: row 1 -> File_Master.xls: row 2
File_3.xls: row 1 -> File_Master.xls: row 3
File_4.xls: row 1 -> File_Master.xls: row 4
.
.
.
File_1000.xls: row 1 -> File_Master.xls: row 1000
提前致谢!
答案 0 :(得分:1)
这应该有所帮助:
Sub FirstRow()
Application.DisplayAlerts = False
Dim strFilename As String
Dim strPath As String
Dim wbMaster As Workbook
Dim wsMaster As Worksheet
Dim wbFiles As Workbook
Dim i As Integer
i = 1
Set wbMaster = ThisWorkbook
Set wsMaster = wbMaster.Sheets(2)
strPath = "C:\path\to\your\files\"
strFilename = Dir(strPath & "*.xls")
Do While strFilename <> ""
Set wbFiles = Workbooks.Open(strPath & strFilename, False)
wbFiles.Sheets(1).Rows(RowIndex:=1).Copy
wsMaster.Cells(RowIndex:=i, ColumnIndex:=1).PasteSpecial Paste:=xlPasteAll
wbFiles.Close (False)
strFilename = Dir
i = i + 1
Loop
Application.DisplayAlerts = True
End Sub
有几点需要注意:
- 您需要根据需要将Sheet(x)
引用更改为适当的值
- 当你放入自己的路径时,确保strPath末尾有一个“\”
- 我在执行期间将DisplayAlerts
设置为false,以避免在每个文件上弹出一个询问您是否要清除剪贴板的文件。