文件合並示例代碼:
要求:在C盤中有一個文件夾,文件夾中有文件存在
Sub wjhb() Dim str As String Dim wb As Workbook str = Dir("c:\data\*.*") For i = 1 To 20 ' 1 打開文件 Set wb = Workbooks.Open("c:\data\" & str & "") ' 2 從遍歷中的某一個工作簿中的第一張表執行拷貝 到這個工作簿中的最后一張表中去 wb.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) ' 3 在這個工作簿中的最后一張表的名字是【已經完成拷貝操作】 = 文件名稱 ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Split(str, ".")(0) '4 遍歷中的工作簿執行關閉 wb.Close '下一次遍歷 str = Dir If str = "" Then Exit For End If Next End Sub
End Sub Sub wjhb2() Dim str As String Dim wb As Workbook str = Dir("c:\data\*.xlsx") For i = 1 To 20 Set wb = Workbooks.Open("c:\data\" & str & "") wb.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = str wb.Close str = Dir If str = "" Then Exit For End If Next End Sub