About Word VBA Application Object

About Word VBA Application Object page contains information about using the Word application object from within another application, such as VB, Excel, Outlook, etc.

The following code places some values into cells A1 to A5, selects, and then copies them.

Then it creates a  Word obect and a Document Object and pastes the cells into the Document.

Note the 2 commented lines...

'    Dim objWord As Word.Application
'    Dim objDoc As Word.Document

While creating the code I used these 2 lines instead of the 2 line above them so intellisense would work. It doesn't work with "As Object" because it doesn't know what type of obect it is. So now you may ask why not just leave the 2 "As Word"... lines and not use the lines with "As Object?"

The reason is two-fold. The first is because to use As Word... lines you first have to add a reference to the Word Object Module in Tools>References (click here to see how).  Other versions of Word may have problems since they don't have the exact same module if you use the code on another computer, such is the case when you compile an exe file in VB.

The second reason is that with the generic As Object, when a computer with any version of Word runs the code...

Set objWord = CreateObject("Word.Application")

... it will create a Word Object with the same version that is installed on it.


Sub WordObject()
   
    Dim objWord As Object
    Dim objDoc As Object
'    Dim objWord As Word.Application
'    Dim objDoc As Word.Document
   
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "1"
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "2"
    Range("A3").Select
    ActiveCell.FormulaR1C1 = "3"
    Range("A4").Select
    ActiveCell.FormulaR1C1 = "4"
    Range("A5").Select
    ActiveCell.FormulaR1C1 = "5"
    Range("A1:A5").Select
    Range("A5").Activate
    Selection.Copy
   
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add
    objWord.Selection.Paste
    Set objDoc = Nothing
    Set objWord = Nothing
End Sub




Google


Return from About Word VBA Application Object to VBA Code Samples


Return to our Homepage