任务非常简单:
问题是当用户关闭文件时,仍然可以在任务管理器的进程选项卡上看到Excel对象。如果我在打开文件后立即写XlApp.quit()
,则用户将无法做任何事情。如何判断用户何时关闭Excel文件,以便运行代码以释放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)
答案 0 :(得分:1)
不久前我遇到过这个问题。我找到了解决方案,并根据您的问题进行了调整。请注意,我已在Excel中的VBA中完成此操作,因此您可能需要进行一些调整。我认为解决方案应该对你有用:
以下是允许用户编辑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 (i.e 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
祝你好运!
答案 1 :(得分:0)
您可以添加事件处理程序来检测close事件。 见https://support.microsoft.com/en-us/kb/822750