Visual Basic – Otvaranje Word dokumenta

Ovaj tekst i VBA (Visual Basic for Application) kod će vam prikazati kako da otvorite MS Word dokument u okviru neke druge aplikacije. Trik je u tome da napišete class module (nazvan WordWrapper, kao u donjem primeru) koji će reagovati na događaj izazvan od strane Word-a, koristeći ključnu reč WithEvents. U nastavku imate kod same WordWrapper class-e i demonstraciju upotrebe koda.

WordWrapper Class

Private WithEvents

wrdApp As

Word.Application

Private wrdDoc As Word.Document
Private strDocName As String
Public Sub NewDoc()
  Set wrdDoc = wrdApp.Documents.Add
  strDocName = wrdDoc.Name
End Sub
Public Sub AddText(strNew As String)
  wrdDoc.Range.InsertAfter strNew
End Sub
Public Sub Preview()
  wrdDoc.PrintPreview
  wrdApp.Visible = True
End Sub
Public Sub Quit(blnSaveChanges As Boolean)
  On Error Resume Next
  If Not wrdApp Is Nothing Then
  wrdApp.Quit SaveChanges:=blnSaveChanges
  End If
  Err.Clear
End Sub
Private Sub Class_Initialize()
  Set wrdApp = New Word.Application
End Sub
Private Sub Class_Terminate()
  If Not wrdApp Is Nothing Then
  wrdApp.Quit False
  End If
End Sub
Private Sub wrdApp_Quit()
  Set wrdDoc = Nothing
  Set wrdApp = Nothing
End Sub
Private Sub wrdApp_WindowActivate( _
  ByVal Doc As Word.Document, _
  ByVal Wn As Word.Window)
  If strDocName = Wn.Caption Then
  wrdApp.Quit False
  End If
End Sub

Da bi testirali kod, možete iskoristiti jednostavnu formu sa dva dugmića (command button) nazavanim cmdStartWord i cmdStopWord koje sadrže sledeće procedure:
Dim ww As WordWrapper

Private Sub cmdStartWord_Click()
  Set ww = New WordWrapper
  With ww
  .NewDoc
  .AddText "Ovo je Test!"
  .Preview
  End With
End Sub
Private Sub cmdStopWord_Click()
  If Not ww Is Nothing Then
  ww.Quit False
  Set ww = Nothing
  End If
End Sub

Pratite Krstaricu na www.krstarica.com