簡單粗暴-將多個excel彙總的一個excel的不同sheet
阿新 • • 發佈:2020-11-18
將待合併的excel放到同一目錄,右鍵sheet檢視程式碼,插入如下程式碼(不用新建excel再插入)
Sub Books2Sheets() '定義對話方塊變數 Dim fd As FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) '新建一個工作簿 Dim newwb As Workbook Set newwb = Workbooks.Add With fd If .Show = -1 Then '定義單個檔案變數 Dim vrtSelectedItem As Variant '定義迴圈變數 Dimi As Integer i = 1 '開始檔案檢索 For Each vrtSelectedItem In .SelectedItems '開啟被合併工作簿 Dim tempwb As Workbook Set tempwb = Workbooks.Open(vrtSelectedItem) '複製工作表 tempwb.Worksheets(1).Copy Before:=newwb.Worksheets(i) '把新工作簿的工作表名字改成被複制工作簿檔名,這兒應用於xls檔案,即Excel97-2003的檔案,如果是Excel2007,需要改成xlsx newwb.Worksheets(i).Name = VBA.Replace(tempwb.Name, ".xlsx", "") '關閉被合併工作簿 tempwb.Close SaveChanges:=False i = i + 1 Next vrtSelectedItem End If End With Set fd = Nothing MsgBox "已將多個檔案合併完畢!", vbInformation, "提示" End Sub
參考https://jingyan.baidu.com/article/6181c3e0bd6274152ef1531e.html