正在关闭 Excel Window 正在打开 VBA

Closing Excel Window that's open VBA

我有检查 excel 文件是否存在的代码。如果文件已经存在,那么我想附加到文档中。但是用户可能已经在前台打开了 excel 文件。我怎样才能关闭那个 excel 文件 window? (这相当于在 excel 文件的 window 中点击 x)

我试过以下方法:

XLName = "excel2close.xlxs"
'Set oxlApp = CreateObject("Excel.Application") 'EDIT: Not correct
'Set oxlApp = GetObject(", Excel.Application")  'EDIT: Syntax error
'Set oxlApp = GetObject(XLName, Excel.Application)  'EDIT: Error 
'429': ActiveX component can't create object

Set oxlApp = GetObject(XLName, "Excel.Application") 'EDIT: Error
'432': File name or class name not found during Automation operation

'Returns Run-time error '9': Subscript out of range
oxlApp.Workbooks(XLName).Close SaveChanges:=False

'Run-time error '438': Object doesn't support this property method
oxlApp.Workbook(XLName).Close

'Run-time error '438': Object doesn't support this property method
oxlApp.Window(XLName).Close

'Returns Run-time error '9': Subscript out of range
oxlApp.Windows(XLName).Close

我也用完整路径尝试了所有这些,而不仅仅是名称。

请测试下一段代码并尝试理解它:

Sub ExcelSessions()
   Dim XLName As String, oxlApp As Object, wb As Workbook, wbOp As Workbook
   XLName = "excel2close.xlsx" 'be careful, you used an inexisting extension (xlxs)...
   
   On Error Resume Next
    Set oxlApp = GetObject(, "Excel.Application") 'if an existing open session exists, it will be set in this way
    If err.Number <> 0 Then   'If no open session exists:
        err.Clear: On Error GoTo 0
        Set oxlApp = CreateObject("Excel.Application") 'create a new session
    Else                      'If an existing session could be set, check if the necessary workbook exists:
        For Each wb In oxlApp.Workbooks
            If wb.Name = XLName Then Set wbOp = wb: Exit For 'Only if it exists, it is set
        Next
    End If
  On Error GoTo 0
  If Not wbOp Is Nothing Then  'if the necessary workbook has been found:
       wbOp.Close              'it is closed
  Else
        MsgBox "No document named """ & XLName & """ exists in the found open session."
  End If
End Sub

现在,GetObject 将设置第一个找到的会话。但是如果存在多个session,可能在找到的open session中找不到您搜索的工作簿...

在这种情况下,有两种选择可供探索:

  1. 如果您确定该工作簿已打开并且您知道它的完整路径,您可以在下一次获取必要的会话方式:
Sub getExcelSessByWbFullName()
   Dim XLName As String, oxlApp As Object, wb As Workbook
    
     XLName = "full name of  excel2close.xlsx" '"C:\yourFolder\excel2close.xlsx"
    Set oxlApp = GetObject(XLName).Application
    oxlApp.Workbooks(Right(XLName, InStrRev(XLName, "\"))).Close
    'oxlApp.Quit 'if you want quiting the session you must uncomment this line
End Sub
  1. 如果你只认为它可能是开放的,而且 许多会话可能是开放的我可以告诉你一个更复杂的方法来找到所有开放的会话并检查每个会话是否搜索到的工作簿已打开。如果打开,请关闭它(如果需要,也可以关闭会话)。但是我会 post 在你测试之前的代码并证明你理解他们在做什么之后......