0

VB.net を使用して、Microsoft Word でトリガーされるイベントを処理するプログラムを作成しようとしています。私の最終的な目標は、このプログラムを使用して、Word がユーザーによって閉じられたときに応答することですが、DocumentBeforeCloseまたはDocumentBeforeSaveそれらを使用しようとすると、トリガーされないように見えますが、処理するイベントがあり、NewDocumentそれは正常に機能します。

これが私のコードです:

Imports Microsoft.Office.Interop

Public Class Form1

Private WithEvents oWord As Word.ApplicationClass
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Create a new instance of Word, make it visible, and activate it.
    oWord = CreateObject("Word.Application")
    oWord.Visible = True
    oWord.Activate()

    'Create a new document.
    oWord.Documents.Add()

    'Release the instance of Word and leave it running.
    oWord = Nothing

End Sub

Private Sub oWord_ApplicationEvents2_Event_DocumentBeforeClose(Doc As Word.Document, ByRef Cancel As Boolean) Handles oWord.ApplicationEvents2_Event_DocumentBeforeClose
    System.Windows.Forms.MessageBox.Show("The document is closing.")
End Sub


Private Sub oWord_ApplicationEvents2_Event_DocumentBeforeSave(Doc As Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles oWord.ApplicationEvents2_Event_DocumentBeforeSave
    System.Windows.Forms.MessageBox.Show("The document is saving.")
End Sub
'Handler for the Microsoft Word NewDocument event.
'The NewDocument event is fired when a new document is created.

Private Sub oWord_ApplicationEvents2_Event_NewDocument(Doc As Word.Document) Handles oWord.ApplicationEvents2_Event_NewDocument
    'Add some text to the new document.
    With oWord.Selection
        .TypeText("The ")
        With .Font
            .Bold = Word.WdConstants.wdToggle
            .Italic = Word.WdConstants.wdToggle
        End With
        .TypeText("NewDocument ")
        With .Font
            .Bold = Word.WdConstants.wdToggle
            .Italic = Word.WdConstants.wdToggle
        End With
        .TypeText("event handler inserted this text.")
    End With
End Sub
End Class

Microsoft Office Interop と Microsoft Word Object Library への参照があります。

.ApplicationEvents2_Event_DocumentBeforeClose Event に関するドキュメントを見つけましたが、コードから使用することを意図していないと述べていますが、宣言して使用する方法を提供しているため、間違った構文を使用しているか、間違った方法で使用しているかはわかりません一緒に。

4

1 に答える 1