将Excel工作表导入现有的Excel文件除了一件事情

我想从一个不同的Excel文件导入一些工作表到一个目标文件,并使用VBAbutton将这些工作表添加到其他工作表之后。 我一直在寻找一些东西,这最接近解决scheme。 然而,还有一个问题依赖于我如何在一个特定的路线(比较评论)。

Private Sub Importer_Click() Dim directory As String Dim import As String Dim curr_file As String Dim source As Workbook Dim sheet As Worksheet Dim total As Integer Application.ScreenUpdating = False Application.DisplayAlerts = False directory = "C:\Users\...\" import = Dir(directory & "*.xl??") curr_file = ActiveWorkbook.Name Do While import <> "" Set source = Workbooks.Open(directory & import) For Each sheet In source.Sheets total = Workbooks(curr_file).Worksheets.Count sheet.Copy After:=Workbooks(curr_file).Sheets(total) Next sheet Workbooks(import).Close ' alternative 1: works smooth, files close, but sheets are not added Workbooks(directory & import).close ' alternative 2: sheets are added, but importing files remain open (because the 'directory' is not needed in fact) + I get a runtime error 9 (subscript out of range) import = Dir() Loop Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub 

我想答案很简单(我对VBA比较新)。 谁可以帮忙?

谢谢!

您打开它时,将工作簿对象设置为工作簿。 使用这个明确的对象引用closures它并指定应该保存更改。

 source.Close SaveChanges:=True