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

时间:2017-09-06 18:46:57

标签: excel ms-access access-vba

我看到了如何使用

执行此操作的版本
Dim ran as Excel.Applcation 

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

我编写了以下运行的代码,但没有关闭文件

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

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码关闭所有Excel文件(已发布here):     

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

但如果我们要关闭一个特定的一个,我们需要一些我无法做到的Win32魔法,但是,如果你不能做某事,你可以在StackOverflow上找到它。 Florent B的大多数代码都找到here

首先,声明我们的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

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

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

然后,实现该关闭功能

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