【问题标题】:VBA won't close workbooks opened programaticallyVBA 不会关闭以编程方式打开的工作簿
【发布时间】:2012-04-05 01:24:23
【问题描述】:

我在一个 Excel 电子表格中编写了一个 VBA 宏,它可以在特定位置打开所有工作簿,并从这些工作簿中提取数据并验证并将其复制到活动工作簿中。然后它会打开目录中的下一个工作簿并重复该过程,直到目录中的所有文件都已通读。

一切正常,除了我似乎无法让目标工作簿在打开后关闭。这包括关闭 Excel。我必须在任务管理器或 powershell 中终止进程才能从系统内存中释放工作簿。

Set fs = CreateObject("Scripting.FileSystemObject")
strExcelFileName = Dir(ThisWorkbook.Path & "\Certs\*.xls", vbNormal)
Set xlApp = CreateObject("Excel.Application")
Do While (strExcelFileName <> "")
      xlApp.Workbooks.Open (ThisWorkbook.Path & "\Certs\" + strExcelFileName)
      'code to run for each workbook opened
      ***xlApp.Workbooks.Close*** 'when present, Excel freezes
      strExcelFileName = Dir 'next file in directory
Loop

当 xlApp.Workbooks.Close 行存在并在程序中调用时,excel 每次都会冻结。没有它,我可以在系统不堪重负和死机之前运行 3-5 个工作簿。然后我必须终止这些进程,将这些文件移出,再移入 3 个并重复,直到所有文件都以这种方式处理。通关50个大概需要一个半小时。

我想做的是在打开下一个工作簿之前关闭从其中抓取数据的工作簿。

ActiveWorkbook.Close

这会尝试关闭正在运行宏的工作簿,而不是关闭已打开以供读取的工作簿。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您已打开 Excel,因此无需打开另一个副本。试试:

    Set WBookOther = Workbooks.Open(PathCrnt & FileNameCrnt)
      :
      :
    WBookOther.Close SaveChanges:=False
    

    这个earlier answer of mine 循环浏览当前文件夹中的每个工作簿可能会有所帮助。

    【讨论】:

      【解决方案2】:

      我运行您的代码没有任何问题,但这里有一个更简洁的替代方案:

      Dim strExcelFileName As String
      Dim xlApp As Object
      Dim wbk As Workbook
      
      strExcelFileName = Dir(ThisWorkbook.Path & "\Certs\*.xls", vbNormal)
      Set xlApp = CreateObject("Excel.Application")
      Do While (strExcelFileName <> "")
            Set wbk = xlApp.Workbooks.Open(ThisWorkbook.Path & "\Certs\" _
                + strExcelFileName) ' set a reference to the workbook you're opening
      
            'code to run for each workbook opened
            'Your code should use the "wbk" reference to make sure
            ' you're accessing the correct workbook.
      
            wbk.Close ' close the workbook using the reference you set earlier
      
            strExcelFileName = Dir 'next file in directory
      Loop
      

      【讨论】:

      • +1。我通常使用wbk.Close False 来避免提示未保存更改的任何问题
      • 这确实可以关闭每个工作簿并且不会占用我所有的系统内存,但它会挂起等待 OLE 操作完成并基本上冻结系统。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      相关资源
      最近更新 更多