首页 > 解决方案 > 如何在 VB.Net 中的 Application.word 上使用 DocumentBeforeClose 事件

问题描述

我通过以下代码在 VB.Net 中打开 Word 应用程序:

Dim appWord As New Microsoft.Office.Interop.Word.Application
appWord.Documents.Open("path")
appWord.Visible = True

我想订阅 msword 的关闭事件并在关闭之前运行一些东西。我读了这个问题和这篇文章,但我真的不知道如何在 VB.Net 中使用

标签: vb.netms-word

解决方案


添加对 Microsoft Word XX.0 对象库的引用(项目--引用...)。

如果您的 MS Office 是 2016,XX 取决于您的 MS Office 版本,即 16.0。

在窗体中添加一个名为 Command1 的命令按钮。将此代码添加到表单中:

Option Explicit

Public WithEvents moWord As Word.Application

Private Sub Command1_Click()
    ' open test document
    With moWord
        .Documents.Open "J:\Test.docx"    ' change document path according to actual file
        '.WindowState = wdWindowStateNormal
        .Visible = True
    End With
End Sub

Private Sub Form_Load()
    Set moWord = New Word.Application
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If Not (moWord Is Nothing) Then Set moWord = Nothing
End Sub

Private Sub moWord_DocumentBeforeClose(ByVal Doc As Word.Document, Cancel As Boolean) Handles moWord.DocumentBeforeClose
    If MsgBox("Do you really want to close the document?", vbQuestion + vbYesNo + vbDefaultButton2) = vbNo Then Cancel = True
End Sub

推荐阅读