Document_New event on launching Word

有些话、适合烂在心里 提交于 2020-03-03 08:13:15

问题


I have a VBA addin which I want to run every time someone opens a document. It's working fine for opening existing documents (AutoOpen) and creating new documents from the File > New menu (AutoNew) but when I just open Word up for the first time, neither of these events are firing. The only event I can seem to hook into is the AutoExec event and this is not great as the document doesn't exist yet so ActiveWindow is null.

Can anyone help?

Sub AutoNew
    MsgBox "New"
End Sub

Sub AutoOpen
    MsgBox "Open"
End Sub

Sub AutoExec
    MsgBox "Exec"
End Sub

回答1:


I would start with DocumentOpen and NewDocument. An additional level of complexity exists if you need to support ProtectedView documents; Word triggers a different event. I've found that if I try to check for that event (and it doesn't occur) it raises an error. I didn't had much luck and eventually it wasn't worth the time I was spending. I've posted an example below of some code that opens the Style Pane when a document is opened or a new one created (assuming the add-in is loading) and expands the style margin in draft view if not already expanded.

In my UI module:

Dim X As New clsAppEvent 'This is in the declarations

Public Sub OnRibbonLoad(objRibbon As IRibbonUI)
    Do While Documents.Count = 0
      DoEvents
    Loop ' I find this useful as sometimes it seems my ribbon loads before the document. 
    Call Register_Event_Handler
    ' Other stuff
End Sub

Private Sub Register_Event_Handler()
    Set X.App = Word.Application
End Sub

Then, in a class module I call clsAppEvent:

Option Explicit

Public WithEvents App As Word.Application

Private Sub App_DocumentOpen(ByVal Doc As Document)
    App.TaskPanes(wdTaskPaneFormatting).visible = True
End Sub

Private Sub App_NewDocument(ByVal Doc As Document)
    App.TaskPanes(wdTaskPaneFormatting).visible = True
End Sub

Private Sub App_WindowActivate(ByVal Doc As Document, ByVal Wn As Window)
    If Wn.StyleAreaWidth <= 0 Then
      Wn.StyleAreaWidth = 60
    End If
End Sub

Other than the caveats I've noted above, the one problem I've had is if a user has Auto code in their Normal template as well. This has only come up once so I haven't investigated it.

I wish I could find the site where I learned about this (and from which the Register_Event_Handler was derived. If I find it I'll add a comment.



来源:https://stackoverflow.com/questions/15070492/document-new-event-on-launching-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!