2017-03-03 70 views
0

我想从一个不同的Excel文件导入一些工作表到目标文件并使用VBA按钮将这些工作表附加到其他工作表之后。我一直在研究一些事情,这最接近解决方案。然而,仍然存在一个问题,这取决于我如何放入一个特定的线路(参见评论)。将Excel工作表导入到现有的Excel文件中除了一件工作

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)。谁可以帮忙?

谢谢!

+0

也许'source.Close的SaveChanges:= TRUE; ...? – Jeeped

回答

1

您在打开工作簿时将工作簿对象设置为工作簿。使用此权威对象引用关闭它并指定应保存更改。

source.Close SaveChanges:=True 
+0

感谢您的回复。不幸的是,这并没有成功。没有新事发生。 curr_file是通过导入Excel工作表的文件以及源文件/工作簿来提取工作表的方式。任何其他建议什么可能是错的?我添加了消息框来检查变量:工作表名称,以及Excel文件和新工作表的总数似乎更新得很好。 – sborms

相关问题