vbCity.com - Where Visual Basic lives!
    members ... register or login
 
Home | Forums | Blogs | .NET | FAQ | Search | PrettyCode.Print | DevCity.NET | Advertise 
 

vbCity/DevCity.NET Forums     [login] [register]   [posting guidelines]
 
vbCity/DevCity.NET Developer Community Forums. (total 559935 posts, by 190209 members) advanced search

Index / .NET / VB.NET / FAQ: Ultimate Guide To Office Automation. Part 1 - MS Word
For faster and easier code reviews use PrettyCode.Print for .NET!
http://www.prettycode.com 25% discount for vbCity Members - use Coupon Code VB040605MBR4598
Page 1 of 2: [1] 2 »
 Reply   New Topic   B'mark-It!   Print   Admin 
7/23/2003 11:54:02 AM
   # Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   Edit 
thebrow
(HyperActive Member)

Show this authors profile  Email the author of this post

posts: 278
since: May 22, 2003
from: King of Prussia
This topic is rated 10 points.
Version 2.0

I have seen way too many posts and answered way too many questions to have me believe this is not yet a frequently asked question. So Starting now I am going to begin compiling a guide to using, manipulating, and creating documents in MS Office using VB .NET.

============
MS Word
============

1) Creating a new Document

Hey you gotta start somewhere.
First make sure you import the Word Object Library to your project.
Now that you have access to the Word Object Library you need to have create an instance of the application

Code:
'office xp
   Dim wordApp As Word.Application
   wordApp = CreateObject("Word.Application")
'office 2000
   Dim wordApp As Word.Application
   wordApp = New Word.Application
'office 97
   Dim wordApp As Word.ApplicationClass
   wordApp = New Word.Application

Although with most objects you create a new instance of it using the New keyword, with OfficeXP it is best to Explicitly define it with the CreateObject method due to a bug that exists in Office 97, which is why we create the Object with the ApplicationClass and not the Application Object.
Now that we have a running Application, we are going to want to create a document, so ...

Code:
'XP and 2000
   Dim wordDoc As Word.Document
'97, once again the 97 bug
   Dim wordDoc As Word.DocumentClass

Now that we have an identifier for our document we are going to want to create a new document and play with it.

Code:
Dim wordRng As Word.Range
   Dim wordPara As Word.Paragraph

   With WordApp
      .WindowState = Word.WdWindowState.wdWindowStateMaximize
      .Documents.Add
      wordDoc = wordApp.ActiveDocument
      wordRng = wordDoc.Range

      With wordRng

         .Font.Bold = True
         .Font.Italic = True
         .Font.Size = 24
         'since this is going to be the first bit of text, you could just use the .Text field, but it is better practice
         'to prevent data lose to use .InsertAfter, anytime you enter data into the .Text field, it erases the pervious
         'info and replaces it with the new, .InsertAfter does the same as .Text += "anything"
         .InsertAfter "Word Automation"
         .InsertParagraphAfter

         ' Insert a blank paragraph between the two paragraphs.
         .InsertParagraphAfter

      End With

      'note, for non XP users, use wordPara = wordRng.Paragraphs.Item(3)
      wordPara = wordRng.Paragraphs(3)

      With wordPara.Range

         .Bold = False
         .Italic = True
         .Font.Size = 14
         .InsertAfter "Document Created On: "
         .Collapse(Direction:=Word.WdCollapseDirection.wdCollapseEnd)
         .InsertDateTime DateTimeFormat:="MM-DD-YY HH:MM:SS"

      End With

      .ActiveDocument.SaveAs "c:\My Documents\createDoc.Doc"
      .ActiveDocument.Saved = True

      .Quit

   End With

That should give you some idea of using the object library. Now this final step is optional but recommended. To help the garbage collector and to increase speed and effectively use memory, set all your large objects to nothing when finished with them. This will allow them to be taken out of memory a lot easier.

Code:
wordPara = Nothing
   wordRng = Nothing
   wordDoc = Nothing
   wordApp = Nothing


2) Opening a Word Document

OK, first create the application and document as before

Code:
'for xp users it would be
   Dim wordApp As Word.Application
   Dim wordDoc As Word.Document
    
   ' Create new hidden instance of Word.
   wordApp = CreateObject("Word.Application")

Now invoke the Application.Documents.Open(...) method

Code:
wordDoc = wordApp.Documents.Open(FileName:=docName)

The open method has a lot of different possible parameters. For lack of a better way to put it, here they are
  FileName - If you dont understand this one, you shouldnt be here
  ConfirmConversions - Set to true if the you want the convert file dialog to appear if the file is not an MS Word doc
  ReadOnly - Set to True if you dont want the ability to modify the text
  AddToRecentFiles - Set to true if you want the Word doc in the Recent Files listing
  Revert - If the file is already open, True will discard all unsaved changes and open file from disk, False will activate current
  Format - Specifies file converter; wdOpenFormatAuto, wdOpenFormatDocument, wdOpenFormatTemplate, wdOpenFormatRTF, wdOpenFormatText, wdOpenFormatUnicodeText
  Password - If the doc needs a password to open, this is where you put it
  WritePassWordDocument - if to modify the doc you need a password, you put it here
  PasswordTemplate - If the doc is based on a template, you put that password here
  WritePasswordTemplate - To change template, password Here
Now that that is over with, do anything you want and quit

Code:
' Display document name and count of words, and then close
   ' document without saving changes.
   With wordDoc
       accessWordDoc = "'" & .Name & "' contains " & .Words.Count & " words."
       .Close wdDoNotSaveChanges
   End With

   wordApp.Quit(False)
   Set wordApp = Nothing

For anyone, like myself, who still has to use Word 97, you will recieve the error

Quote:
'close' is ambiguous across the inherited interfaces 'Word._Document' and 'Word.DocumentEvents_Event'.

to get around this, force the type of object with the current close/quit method

Code:
CType(.ActiveDocument, Word._Document).Close()

I've seen that questions asked about 10 times in 3 months so I am going to keep repeating it.

3) Inserting Data into Word from an MS Access Form

Here is the code to do this in Word XP:-

Code:
Private Sub MergeButton_Click()
   On Error GoTo MergeButton_Err
   Dim objWord As Word.Application
   ' Get path of the photo.
   Dim sImagePath As String
   sImagePath = ""
   If InStr(2, ImagePath.Value, ":") Or InStr(1, ImagePath.Value, "\") Then
      sImagePath = ImagePath.Value 'path was complete
   Else ' ImagePath is to file in folder of this database.
      sImagePath = Me.Application.CurrentProject.path & "\" & ImagePath.Value
   End If
  
   'Start Microsoft Word.
   Set objWord = CreateObject("Word.Application")
   With objWord ' Make the application visible.
      .Visible = True
      ' Open the document.
      .Documents.Open ("c:\MyDocs\mymerge.doc")
      ' Move to each bookmark and insert text from the form.
      .ActiveDocument.Bookmarks("First").Select
      .Selection.Text = (CStr(Forms!Employees!FirstName))
      .ActiveDocument.Bookmarks("Last").Select
      .Selection.Text = (CStr(Forms!Employees!LastName))
      .ActiveDocument.Bookmarks("Address").Select
      .Selection.Text = (CStr(Forms!Employees!Address))
      .ActiveDocument.Bookmarks("City").Select
      .Selection.Text = (CStr(Forms!Employees!City))
      .ActiveDocument.Bookmarks("Region").Select
      .Selection.Text = (CStr(Forms!Employees!Region))
      .ActiveDocument.Bookmarks("PostalCode").Select
      .Selection.Text = (CStr(Forms!Employees!PostalCode))
      .ActiveDocument.Bookmarks("Greeting").Select
      .Selection.Text = (CStr(Forms!Employees!FirstName))
   
      ' Insert the photo.
      .ActiveDocument.Bookmarks("Photo").Select
      .Selection.InlineShapes.addpicture fileName:=sImagePath, _
      LinkToFile:=False, SaveWithDocument:=True
   End With
  
   ' Print the document in the foreground so that Word
   ' does not close until the document is finished printing.
   objWord.ActiveDocument.PrintOut Background:=False
   ' Close the document without saving changes.
   objWord.ActiveDocument.Close
 
   SaveChanges:=wdDoNotSaveChanges
   ' Quit Microsoft Word and release the object variable.
   objWord.Quit
   Set objWord = Nothing

   Exit Sub
 
MergeButton_Err:
   ' If a field on the form is empty,
   ' remove the bookmark text and continue.
   If Err.Number = 94 Then
      objWord.Selection.Text = ""
      Resume Next ' If the Photo field is empty...
   ElseIf Err.Number = 2046 Then
      MsgBox "Please add a photo to this record and try again."
   Else
      MsgBox Err.Number & vbCr & Err.Description
   End If
   Exit Sub
End Sub




Edited by - thebrow on 7/30/2003 11:22:18 AM

Attachment: OfficeAutomationAllVersions.zip (2 KB)   This has been downloaded 2553 time(s).
7/27/2003 4:40:31 AM
   #1 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
XTab
(vbCity Leader)

Show this authors profile  Email the author of this post

posts: 4741
since: Feb 21, 2002
from: Dumfries, Scotland
I think some of the code in the FAQ will only work with XP. Attached is a demo solution, which should have backward compatibility, that demonstrates the first two topics of the FAQ; thanks again to thebrow for this follow-up


[Edit] There's a temporary problem with file uploading, so the attachment hasn't made the trip. sad I'll post it up as soon as things are fixed.




Edited by - XTab on 7/27/2003 5:04:17 AM
7/28/2003 9:44:44 AM
   #2 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
MHWright
(Fanatic Member)

Show this authors profile  Email the author of this post

posts: 232
since: Apr 25, 2003
from: Westfield MA
This reply is rated 3 points.
Over the past 6 weeks I have been trying to add something along the same lines but have issues when it comes to office XP. will this code also work with Office XP?


7/28/2003 10:57:59 AM
   #3 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
thebrow
(HyperActive Member)

Show this authors profile  Email the author of this post

posts: 278
since: May 22, 2003
from: King of Prussia
This reply is rated 1 point.
The code I posted is XP for Office XP while the code I sent XTab that is posted for download should work with 97 and 2000

Office XP objects prefer explicit declaration (using set, createobject, etc) and generally will cause errors, bug, exceptions when defined implicately

Office 2000 doesnt have any problems with implict declaration (New) since .net was first designed to work with it

Office 97 has a wrapper bug that prevents explicit declaration and causes conflicts with implicit. This forces you to define the Application by with New ApplicationClass or force the conflicting methods to their type with CType. This is defined in much greater detail in the KB article I linked to in section 1

7/29/2003 6:54:51 AM
   #4 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
jfb
(Junior Member)

Show this authors profile  Email the author of this post

posts: 25
since: Jul 29, 2003
from: Virginia
This reply is rated 3 points.
Hi,
I try this for vs.net 2003 and office XP and I have and error

I include the word library but i can't defined the line:
         Imports Interop.Word

Also I getting error in the line:
         WA = CreateObject("Word.Application")

ERROR DESCRIPTION:

An unhandled exception of type 'System.InvalidCastException' occurred in
PrintSpoolFolder.exe

Additional information: Specified cast is not valid.

Any Ideas why i'm getting this error?

Is wordApp.Print() the command for print?

Thanks in advance

JFB



7/29/2003 7:46:30 AM
   #5 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
thebrow
(HyperActive Member)

Show this authors profile  Email the author of this post

posts: 278
since: May 22, 2003
from: King of Prussia
This reply is rated 1 point.
ok a couple things

1) when i was pasting this together, i forgot a line or two.
to use Imports Interop.Word, you must add this line
Imports System.Runtime.InteropServices
to your assembly infor and copy the dll of office and word to the bin folder of your project.
sorry, I make small mistakes a lot. Also its a lot easier to just add the reference in the Solution Explorer

2) not sure why you are getting that error, but make sure you define Dim WA as Word.Application. If that doesnt work try
Dim WA as Word.ApplicationClass. If that doesnt work, well I'm really suprised and have never seen that before. Try implicate declarations then or add the Set operator (Set WA = CreateObject("Word.Application"))

3) To print use the PrintOut method in the Application or the Document Objects. (by default the activedocument is printed unless the filename parameter is set)

7/29/2003 9:06:34 AM
   #6 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
jfb
(Junior Member)

Show this authors profile  Email the author of this post

posts: 25
since: Jul 29, 2003
from: Virginia
This reply is rated 3 points.
Tks for you reply thebrow,
I try all you said and still the error.
Also i cant define the line Imports Interop.Word
I'm attaching my simple project.
Any other toughts?
Tks again
JFB



Attachment: PrintWordDocument.zip (330 KB)   This has been downloaded 180 time(s).
7/29/2003 9:47:44 AM
   #7 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
thebrow
(HyperActive Member)

Show this authors profile  Email the author of this post

posts: 278
since: May 22, 2003
from: King of Prussia
This reply is rated 1 point.
ok i looked at it and i made a few small changes and everything seemed to work fine for me, i couldnt run the project because i only have VS.net 2002.




Attachment: Form1.zip (990 B)   This has been downloaded 164 time(s).
7/30/2003 7:50:23 AM
   #8 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
jfb
(Junior Member)

Show this authors profile  Email the author of this post

posts: 25
since: Jul 29, 2003
from: Virginia
This reply is rated 3 points.
Tks thebrow for all you help.
Finally i made it work like this...
        Dim wordApp As Word.Application
        Dim wordDoc As Word.Document

        ' Create new hidden instance of Word.

        Try
            'for office xp
            wordApp = CreateObject("Word.Application")
            wordDoc = CreateObject("Word.document")
        Catch
            'for office 2000 and 97
            wordApp = New Word.Application
            wordDoc = New Word.Document
        End Try

        wordApp.Visible = False
        wordDoc = wordApp.Documents.Open(FileName:="C:\spool folder\test.doc")
        wordDoc.printout()
        wordDoc.close()
        wordApp.Quit()
        wordApp = Nothing
        wordDoc = Nothing

8/28/2003 2:34:56 AM
   #9 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
anthonymain
(New Member)

Show this authors profile  Email the author of this post

posts: 1
since: Aug 28, 2003
from: UK
This reply is rated 3 points.
Great guide well done fella, but Im having problems with it. Tried a few of the follow up post messages but this is what I have:

            Dim wordApp As Word.Application
            Dim wordDoc As Word.Document
            Try
                'for office xp
                WriteLog("Switch: Office XP")
                wordApp = CreateObject("Word.Application")
                wordDoc = CreateObject("Word.document")
            Catch
                'for office 2000 and 97
                WriteLog("Switch: Office 2K / 97")
                wordApp = New Word.Application
                wordDoc = New Word.Document
            End Try

            wordDoc = wordApp.Documents.Open(FileName:="c:\inetpub\wwwroot\docstreamer\1.rtf")

Office XP is installed on my system (running locally for now). I get cannot creative ActiveX component if I force it to use the XP code.

If I use the try catch I get Access Denied as it tries to use the 2k version (which isnt installed)

Any ideas why the XP method wouldn't work ?! I have ref'd both the word and office components


Edited by - anthonymain on 8/28/2003 2:36:36 AM
8/28/2003 12:21:29 PM
   #10 Re: Ultimate Guide To Office Automation. Part 1 - MS Word  
 Reply   w/Quote   B'mark-It!   Edit   Del 
thebrow
(HyperActive Member)

Show this authors profile  Email the author of this post

posts: 278
since: May 22, 2003
from: King of Prussia
This reply is rated 1 point.
I've been looking into this for awhile, and this is what I've found

Microsoft has been using late binding in all of their documentation of automating Office for years, however for some reason or another problems have arrised whenever late binding is used with Office products on some machines and not others. In fact Microsoft has even acknowledged this in one of the more recent kb articles on Automating Office XP. When I wrote this FAQ, the machine I was using Office XP on ( my company had just switched to XP everything ) had no problems with the late binding methods I posted, however when I first tried distributing the app, there were massive errors on serval different computers claiming that the objects could not be made.

I guess I need to rewrite the example I posted but I am 1) too lazy right now and 2) have alot of work to do.
Just use early early binding for all office types
Dim WordApp As Word.Application
wordApp = New Word.Application

Also, some of the constants that I have posted in XP their name Space changes from Office.* to Microsoft.Office.Core.*


 Reply   New Topic   B'mark-It!   Print   Admin 
Page 1 of 2: [1] 2 »
All times are GMT -08:00 (Pacific Time)  
 
Jump to:
 

Powered by discussMaster v2.0,
Copyright © 2000-2005 vbCity.com.

Got Tools?
Premium Sponsor
Contest Winners
September 2006
HOTM: - Christopher Fannin aka AbbydonKrafts  » 
Sponsored Links
Compare, synch, package, deploy...
Download Red Gate's SQL tools & automate database development tasks.
Visual Basic 2005 Express Edition - FREE forever!
Finally, a professional Visual Basic printout.
That's PrettyCode.Print - http://www.prettycode.com