closures用户从Access-VBA打开的特定Excel文件

我看到如何做到这一点的版本

Dim ran as Excel.Applcation 

但是我使用的Access版本没有Excel.Application作为选项。

我写了下面的代码运行,但不closures文件

 Dim Path1 as String Dim objXL As Object Dim xlWB As Object Path1 = "C:/....." Set objXL = CreateObject("Excel.Application") Set xlWB = objXL.Workbooks.Open(Path1) xlWB.Close False Set xlWB = Nothing objXL.Quit Set objXL = Nothing 

您可以使用下面的代码来closures所有的Excel文件( 这里已经发布):

 Public Sub CloseAllExcel() Dim obj As Object On Error GoTo ExitSub Dim i As Integer 'There shouldn't be more than 10000 running Excel applications 'Can use While True too, but small risk of infinite loop For i = 0 To 10000 Set obj = GetObject(, "Excel.Application") obj.Quit Next i ExitSub: End Sub 

但是如果我们要closures一个特定的,我们需要一些我不能做的Win32魔法,但是,如果你不能做什么,你可以在StackOverflow上find它。 Florent B的大部分代码都在这里find

首先,声明我们的Win32函数

 #If VBA7 Then Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" ( _ ByVal hwnd As LongPtr, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long Private Declare PtrSafe Function FindWindowExA Lib "user32" ( _ ByVal hwndParent As LongPtr, ByVal hwndChildAfter As LongPtr, _ ByVal lpszClass As String, ByVal lpszWindow As String) As LongPtr #Else Private Declare Function AccessibleObjectFromWindow Lib "oleacc" ( _ ByVal hwnd As Long, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long Private Declare Function FindWindowExA Lib "user32" ( _ ByVal hwndParent As Long, ByVal hwndChildAfter As Long, _ ByVal lpszClass As String, ByVal lpszWindow As String) As Long #End If 

然后使用它们获取所有正在运行的Excel应用程序对象

 Public Function GetExcelInstances() As Collection Dim guid&(0 To 3), acc As Object, hwnd, hwnd2, hwnd3 guid(0) = &H20400 guid(1) = &H0 guid(2) = &HC0 guid(3) = &H46000000 Set GetExcelInstances = New Collection Do hwnd = FindWindowExA(0, hwnd, "XLMAIN", vbNullString) If hwnd = 0 Then Exit Do hwnd2 = FindWindowExA(hwnd, 0, "XLDESK", vbNullString) hwnd3 = FindWindowExA(hwnd2, 0, "EXCEL7", vbNullString) If AccessibleObjectFromWindow(hwnd3, &HFFFFFFF0, guid(0), acc) = 0 Then GetExcelInstances.Add acc.Application End If Loop End Function 

然后使用该集合,以便我们可以检查哪个工作簿已打开,然后closures它

 Public Sub closeWorkbook(workbookPath As String) Dim excelInstances As Collection Set excelInstances = GetExcelInstances Dim excelApp As Object Dim excelWorkbook As Object For Each excelApp In excelInstances For Each excelWorkbook In excelApp.Workbooks If excelWorkbook.FullName = workbookPath Then excelWorkbook.Close False End If Next excelWorkbook If excelApp.Workbooks.Count = 0 Then excelApp.Quit End If Next excelApp End Sub 

然后,执行那个closuresfunction

 Dim Path1 as String Path1 = "C:/....." closeWorkbook Path1