簡體   English   中英

從Excel VBA關閉OneNote應用程序

[英]Closing OneNote Application from excel VBA

我正在嘗試使用以下代碼從VBA excel中關閉OneNote應用程序:

Sub closeOneNote()
                Dim oneNoteApp As Object
                On Error Resume Next
                Set oneNoteApp = GetObject(, "OneNote.Application")
                If Err.Number = 0 Then
                oneNoteApp.Quit
                Else
                Err.Clear
                End If
End Sub

當我嘗試使用Outlook而不是OneNote時,它可以正常工作,並且Outlook關閉。 我想知道是否是因為OneNote不是支持通過VBA自動化的應用程序。 如下面的鏈接所示,頁面底部的表列出了Ican可以引用的所有頂級Office對象及其類名,而OneNote不在其中:

創建對象變量以自動化另一個Office應用程序

關於如何關閉應用程序的任何想法和建議(不是筆記本本身,僅是運行中的應用程序。)

謝謝

OneNote應用程序接口( 在此處記錄 )沒有Quit方法。 這就是為什么它不起作用的原因。 相反,您可以做的是關閉OneNote窗口,這有些棘手。 以下是一些說明和示例代碼:

  • 獲取OneNote窗口句柄:應用程序對象具有CurrentWindow成員,然后該成員具有一個WindowHandle成員,該成員是當前OneNote窗口的HWND

  • 獲取頂級窗口:此句柄通常是OneNote的窗口的子窗口,所以你需要調用GetAncestorGA_ROOT得到頂層窗口

  • 關閉窗口:您可以將WM_CLOSE發送到頂層窗口以將其關閉。 當然,如果它正在顯示對話框或以其他方式忙碌,則它可能不會對此做出響應。

     Option Explicit Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Private Declare PtrSafe Function GetAncestor Lib "user32.dll" _ (ByVal hwnd As Long, ByVal gaFlags As Long) As Long Private Const GA_ROOT As Long = 2 Private Const WM_CLOSE = &H10 Sub test() ' Create Application Object Dim app As Object Set app = CreateObject("OneNote.Application") ' Get the window handle Dim hwnd As Long hwnd = app.Windows.CurrentWindow.WindowHandle ' Get the top level window Dim hwndRoot As Long hwndRoot = GetAncestor(hwnd, GA_ROOT) ' Close it PostMessage hwndRoot, WM_CLOSE, 0&, 0& End Sub 

如果周圍有多個OneNote窗口,這還不夠。 在這種情況下,您可以枚舉Windows集合並對其中的每個Window對象執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM