O'Reilly logo

VB & VBA in a Nutshell: The Language by Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.6. Automation Examples

So let's bring together all you've seen in this chapter with a few sample implementations of OLE automation servers.

5.6.1. Using Word as a Report Writer from VB

This first application demonstrates how you can seamlessly use Microsoft Word to print output from your VB program without the user knowing that you have actually used Microsoft Word:

Private Sub cmdWordDoc_Click()

   'create an error handler
   On Error GoTo cmdWordDoc_Err
        
      'create the local Early Bound object variables
   Dim oWord           As Word.Application
   Dim oWordActiveDoc  As Word.Document
   Dim oWordSel        As Word.Selection
    
   'Create a new instance of Word
   Set oWord = New Word.Application
   'Create a new document object
   Set oWordActiveDoc = oWord.Documents.Add
   Set oWordSel = oWord.Selection
            
      'Do some work with the Selection object
      oWordSel.TypeText "This is some text from the VB app."
      oWordSel.WholeStory
      oWordSel.Font.Name = "Arial"
      oWordSel.Font.Size = 12
      oWordSel.Font.Bold = wdToggle
                    
      'Now print out the doc
      oWordActiveDoc.PrintOut
          
   'always tidy up before you leave
   Set oWordSel = Nothing
   Set oWordActiveDoc = Nothing
            
   Set oWord = Nothing
        
   Exit Sub

cmdWordDoc_Err:
   MsgBox Err.Number & vbCrLf & Err.Description & vbCrLf _
          & Err.Source
    
End Sub

Because this example uses early binding, you'll have to use the References dialog to add a project reference to the Word 8 Object Model.

Note that this application appears seamless ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required