Link to home
Start Free TrialLog in
Avatar of 7of9121098
7of9121098

asked on

Create a word document in VB

How can I create a word document in Word a simple syntax example will suffice. I' m a newbie in VB I have been doing ASP, so it may be similar in asp. Thanks. Also which object library do I use.
Avatar of bobbit31
bobbit31
Flag of United States of America image

reference ms word object library under project/references:

Dim wdApp as New Word.Application
Dim wdDoc as Word.Document

set wdDoc = wdApp.documents.Add ("<path to new file>")

'' add whatever you want to the doc

wdDoc.save

wdDoc.close
set wdDoc = nothing

wdApp.quit
set wdApp = nothing
Avatar of 7of9121098
7of9121098

ASKER

How do I add whatever you want to the doc, what property?

wdApp.Selection.TypeText "Hello World"
wdApp.Selection.TypeParagraph '' this is a newline/cr

if you want to do bold and the like... i'd suggest recording a new macro. Type stuff, make stuff bold, insert picture, whatever... then go to edit the macro and you can see the code on how to do it.
bobbit31, I get an error when I try to create the new word document. Did I do something wrong?

set wdDoc = wdApp.documents.Add ("c:\temp\newfile.doc")
what's the error?
The word document has to exist otherwise I get an error: path invalid...error.
I works fine it the newfile.doc exists in the path, otherwise a error occurs.

How do I make it so I can create a new word document....instead of have a preexisting document in the directory path?
ASKER CERTIFIED SOLUTION
Avatar of bobbit31
bobbit31
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Your the man!, thanks....

  Dim wdApp As New Word.Application
  Dim wdDoc As Word.Document

  wdApp.documents.Add
  wdApp.Selection.TypeText "Hello World"
  wdApp.Selection.TypeParagraph 'new line
  wdApp.Selection.TypeText "Hello World2"
  Set wdDoc = wdApp.ActiveDocument

  wdDoc.saveas "C:\temp\newfile.doc"
  wdDoc.Close
  Set wdDoc = Nothing

  wdApp.quit
  Set wdApp = Nothing