-1

I open Word application in VB.Net by below code:

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

I wanna subscribe the closing event of msword and run something before closing. I read this question and this article but I really don't know how to use in VB.Net

Morteza Ebrahimi
  • 740
  • 1
  • 8
  • 20

1 Answers1

3

Add a reference (Project--References...) to Microsoft Word XX.0 Object Library.

XX depends on your version of MS Office i.e. 16.0 if your MS Office is 2016.

Add a command button named Command1 to form. Add this code to form:

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
Morteza Ebrahimi
  • 740
  • 1
  • 8
  • 20
Smith
  • 710
  • 1
  • 7
  • 11
  • Now got it, "moWord_DocumentBeforeClose" ,"moWord_DocumentBeforeSave", ... are events of Word.Application that will be bound by "WithEvents". Thanks a lot. – Morteza Ebrahimi Oct 09 '19 at 12:59
  • @MortezaEbrahemi That makes no sense. The code in your question is VB.NET using the [Office interop assemblies](https://learn.microsoft.com/en-us/visualstudio/vsto/office-primary-interop-assemblies?view=vs-2019). The code in this answer is VB6. It will not work in VB.NET. If you are indeed using VB6, then why did you put VB.NET code in your question? – GSerg Oct 09 '19 at 13:52
  • @GSerg you're right. I don't work in vb , I just asked for someone else. Thanks for your tips. – Morteza Ebrahimi Oct 11 '19 at 18:28