通过PID关闭新创建的Excel对象


问题背景

在Outlook中操作Excel,在Createbject后,进行对Excel的操作。用完之后有的时候set nothing到彻底关闭进程会有延迟。导致下次操作要花费一定的等待时间。 解决思路是,根据PID强制关闭进程。示例代码如下:

Public Declare Function GetWindowThreadProcessId Lib "user32" _
  (ByVal hwnd As Long, _
   ByRef lpdwProcessId As Long) As Long

Function KillProcess(hwnd As Long)
  Dim CurrentForegroundThreadID As Long
  Dim strComputer As String
  Dim objWMIService
  Dim colProcessList
  Dim objProcess
  Dim ProcIdXL As Long

  ProcIdXL = 0
  CurrentForegroundThreadID = GetWindowThreadProcessId(hwnd, ProcIdXL)

  strComputer = "."

  Set objWMIService = GetObject _
  ("winmgmts:\\" & strComputer & "\root\cimv2")
  Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where ProcessID =" & ProcIdXL)
  For Each objProcess In colProcessList
    objProcess.Terminate
  Next

End Function


Sub Test()
Set app = CreateObject("Excel.Application")
Set wb = app.Workbooks.Open("C:\Users\Tango\Desktop\0727\B.xlsx")
MsgBox wb.Name
KillProcess (app.hwnd)
End Sub