The code first creates an instance of the Word.ApplicationClass. Notice that the variable has the odd type Word._Application containing an underscore. (There's also an Application class without the underscore but if you use that then Visual Basic gets a little confused about some ambiguous methods.)
This example makes the Word server visible. In a real application, you might want to keep it hidden.
The Word object model uses lots of method calls that for some reason take object parameters by reference. That means you must put the values for those parameters in variables. For example, you cannot use "True" as a Boolean parameter because you cannot pass a constant by reference. Similarly you can't use a file name such as "C:\wherever\test.doc" for the name of the file you are opening because that is not an assignable variable.
Now the program starts adding text to the document. It adds a Paragraph object to the document's collection.
One of the more important objects in Word is Range. A Range represents a chunk of a document. The code sets the new paragraph's text to "Chrysanthemum Curve." It then sets the Range's style to "Heading 1."
The code then calls the Range's InsertParagraphAfter method. That adds a paragraph mark after the Range's current text and updates the Range so it advances to the new paragraph. Now the Range is ready to add more text after the first paragraph.
The code sets the Range's text again to add the new text and calls InsertParagraphAfter again.
The code will now add some text formatted as code with the font Courier New. It saves the current font's name and sets the Range's font to Courier New. From now on, new text will have this font.
The code sets the Range's text, adds a new paragraph mark, and then restores the original font name so future text will be in the original font.
Next the code calls the Word document's SaveAs method to save the new document. This overwrites any existing file with that name without any warning. If you want to be sure the file doesn't already exist, use File.Exists to check.
Finally the code closes the Word document and the Word application.
|