用户完成后closuresExcel

任务非常简单:

  1. 我想从VB.net GUI打开一个Excel文档(.xls)
  2. 用户将在Excel文件上工作
  3. 用户在完成时closuresExcel文件
  4. 我想要VB.net代码释放Excel对象

问题是,当用户closures文件时,Excel对象仍然可以在任务pipe理器的进程选项卡上看到。 如果我打开文件后立即写XlApp.quit() ,用户将无法做任何事情。 如何知道用户何时closuresExcel文件,以便我可以运行代码来释放Excel对象?

我到目前为止:

 Dim xlapp as new Excel.Application Dim xlwb as excel.workbook = xlapp.workbooks.open("file path") xlapp.visible = true 'The user do work here' 'What should I put in between here to detect when the user exits the excel file???" xlwb.close() xlapp.quit() releaseObject(xlwb) releaseObject(xlApp) 

不久之前我就遇到了这个问题。 我发现我的解决scheme,并适应您的问题。 请注意,我已经在Excel中使用了VBA,所以也许你需要做一些调整。 我认为,解决scheme应该为你工作:

这里是让用户编辑excel文件的代码:

 Dim xlapp as new Excel.Application Dim xlwb as excel.workbook = xlapp.workbooks.open("T:\tmp\Book1.xlsx") xlapp.visible = true 'Loop until the Excel file is closed. 'I though I had to check if the user closed Excel and not just the excel-file, 'but it seems that Excel does not close even if the user does "Exit Excel". Do Sleep 1000 'Keep on looping as long as the Excel-file is part of the open workbooks. Loop While objExist(xlApp.Workbooks,"Book1.xlsx") 'xlwb.Close You can't run this command, as the workbook is already closed xlapp.Quit releaseObject (xlwb) releaseObject (xlapp) 

为了能够在VBA中使用Sleep,我需要在模块的开头声明它:

 Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 

这是我objExist的代码:

 Public Function ObjExist(objCollection As Variant, iname As String) As Boolean '------------------------------------------------------------ 'Purpose Tell if a named element is part of a collection 'Expects obCollection A collection of objects (ie Worksheets, Tables) ' iname The name of the object that we want to look for 'Returns True if the named object exists in the collection, otherwise False. ' Note that it returns FALSE also if any other error occurs, like ' the objCollection not being a collection. '------------------------------------------------------------ Dim a As Object On Error GoTo DoesNotExist Set a = objCollection(iname) ObjExist = True Set a = Nothing Exit Function DoesNotExist: ObjExist = False End Function 

祝你好运!

您可以添加事件处理程序来检测closures事件。 看到这里https://support.microsoft.com/en-us/kb/822750