【问题标题】:Closing OneNote Application from excel VBA从 excel VBA 关闭 OneNote 应用程序
【发布时间】:2014-02-22 14:17:23
【问题描述】:

我正在尝试使用这段代码从 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 不在其中:

Creation of Object Variables to Automate Another Office Application

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

谢谢

【问题讨论】:

  • 你试过摆脱On Error Resume Next你也许可以调试这个...
  • 给出错误 429:ActiveX 组件无法创建对象或返回对此对象的引用。这是否意味着 OneNote 是我无法引用的 Office 对象?
  • 哪一行会引发错误? GetObject.Quit?
  • .GetObject 引发错误
  • 使用CreateObject 获取OneNote 应用程序,或将其标注为对象变量并使用CreateObject 或Dim as New` 方法。 Quit 仍然会失败。根本不支持。

标签: vba excel onenote


【解决方案1】:

【讨论】:

  • 这提供了有关如何关闭笔记本的信息,这不是我需要知道的。我需要让笔记本保持打开状态,但只需要关闭应用程序 OneNote。
  • Notebooks 属于 OneNote。关闭 OneNote 应用程序时,您不能让笔记本保持打开状态。这就像询问如何在关闭 Excel.Application 时打开Workbook。这是不可能的。我认为这个答案有你需要的信息。否则,请尝试启用对 OneNote 库的引用并使用智能感知来帮助您完成。当您对代码按预期工作感到满意时,您始终可以恢复为后期绑定方法。
  • 我知道这听起来很奇怪,但 OneNote 允许让笔记本保持打开和关闭应用程序。当用户重新打开 OneNote 时,他会发现他所有的笔记本都打开了。如果我在代码中使用oneNote.CloseNotebook notebookID,它将正常关闭笔记本,但不会关闭 OneNote 应用程序。在那行代码之后,用户在 OneNote 上加注,没有打开笔记本。..
【解决方案2】:

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

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

  • 获取顶层窗口:此句柄通常是 OneNote 窗口的子窗口,因此您需要调用 GetAncestorGA_ROOT 以获取顶层窗口 p>

  • 关闭窗口:您可以发送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 对象执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多