1.

Solve : Outlook 2k7 - create and populate new word document in VBA?

Answer»

Hello again.

I need to create a word document in VBA, then populate it with positioned images and text. How do i go about this?


ThanksQuote from: molly coddlez on March 18, 2011, 09:06:04 AM

Hello again.

I need to create a word document in VBA, then populate it with positioned images and text. How do i go about this?


Thanks


Since you are creating a Word Document, you would first need to get the word OBJECT. in VBA, you can use CreateObject.

Then you would want to create a new document; then you can use the document and manipulate it as you see fit.


If you want, you can also add a reference to the "Microsoft Word Object Library" (Tools->References in the VBA EDITOR).

Once added, you can work with Word Objects:

Code: [SELECT]Public Sub CreateDocument()

Dim WordApp As Word.Application
Dim NewDocument As Word.Document
Dim InsertImage As String
InsertImage="D:\bcmountain2.gif"
SET WordApp = New Word.Application
WordApp.Visible = False
Set NewDocument = WordApp.Documents.Add(, , , True)
Set objSelection = NewDocument.ActiveWindow.Selection
objSelection.TypeText "Text before the picture"
objSelection.TypeParagraph
Set Shapes = NewDocument.Shapes
Set objShape = Shapes.AddPicture(insertimage)
objSelection.TypeParagraph
objSelection.TypeText "More text appearing after the picture"
objSelection.TypeParagraph
WordApp.Visible = True





End Sub

The above is a simple macro that demonstrates how to add basic images as "shapes" and text around that image.

You can also save the resulting document by using the SaveAs() Method (NewDocument.SaveAs())

Be careful if you don't quit the Application Object but leave it invisible, since it will still be a running process. Usually best to do what you want with Word, and either quit it or show the results of the VBA to the user (by changing the Visible property to true). I did that here, if you want it to be invisible and quit, remove that LINE and add WordApp.Quit() to the end.



Discussion

No Comment Found