从excel VBA关闭OneNote应用程序

时间:2013-09-10 12:12:38

标签: vba excel-vba onenote excel

我正试图用这段代码从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支持自动化的应用程序。如下面的链接所示,页面底部的表格列出了我可以引用的所有顶级Office对象及其类名,OneNote不在其中:

Creation of Object Variables to Automate Another Office Application

关于如何关闭应用程序的任何想法,建议(不是笔记本本身,只有运行的应用程序..)

由于

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

OneNote应用程序界面(记录为here)没有Quit方法。这就是为什么它不起作用的原因。你可以做的是关闭OneNote窗口,这有点棘手。以下是一些说明和示例代码:

  • 获取OneNote窗口句柄:应用程序对象有一个CurrentWindow成员,然后成员WindowHandle成为HWND成员当前的OneNote窗口。

  • 获取顶级窗口:此句柄通常是OneNote窗口的子窗口,因此您需要使用GetAncestor调用GA_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对象执行此操作。