Microsoft Word VBA (1)
Word objects Common Tasks
Macros Automation DAO 3.6
Word objects
Application
├ Documents (Document) Currently open documents
├ Templates (Template) Currently available templates ├ Tasks (Task) ├ Selection ├ Options
├ MailingLabel
┖… …
Document的下属Collections和Objects:
Subdocuments (Subdocument), Versions (Version), Windows (Window), Sections (Section), Paragraphs (Paragraph), Sentences (Sentence), Words (Range), Characters (Range), Range, Bookmarks (Bookmark),
Tables (Table), Lists (List), Fields (Field), FormFields (FormField), Variables (Variable), Styles (Style),
Shapes (Shape), InlineShapes (InlineShape)
Comments (Comment), Footernotes (Footnotes), Endnotes (Endnote) Hyperlinks (Hyperlink)
Indexes (Index),TableOfContents (TableOfContent), TableOfFigures (TableOfFigure), PageSetup,
DocumentProperties(DocumentProperty), LetterContent, Envelope,
Email, Scrips (Script), Frames (Frame),
MailMerge( MailMergeDataSource, MailMergeFields (MaiMergeField)) CommandBars (CommabdBar), VBProject, HTMLProject, WebOptions … …
Objects are the fundamental building block of Visual Basic; nearly everything you do in Visual Basic involves modifying objects. Every element of Word — documents, tables, paragraphs, bookmarks, fields, a single character and so on — can be represented by an object in Visual Basic.
Properties and Methods
Documents(\"MyDoc.doc\").TrackRevisions = True docName = ActiveDocument.Name
ActiveDocument.PrintOut From:=1, To:=3
Collections
A collection is an object that contains several other objects, usually of the same type; for example, all the bookmark objects in a document are contained in a single collection object. Using properties and methods, you can modify a single object or an entire collection of objects.
For example,the Documents collection contains the open Word documents. You use the Documents property of the Application object (the object at the top of the Word object hierarchy) to return the Documents collection.
The Item method returns a single object from a collection. The following example sets the firstDoc variable to a Document object that represents the first document in the Documents collection.
Set firstDoc = Documents.Item(1)
The Item method is the default method for most collections, so you can write the same statement more concisely by omitting the Item keyword. Set firstDoc = Documents(1)
Named Objects
Although you can usually specify an integer value with the Item method, it may be more convenient to return an object by name. Documents(\"Sales.doc\").Activate Documents(\"Sales.doc\").Close
The following example selects the range of text marked by the bookmark named temp in the active document.
ActiveDocument.Bookmarks(\"temp\").Select
Not all collections can be indexed by name. To determine the valid collection index values, see the collection object topic.
Predefined Index Values
Some collections have predefined index values you can use to return single objects. Each predefined index value is represented by a constant. For example, you specify an WdBorderType constant with the Borders property to return a single Border object.
The following example adds a single 0.75 point border below the first paragraph in the selection.
With Selection.Paragraphs(1).Borders(wdBorderBottom)
.LineStyle = wdLineStyleSingle .LineWidth = wdLineWidth075pt
End With
Collection objects often have methods and properties which you can use to modify the entire collection of objects. The Documents object has a Save method that saves all the documents in the collection. The following example saves the open documents by applying the Save method.
Documents.Save
The Document object also has a Save method available for saving a single document.
Documents(\"Report.doc\").Save
Other examples:
ActiveDocument.Close SaveChanges:=wdSaveChanges
ActiveDocument.ActiveWindow.WindowState = wdWindowStateMaximize
The following example creates a new document and displays the Save As dialog box so that a name can be provided for the document.
Documents.Add.Save
Common Word tasks
Working with Document objects
In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection object.
Creating a new document
The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a new document.
Documents.Add
A better way to create a new document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following
example, the Document object returned by the Add method is assigned to an object variable, newDoc. Then several properties and methods of the Document object are set. You can easily control the new document using the newDoc object variable.
Set newDoc = Documents.Add With newDoc
.Content.Font.Name = \"Arial\" .SaveAs FileName:=\"Sample.doc\"
End With
Add Method (Documents Collection)
Add(Template, NewTemplate, DocumentType, Visible)
Template: Optional Variant. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used. NewTemplate: True/False. True to open the document as a template DocumentType: Optional Variant
wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. Visible: True/False.
例: Documents.Add Template:=\"C:\\Program Files\\Microsoft Office\" _ & \"\\Templates\\Memos\\Professional Memo.dot\"
Opening a document
To open an existing document, use the Open method with the Documents collection.
Documents.Open FileName:=\"C:\\MyFolder\\MyDocument.doc\"
Saving an existing document
To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.
Documents(\"Sales.doc\").Save
You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.
Documents.Save
Saving as a new document
To save a single document, use the SaveAs method with a Document object.
ActiveDocument.SaveAs FileName:=\"Temp.doc\"
The FileName argument can include only the file name or the complete path (for example, \"C:\\Documents\\Temporary File.doc\").
Closing documents
To close a single document, use the Close method with a Document object.
Documents(\"Sales.doc\").Close SaveChanges:=wdSaveChanges
You can close all open documents by applying the Close method to the Documents collection.
Documents.Close SaveChanges:=wdDoNotSaveChanges
The following example prompts the user to save each document before the document is closed.
For Each aDoc In Documents aDoc.Save NoPrompt:=False aDoc.Close Next
Activating a document
To change the active document, use the Activate method with a Document object
Documents(\"MyDocument.doc\").Activate
Determining if a document is open
To determine if a document is open, you can enumerate the Documents collection by using a For Each...Next statement. The following example activates the document named \"Sample.doc\" if the document is open, or opens Sample.doc if it's not currently open.
For Each aDoc In Documents
If InStr(1, aDoc.Name, \"sample.doc\ aDoc.Activate Else
docFound = False End If Next aDoc
If docFound = False Then _
Documents.Open FileName:=\"C:\\Documents\\Sample.doc\"
Referring to the active document
Instead of referring to a document by name or index number — for example
Documents(\"Sales.doc\") — the ActiveDocument property returns a Document object which refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.
If Documents.Count >= 1 Then MsgBox ActiveDocument.Name Else
MsgBox \"No documents are open\" End If
Applying formatting to text
Applying formatting to the selection
The following example uses the Selection property to apply character and paragraph formatting to the selected text. Use the Font property to access character formatting properties and methods and the ParagraphFormat property (object) to access paragraph formatting properties and methods.
With Selection.Font
.Name = \"Times New Roman\" .Size = 14
.AllCaps = True End With
With Selection.ParagraphFormat
.LeftIndent = InchesToPoints(0.5) .Space1 End With
Applying formatting to a range
The following example defines a Range object that refers to the first three paragraphs in the active document. The Range (myRange) is formatted by applying properties of the Font and ParagraphFormat objects.
Set myRange = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(1).Range.Start, _ End:=ActiveDocument.Paragraphs(3).Range.End) With myRange
.Font.Name = \"Arial\"
.ParagraphFormat.Alignment = wdAlignParagraphJustify End With
Inserting text and applying character and paragraph formatting
The following example adds the “Title” at the top of the current document. The first
paragraph is center aligned and a half inch space is added after the paragraph. The word Title is formatted with 24 point Arial font.
Set oRange = ActiveDocument.Range(Start:=0, End:=0) With oRange
.InsertAfter Text:=\"Title\" .InsertParagraphAfter .Font.Name = \"Arial\" .Font.Size = 24 End With
With ActiveDocument.Paragraphs(1)
.Alignment = wdAlignParagraphCenter
.SpaceAfter = InchesToPoints(.5) End With
Range Method ( Document object )
Returns a Range object by using the specified starting and ending character positions. Range(Start, End)
Start : Optional Long. The starting character position. End: Optional Long. The ending character position. Remarks
Character position values begin with 0 (zero) at the beginning of the document. All characters are counted, including nonprinting characters. Hidden characters are counted even if they're not displayed. If you don't specify starting and ending
character positions for the Range method, the entire document is returned as a Range object.
Toggling the space before a paragraph between 12 points none
The following example toggles the space before formatting of the first paragraph in the
selection. The macro retrieves the current space before value, and if the value is 12 points the space before formatting is removed (the SpaceBefore property is set to zero). If the
space before value is anything other than 12, then SpaceBefore property is set to 12 points.
Set oParagraph = Selection.Paragraphs(1) If oParagraph.SpaceBefore = 12 Then oParagraph.SpaceBefore = 0 Else
oParagraph.SpaceBefore = 12 End If
Toggling bold formatting
The following example toggles bold formatting of the selected text.
Selection.Font.Bold = wdToggle
Increasing the left margin by 0.5 inch
The following example increases the left margin by 0.5 inch. The PageSetup object contains all the page setup attributes of a document (left margin, bottom margin, paper size, and so on) as properties. The LeftMargin property is used to return and set the left margin setting.
iMargin = ActiveDocument.PageSetup.LeftMargin iMargin = iMargin + InchesToPoints(0.5)
ActiveDocument.PageSetup.LeftMargin = iMargin
Finding and replacing text or formatting
Finding and replacing is exposed by the Find and Replacement objects. The Find object is available from the Selection and Range object. The find action differs slightly depending upon whether you access the Find object from the Selection or Range object.
Finding text and selecting it
If the Find object is accessed from the Selection object, the selection is changed when the find criteria is found. The following example selects the next occurrence of the word
\"Hello.\" If the end of the document is reached before the word \"Hello\" is found, the search is stopped.
With Selection.Find .Forward = True .Wrap = wdFindStop .Text = \"Hello\" .Execute End With
The Find object includes properties that relate to the options in the Find and Replace dialog box (choose Find from the Edit menu). You can set the individual properties of the Find object or use arguments with the Execute method as shown in the following example.
Selection.Find.Execute FindText:=\"Hello\
Finding text without changing the selection
If the Find object is accessed from a Range object, the selection is not changed but the Range is redefined when the find criteria is found. The following example locates the first occurrence of the word \"blue\" in the active document. If the find operation is successful, the range is redefined and bold formatting is applied to the word \"blue.\"
With ActiveDocument.Content.Find .Text = \"blue\" .Forward = True .Execute
If .Found = True Then .Parent.Bold = True End With
The following example performs the same result as the previous example using arguments of the Execute method.
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:=\"blue\If myRange.Find.Found = True Then myRange.Bold = True
Using the Replacement object
The Replacement object represents the replace criteria for a find and replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box (Edit menu).
The Replacement object is available from the Find object. The following example replaces all occurrences of the word \"hi\" with \"hello.\" The selection changes when the find criteria is found because the Find object is accessed from the Selection object.
With Selection.Find .ClearFormatting .Text = \"hi\"
.Replacement.ClearFormatting .Replacement.Text = \"hello\"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue End With
The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. In order to find and replace formatting, set the find and replace text to empty strings (\"\") and set the Format argument of the Execute method to True. The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).
With ActiveDocument.Content.Find .ClearFormatting .Font.Bold = True With .Replacement .ClearFormatting .Font.Bold = False End With
.Execute FindText:=\"\ Format:=True, Replace:=wdReplaceAll End With
Selecting text in a document
Use the Select method to select an item in a document. The Select method is available from several objects, such as Bookmark, Field, Range, and Table. The following example selects the first table in the active document.
ActiveDocument.Tables(1).Select
The following example selects the first field in the active document.
ActiveDocument.Fields(1).Select
The following example selects the first four paragraphs in the active document. The Range method is used to create a Range object which refers to the first four paragraphs. The Select method is then applied to the Range object.
Set myRange = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(1).Range.Start, _ End:=ActiveDocument.Paragraphs(4).Range.End) myRange.Select
Returning text from a document
Use the Text property to return text from a Range or Selection object. The following example selects the next paragraph formatted with the Heading 1 style. The contents of the Text property are displayed by the MsgBox function.
With Selection.Find .ClearFormatting
.Style = wdStyleHeading1
.Execute FindText:=\"\ Forward:=True, Wrap:=wdFindStop
If .Found = True Then MsgBox Selection.Text End With
The following instruction returns the selected text.
strText = Selection.Text
The following example returns the first word in the active document. Each item in the Words collection is a Range object that represents one word.
aFirst = ActiveDocument.Words(1).Text MsgBox aFirst
The following example returns the text associated with the first bookmark in the active document.
If ActiveDocument.Bookmarks.Count >= 1 Then
bookText = ActiveDocument.Bookmarks(1).Range.Text MsgBox bookText End If
Editing text
Determining whether text is selected
The Type property of the Selection object returns information about the type of selection. The following example displays a message if the selection is an insertion point.
If Selection.Type = wdSelectionIP Then MsgBox \"Nothing is selected\"
Selection type can be one of the following WdSelectionType constants:
wdNoSelection, wdSelectionBlock, wdSelectionColumn, wdSelectionFrame, wdSelectionInlineShape, wdSelectionIP(Insert point), wdSelectionNormal, wdSelectionRow, or wdSelectionShape. Read-only Long.
Collapsing a selection or range
Use the Collapse method to collapse a Selection or Range object to it's beginning or ending point. The following example collapses the selection to an insertion point at the beginning of the selection(去掉原Selection,光标指向原Selectio的下一字符位置).
Selection.Collapse Direction:=wdCollapseStart
The following example cancels the myRange object to it's ending point (after the first word).
Set myRange = ActiveDocument.Words(1)
myRange.Collapse Direction:=wdCollapseEnd
Extending a selection or range
The following example uses the MoveEnd method to extend the end of the selection to include three additional words. The MoveLeft, MoveRight, MoveUp and MoveDown methods can also be used to extend a Selection object.
Selection.MoveEnd Unit:=wdWord, Count:=3
The following example uses the MoveEnd method to extend oRange to include the first three paragraphs in the active document.
Set oRange = ActiveDocument.Paragraphs(1).Range oRange.MoveEnd Unit:=wdParagraph, Count:=2
Redefining a Range object
Use the SetRange method to redefine an existing Range object. The following example defines myRange to the current selection. The SetRange method redefines myRange so that it refers to current selection plus the next ten characters.
Set myRange = Selection.Range
myRange.SetRange Start:=myRange.Start, End:=myRange.End + 10
Changing text
You can change existing text by changing the contents of a range. The following instruction changes the first word in the active document by setting the Text property to \"The.\"
ActiveDocument.Words(1).Text = \"The \"
You can also use the Delete method to delete existing text and then insert new text using the InsertAfter or InsertBefore method. The following example deletes the first paragraph in the active document and inserts new text.
Set myRange = ActiveDocument.Paragraphs(1).Range With myRange .Delete
.InsertAfter Text:=\"New text\" ‘Insert characters .InsertParagraphAfter ‘Insert Paragraph mark End With
The following example inserts text at the end of the active document.
ActiveDocument.Content.InsertAfter Text:=\" the end.\"
After using the InsertBefore or InsertAfter method, the Range or Selection expands to include the new text. Use the Collapse method to collapse a Selection or Range to the beginning or ending point.
Modifying a portion of a document
Visual Basic includes objects which you can use to modify the following document elements: characters, words, sentences, paragraphs and sections. The following table includes the properties that correspond to these document elements and the objects they return.
This expression Returns this object Words(index) Range Characters(index) Range Sentences(index) Range Paragraphs(index) Paragraph Sections(index) Section
When these properties are used without an index, a collection object with the same name is returned. For example, the Paragraphs property returns the Paragraphs collection object. However, if you identify an item within these collections by index, the object in the second column of the table is returned. For example, Words(1) returns a Range object. After you have a Range object, you can use any of the range properties or methods to modify the Range object. For example, the following instruction copies the first word in the selection to the Clipboard.
Selection.Words(1).Copy
Note The items in the Paragraphs and Sections collections are singular forms of the collection rather than Range objects. However, the Range property (which returns a Range object) is available from both the Paragraph and Section objects. For example, the following instruction copies the first paragraph in the active document to the Clipboard.
ActiveDocument.Paragraphs(1).Range.Copy
All of the document element properties in the preceding table are available from the
Document, Selection, and Range objects. The following examples demonstrate how you can drill down to these properties from Document, Selection, and Range objects.
The following example sets the case of the first word in the active document.
ActiveDocument.Words(1).Case = wdUpperCase
The following example sets the bottom margin of the current section to 0.5 inch.
Selection.Sections(1).PageSetup.BottomMargin = InchesToPoints(0.5)
The following example double spaces the text in the active document (the Content property returns a Range object).
ActiveDocument.Content.ParagraphFormat.Space2
Modifying a group of document elements
To modify a range of text that consists of a group of document elements (characters, words, sentences, paragraphs or sections), you need to create a Range object. The Range method creates a Range object given a start and end point. For example, the following instruction creates a Range object that refers to the first ten characters in the active document.
Set myRange = ActiveDocument.Range(Start:=0, End:=10)
Using the Start and End properties with a Range object, you can create a new Range object that refers to a group of document elements. For example, the following instruction creates a Range object (myRange) that refers to the first three words in the active document.
Set Doc = ActiveDocument
Set myRange = Doc.Range(Start:=Doc.Words(1).Start, _ End:=Doc.Words(3).End)
The following example creates a Range object (aRange) beginning at the start of the second paragraph and ending after the third paragraph.
Set Doc = ActiveDocument
Set myRange = Doc.Range(Start:=Doc.Paragraphs(2).Range.Start, _ End:=Doc.Paragraphs(3).Range.End)
Range object
A Range object represents a contiguous area in a document. Each Range object is defined by a starting and ending character position. Similar to the way bookmarks are used in a document, Range objects are used in Visual Basic procedures to identify specific portions of a
document. However, unlike a bookmark, a Range object only exists while the procedure that defined it is running.
Note Range objects are independent of the selection. That is, you can define and manipulate a range without changing the selection. You can also define multiple ranges in a document, while there can be only one selection per pane.
Using the Range Object
Use the Range method to return a Range object defined by the given starting and ending character positions. The following example returns a Range object that refers to the first 10 characters in the active document.
Set myRange = ActiveDocument.Range(Start:=0, End:=10)
Use the Range property to return a Range object defined by the beginning and end of another object. The Range property applies to many objects (for example, Paragraph, Bookmark, and Cell). The following example returns a Range object that refers to the first paragraph in the active document.
Set aRange = ActiveDocument.Paragraphs(1).Range
The following example returns a Range object that refers to the second through fourth paragraphs in the active document
Set aRange = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(2).Range.Start, _ End:=ActiveDocument.Paragraphs(4).Range.End) With aRange
.Bold = True
.ParagraphFormat.Alignment = wdAlignParagraphCenter .Font.Name = \"Arial\" End With
Using the Duplicate property
The following instruction creates a new duplicated Range object, Range2, which has the same start and end points and text as Range1.
Set Range2 = Range1.Duplicate
If you change the start or end point of Range1, it doesn't affect Range2, and vice versa. Because these two ranges point to the same location in the document, changing the text in one range affects the text in the other range.
Working with tables
Inserting text into a table cell
The following example inserts text into the first cell of the first table in the active document. The Cell method returns a single Cell object. The Range property returns a Range object. The Delete method is used to delete the existing text and the InsertAfter method inserts the text \"Cell 1,1\" text.
If ActiveDocument.Tables.Count >= 1 Then
With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range .Delete
.InsertAfter Text:=\"Cell 1,1\" End With End If
注: 在cell中插入公式可以用Cell object 的Formula方法,或先Select这个cell,然后用Selection的InsertFormula方法。如:
Selection.InsertFormula Formula:=\"=D3*E3\
在交互环境可以用Table->Formula命令在当前选择的cell插入公式。如果看所插入的公式,只能Alt+F9(用Table->Formula对话框不再能看到以前已插入的公式),看Field Code。在VBA里可以用Fields集合,field object有Code和Result属性。
另外,在Word中,好象无法设置公式的自动更新。只能按F9更新所选择的Fields。用VBA:
ActiveDocument.Tables(1).Select Selection.Fields.Update
Creating a table, inserting text, and applying formatting
The following example inserts a 4 column, 3 row table at the beginning of the document. The For Each...Next structure is used to step through each cell in the table. Within the For
Each...Next structure, the InsertAfter method is used to add text to the table cells (Cell 1, Cell 2, and so on).
Set oDoc = ActiveDocument
Set oTable = oDoc.Tables.Add( _
Range:=oDoc.Range(Start:=0, End:=0), NumRows:=3, _ NumColumns:=4) iCount = 1
For Each oCell In oTable.Range.Cells
oCell.Range.InsertAfter \"Cell \" & iCount iCount = iCount + 1 Next oCell
oTable.AutoFormat Format:=wdTableFormatColorful2, _
ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True
Returning text from a table cell without returning the end of cell marker
The following examples return and display the contents of each cell in the first row of the first document table.
Set oTable = ActiveDocument.Tables(1) For Each aCell In oTable.Rows(1).Cells
Set myRange = ActiveDocument.Range(Start:=aCell.Range.Start, _ End:=aCell.Range.End - 1) MsgBox myRange.Text Next aCell
Set oTable = ActiveDocument.Tables(1) For Each aCell In oTable.Rows(1).Cells Set myRange = aCell.Range
myRange.MoveEnd Unit:=wdCharacter, Count:=-1 MsgBox myRange.Text Next aCell
自注:Cell的End mark是2个字符:Chr(13)(i.e.return)和Chr(7),不知为什么只回退
一个。但回退一个确实是对的(已实验).
Dim c As Range
Set c = ActiveDocument.Tables(1).Cell(1, 1).Range ‘ 设cell(1,1)含 “ABCDEFG” MsgBox c.Text & \" Len=\" & Len(c.Text) ‘ Len=9
MsgBox Left(c.Text, Len(c.Text) - 1) & “*” ‘ “ABCDEFG”+Chr(13)+”*” MsgBox Left(c.Text, Len(c.Text) - 2) & “*” ‘ “ABCDEFG*” Ok c.MoveEnd Unit:=wdCharacter, Count:=-1
MsgBox c.Text & \" Len=\" & Len(c.Text) & “*” ‘ “ABCDEFG*” Len=7 Ok
Returning the contents of each table cell
The following example defines an array equal to the number of cells in the first document table (assuming Option Base 1). The For Each...Next structure is used to return the contents of each table cell and assign the text to the corresponding array element.
If ActiveDocument.Tables.Count >= 1 Then Set oTable = ActiveDocument.Tables(1) iNumCells = oTable.Range.Cells.Count ReDim aCells(iNumCells) i = 1
For Each oCell In oTable.Range.Cells Set myRange = oCell.Range
myRange.MoveEnd Unit:=wdCharacter, Count:=-1 aCells(i) = myRange.Text i = i + 1 Next oCell End If
Converting existing text to a table
The following example inserts tab-delimited text at the beginning of the active document and then converts the text to a table.
Set oRange1 = ActiveDocument.Range(Start:=0, End:=0)
oRange1.InsertBefore \"one\" & vbTab & \"two\" & vbTab & \"three\" & vbCr Set oTable1 = oRange1.ConvertToTable( _
Separator:=Chr(9), NumRows:=1, NumColumns:=3)
Converting a table to Tab- or Comma-delimited text
Selection.Rows.ConvertToText Separator:=wdSeparateByTabs, NestedTables:=True Table:
Gender Name Addr City State PostCode Country EmailAddr
NameA M AddressA CityA StateA 10001 U.S.A. Name1@email.com NameB F AddressB CityB StateB 20002 U.S.A. Name2@email.com Text: Name Gender Addr City State PostCode Country EmailAddr NameA M AddressA CityA StateA 10001 U.S.A. Name1@email.com NameB F AddressB CityB StateB 20002 U.S.A. Name2@email.com
Copying all tables in the active document into a new document
This example copies the tables from the current document into a new document.
If ActiveDocument.Tables.Count >= 1 Then Set oDoc1 = ActiveDocument
Set MyRange = Documents.Add.Range(Start:=0, End:=0) For Each oTable In oDoc1.Tables oTable.Range.Copy With MyRange .Paste
.Collapse Direction:=wdCollapseEnd .InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd End With Next End If
Miscellaneous tasks Changing the view
The View object includes properties and methods related to view attributes (show all, field shading, table gridlines, and so on) for a window or pane. The following example changes the view to print view.
ActiveDocument.ActiveWindow.View.Type = wdPrintView
Setting text in a header or footer
The HeaderFooter object is returned by the Headers, Footers and HeaderFooter properties. The following example changes the text of current page header.
ActiveDocument.ActiveWindow.View.SeekView = wdSeekCurrentPageHeader Selection.HeaderFooter.Range.Text = \"Header text\"
This example creates a Range object (oRange) that references the primary footer for the first section in the active document. After the Range object is set, the existing footer text is deleted. The FILENAME field is added to the footer along with two tabs and the AUTHOR field.
Set oRange = ActiveDocument.Sections(1) _ .Footers(wdHeaderFooterPrimary).Range With oRange .Delete
.Fields.Add Range:=oRange, Type:=wdFieldFileName, Text:=\"\\p\" .InsertAfter Text:=vbTab & vbTab
.Collapse Direction:=wdCollapseStart
.Fields.Add Range:=oRange, Type:=wdFieldAuthor End With
Setting options
The Options object includes properties that correspond to items in the Options dialog box (Tools menu). The following example sets three application options for Word.
With Options
.AllowDragAndDrop = True .ConfirmConversions = False .MeasurementUnit = wdPoints End With
Changing the document layout
The PageSetup contains all the page setup attributes of a document (left margin, bottom margin, paper size, and so on) as properties. The following example sets the margin values for the active document.
With ActiveDocument.PageSetup
.LeftMargin = InchesToPoints(0.75) .RightMargin = InchesToPoints(0.75) .TopMargin = InchesToPoints(1.5) .BottomMargin = InchesToPoints(1)
End With
Looping through paragraphs in a document
This example loops through all of the paragraphs in the active document. If the space before setting for a paragraph is 6 points, this example changes the spacing to 12 points.
For Each aPara In ActiveDocument.Paragraphs
If aPara.SpaceBefore = 6 Then oPara.SpaceBefore = 12 Next aPara
Customizing menus and toolbars
The CommandBar object represents both menus and toolbars. Use the CommandBars property with a menu or toolbar name to return a single CommandBar object. The Controls property returns a CommandBarControl object that refers to the items on the specified command bar. The following example adds the Double Underline command to the Formatting toolbar.
CustomizationContext = NormalTemplate CommandBars(\"Formatting\").Controls.Add _
Type:=msoControlButton, ID:=60, Before:=7
Turn on the macro recorder and customize a menu or toolbar to determine the ID value for a particular command (for example, ID 60 is the Double Underline command).
The following example adds the Word Count command to the Tools menu.
CustomizationContext = NormalTemplate CommandBars(\"Tools\").Controls.Add _
Type:=msoControlButton, ID:=792, Before:=6
[自注1] 关于上例的CommandBars(\"Tools\")
在CommandBars集合中并没有 “Tools”(见自注2),但上面的程序确实把Caption=”Word Count”的命令加到Menu Bar的 “Tools” 子菜单里了(本来也有它,不过是又加了一个)。因此只可以这样解释: CommandBars(\"BarName\")中的BarName如果不存在,就在 CommandBars(“Menu Bar”)里找它的成员,如果找到就认为CommandBars(\"BarName\")等同于CommandBars(“Menu Bar”).Controls(\"BarName\")。我实验了”File”子菜单也可以这样做。以下两个程序有同样的结果:
Dim c As CommandBarControl
For Each c In CommandBars(\"Tools\").Controls Debug.Print c.Caption Next
For Each c In CommandBars(\"Menu Bar\").Controls(\"Tools\").Controls Debug.Print c.Caption Next
注:CommandBars(\"Menu Bar\").Controls(\"Tools\")是子菜单,Control.Type= msoControlPopup,因此它还有Controls集合。
[自注2]
CommandBars集合包含的全部built-in commandbars并没有在Tools->Customize对话框Toolbars tab里都显示出来。请看以下过程的输出结果(未加过任何自定义CommandBars):
Sub ListCommandBars()
Dim cb As CommandBar, i As Integer For Each cb In CommandBars i = i + 1
Debug.Print \"(\" & i & \") \" & cb.Name Next End Sub
CustomizationContext Property ( Application/Global object )
指向一 Template or Document object 。Read/Write。Default是NormalTemplate template。你可以设置它为任何打开的Document 或它的AttachedTemplate,或任何 Global Template。
当你对menu bars, toolbars, 和 key bindings做任何增删改后,如果Close/Save文挡或模板,这些修改将会保存,从而下一次打开时仍在。例如你希望建立一自定义toolbar,置CustomizationContext = ActiveDocument,Save后每当打开这个文档时,这个Toolbar都是可用的。如果未设置这个属性,by default,它是NormalTemplate,当Quit Word时会问你,对Normal.dot的changes是否保存。如果保存,则每档打开任何文档时,这个Toolbar都是可用的,因为Normal.dot总是跟着打开的。这个属性对应于Tools->Customize对话框里New Toolbar命令或Command tab里的 “Save in” option。
This example adds the ALT+CTRL+W key combination to the FileClose command. The keyboard customization is saved in the Normal template.
CustomizationContext = NormalTemplate ‘ or = ActiveDocument 保存在文档里。 KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, _ wdKeyAlt, wdKeyW), _
KeyCategory:=wdKeyCategoryCommand, Command:=\"FileClose\"
This example adds the File Versions button to the Standard toolbar. The command bar customization is saved in the template attached to the active document.
CustomizationContext = ActiveDocument.AttachedTemplate Application.CommandBars(\"Standard\").Controls.Add _ Type:=msoControlButton, _ ID:=2522, Before:=8
Macros
Record a macro
When you're recording a macro, you can use the mouse to click commands and options, but the macro recorder doesn't record mouse movements in a document window. You need to use shortcut keys for this purpose.
Supplied macros
The following template and wizard contain macros that you may find useful in your daily work or as samples to review and modify.
To use the macros, click Open on the File menu. In the Files of type box, click All Files. Locate the file you want, double-click it, and then run the macros you want
If you find one or more of these macros useful, you can load the template as a global template and then assign the macro to a toolbar button, menu item, or shortcut key
Template Support9.dot
This template is located in Program Files\\Microsoft Office\\Office\\Macros. If it is not available, you may need to install it. This template provides macros that can be used for manipulating data, troubleshooting, and fixing problems in a document. If a warning dialog box appears after you open Support9.dot, click Enable Macros. Macro Description . Edit Conversion Options Allows you to customize unique settings for text converters and graphic filters.
Registry Options Allows you to modify Microsoft Word settings in the Windows registry.
Conversion Wizard (Batch Conversion Wizard.wiz)
The Conversion Wizard helps you convert several files at one time. To start this wizard, click New on the File menu. Click the Other Documents tab, double-click Batch Conversion Wizard, and then follow the steps in the wizard. If a warning dialog box appears after you open the Conversion Wizard, click Enable Macros.
If the wizard is not available, you may need to install it. Macro Description . StartConversionWizard Runs a wizard that helps you select and convert
multiple files from another format to Word or from Word to another format.
Auto Macros
By giving a macro a special name, you can run it automatically when you perform an operation such as starting Word or opening a document. Word recognizes the following names as automatic macros, or \"auto\" macros.
Macro name When it runs . AutoExec When you start Word or load a global template AutoNew Each time you create a new document AutoOpen Each time you open an existing document AutoClose Each time you close a document
AutoExit When you quit Word or unload a global template
Auto macros in code modules are recognized if either of the following conditions are true.
The module is named after the auto macro (for example, AutoExec) and it contains a
procedure named \"Main.\"
A procedure in any module is named after the auto macro.
Just like other macros, auto macros can be stored in the Normal template, another template, or a document. In order for an auto macro to run, it must be either in the Normal template, in the active document, or in the template on which the active document is based. The only exception is the AutoExec macro, which will not run automatically unless it is stored in one of the following: the Normal template, a template that is loaded globally through the
Templates and Add-Ins dialog box, or a global template stored in the folder specified as the Startup folder.
In the case of a naming conflict (multiple auto macros with the same name), Word runs the auto macro stored in the closest context. For example, if you create an AutoClose macro in a document and the attached template, only the auto macro stored in the document will execute. If you create an AutoNew macro in the normal template, the macro will run if a macro named AutoNew doesn't exist in the document or the attached template.
Note You can hold down the SHIFT key to prevent auto macros from running. For example, if you create a new document based on a template that contains an AutoNew macro, you can
prevent the AutoNew macro from running by holding down SHIFT when you click OK in the New
dialog box (File menu) and continuing to hold down SHIFT until the new document is displayed. In a macro that might trigger an auto macro, you can use the following instruction to prevent auto macros from running:
WordBasic.DisableAutoMacros
Modifying a Word Command
You can modify most Word commands by turning them into macros. For example, you can modify the Open command on the File menu so that instead of displaying a list of Word document files (files ending with the .doc file name extension), Word displays every file in the current folder.
To display the list of built-in Word commands in the Macro dialog box, you select Word
Commands in the Macros In box. Every menu command and every command available on a toolbar or through shortcut keys is listed. Menu commands begin with the menu name associated with the command. For example, the Save command on the File menu is listed as FileSave.
You can replace a Word command with a macro by giving a macro the same name as a Word
command. For example, if you create a macro named \"FileSave,\" Word runs the macro when you
choose Save from the File menu, click the Save toolbar button, or press the FileSave shortcut key combination.
This example takes you through the steps needed to modify the FileSave command.
1. On the Tools menu, point to Macro, and then click Macros. 2. In the Macros In box, select Word Commands. 3. In the Macro Name box, select FileSave.
4. In the Macros In box, select a template or document location to store the macro. For
example, select Normal.dot (Global Template) to create a global macro (the FileSave command will be modified for all documents). 5. Click the Create button.
The FileSave macro appears as shown below.
Sub FileSave() '
' FileSave Macro
' Saves the active document or template '
ActiveDocument.Save
End Sub
You can add additional instructions or remove the existing ActiveDocument.Save instruction. Now every time the FileSave command runs, your FileSave macro runs instead of the word
command. To restore the original FileSave functionality, you need to rename or delete your FileSave macro.
Note You can also replace a Word command by creating a code module named after a Word command (for example, FileSave) with a subroutine named Main.
Assign a shortcut key to a macro or command
在交互式环境给Macro或Command指定Shortcut Keys:
1. Tools -> Customize ,打开Customize对话框。 2. 按 3. 在Categories列表中选择一Category,如File,Edit,…或All Commands(包括File,Edit,…以 及所有的Word Commands),或Macros,Styles,Fonts,AutoText,Symbols。 4. 在撒:Save Changes in框选择一文件:document或template(包括:Normal.dot)。 5. 在Commands列表选择一Command,Macrro,Style,Font,…,or Symbol。 6. 此时,在Current keys框会显示对该Command以及指定的Shortcut keys(可以不止一组)。 7. 你现在可以在Press New Shortcut Key框指定新Shortcut key,如果和已有的重复了,会在下 面告诉你它已被指定给哪个Command了。你可更改重新按。如果仍坚持用它也行(一旦Assign就取消了原来的指定)。 8. 按 Assign后就有效。到Save/Close文档或模板时如果Save,就变成永久性的了。 在Customize Keyboard对话框里也能Remove已指定的shortcut keys。用 注:Normal.dot中的命令及其Shortcut keys对任何.doc都是可用的。当你Save文档时,Custom short keys也会保存再你的.doc里。但若在Customize Keyboard对话框里Remove你的.doc所继承的shortcut keys,此后该shortcut keys对你的这个.doc将不再起作用,虽然该shortcut keys及所联系的Macro仍在Normal.dot里。 KeyBindings Property (Application/Gloabal object) Returns a KeyBindings collection that represents customized key assignments, which include a key code, a key category, and a command, in the specified CustomizationContext. Read-only. 不包括对Built-in Commands指定的Built-in shortcut keys,但包括对Built-in Commands指定的Custom keys。 KeyBindings Collection Object A collection of KeyBinding objects that represent the custom key assignments in the current context(即由CustomizationContext属性指定的)。 下例把NormalTemplate里保存的所有 Customized Shortcut keys及相应的命令显示在当前文档当前Selection处: Dim aKey as KeyBinding CustomizationContext = NormalTemplate For Each aKey In KeyBindings Selection.InsertAfter aKey.Command & vbTab & aKey.KeyString & vbCr Selection.Collapse Direction:=wdCollapseEnd Next aKey Use the KeyBindings.Add method to add a KeyBinding object to the KeyBindings collection. The following example adds the CTRL+ALT+H key combination to the Heading 1 style in the active document. CustomizationContext = ActiveDocument KeyBindings.Add _ KeyCategory:=wdKeyCategoryStyle, _ Command:=\"Heading 1\ KeyCode:=BuildKeyCode(wdKeyControl, wdKeyAlt, wdKeyH) Use KeyBindings(index), where index is the index number, to return a single KeyBinding object. KeyBindings collection 属性:Count,Context 方法:Item, Add, Key, ClearAll Context属性:返回Document or Template,即该custom shortcut key 存储在哪儿。 如果是built-in shortcut ket,则返回 Application object. Read-only. ClearAll方法:keybindings.ClearAll相当于交互式下的 Returns a KeyBinding object that represents the specified custom shortcut key. If the key doesn't exist, this method returns Nothing. This example determines whether the CTRL+SHIFT+A key combination is part of the KeyBindings collection. CustomizationContext = NormalTemplate Set myKey = KeyBindings.Key(BuildKeyCode(wdKeyControl,wdKeyShift,wdKeyA)) If myKey Is Nothing Then MsgBox \"Key is not in the KeyBindings collection\" End If 附:BuildKeyCode Method (Application/Global object) Returns a unique number for the specified key combination. Syntax: BuildKeyCode(Arg1, Arg2, Arg3, Arg4) Arg1 Required Long. A key you specify by using one of the WdKey constants. Arg2 – Arg4 Optional Variant. A key you specify by using one of the WdKey constants. WdKey constants: wdKeyAlt(1024),wdKeyControl(512),wdKeyShift(256), wdKeyF1(112)-wdKeyF16(127), wdKey0(48)–wdKey9(57),wdKeyA(65)–wdKeyZ(90), wdKeySpacebar(32), wdKeySemiColon(186)… (好多是用其Ascii码) KeyBinding object 属性:Command,CommandParameter,KeyCategory,KeyCode,KeyString,Protected,Context 方法:Clear,Rebind,Execute,Disable Storing values when a macro ends When a macro ends, the values stored in its variables aren't automatically saved to disk. If a macro needs to preserve a value, it must store that value outside itself before the macro execution is completed. Document variables Document variables allow you to store values as part of a document or a template. For example, you might store macro values in the document or template where the macro resides. You can add variables to a document or template using the Add method of the Variables collection. The following example saves a document variable in the same location as the macro that is running (document or template) using the ThisDocument property. ThisDocument.Variables.Add Name:=\"Age\ The following example uses the Value property with a Variable object to return the value of a document variable. num = ThisDocument.Variables(\"Age\").Value Note You can use the DOCVARIABLE field to insert a document variable into a document. Document properties Like document variables, document properties allow you to store values as part of a document or a template. Document properties can be viewed in the Properties dialog box (File menu). The Word object model breaks document properties into two groups: built-in and custom. Custom document properties include the properties shown on the Custom tab in the Properties dialog box. Built-in document properties include the properties on all the tabs in the Properties dialog box except the Custom tab. To access built-in properties, use the BuiltinDocumentProperties property to return a DocumentProperties collection that includes the built-in document properties. Use the CustomDocumentProperties property to return a DocumentProperties collection that includes the custom document properties. The following example creates a custom document property named \"YourName\" in the same location as the macro that is running (document or template). ThisDocument.CustomDocumentProperties.Add Name:=\"YourName\ LinkToContent:=False, Value:=\"Joe\ Built-in document properties cannot be added to the DocumentProperties collection returned by the BuiltInDocumentProperties property. You can, however, retrieve the contents of a built-in document property or change the value of a read/write built-in document property. Note You can use the DOCPROPERTY field to insert document properties into a document. AutoText entries AutoText entries can be used to store information in a template. Unlike a document variable or property, AutoText entries can include items beyond macro variables such as formatted text or a graphic. Use the Add method with the AutoTextEntries collection to create a new AutoText entry. The following example creates an AutoText entry named \"MyText\" that contains the contents of the selection. If the following instruction is part of a template macro, the new AutoText entry is stored in the template, otherwise, the AutoText entry is stored in the template attached to the document where the instruction resides. ThisDocument.AttachedTemplate.AutoTextEntries.Add Name:=\"MyText\ Range:=Selection.Range Use the Value property with an AutoTextEntry object to retrieve the contents of an AutoText entry object. Settings files You can set and retrieve information from a settings file using the PrivateProfileString property. The structure of a Windows settings file is the same as the Windows 3.1 WIN.INI file. The following example sets the DocNum key to 1 under the DocTracker section in the Macro.ini file. System.PrivateProfileString( _ FileName:=\"C:\\My Documents\\Macro.ini\ Section:=\"DocTracker\ After running the above instruction, the Macro.ini file includes the following text. [DocTracker] DocNum=1 The PrivateProfileString property has three arguments: FileName, Section, and Key. The FileName argument is used to specify a settings file path and file name. The Section argument specifies the section name that appears between brackets before the associated keys (don't include the brackets with section name). The Key argument specifies the key name which is followed by an equal sign (=) and the setting. Use the same PrivateProfileString property to retrieve a setting from a settings file. The following example retrieves the DocNum setting under the DocTracker section in the Macro.ini file. num = System.PrivateProfileString( _ FileName:=\"C:\\My Documents\\Macro.ini\ Section:=\"DocTracker\ Windows registry You can set and retrieve information from the Windows registry using the PrivateProfileString property. The following example retrieves the Word 2000 program directory from the Windows registry. aSec = \"HKEY_CURRENT_USER\\Software\\Microsoft\" _ & \"\\Office\\9.0\\Word\\Options\" programDir = System.PrivateProfileString(FileName:=\"\ Section:=aSec, Key:=\"PROGRAMDIR\") MsgBox programDir The PrivateProfileString property has three arguments: FileName, Section, and Key. To return or set a value for a registry entry, specify an empty string (\"\") for the FileName argument. The Section argument should be the complete path to the registry subkey. The Key argument should be the name of an entry in the subkey specified by Section. You can also set information in the Windows registry using the following PrivateProfileString syntax: System.PrivateProfileString(FileName, Section, Key) = value The following example sets the DOC-PATH entry to “C:\\” in the Options subkey for Word 9.0 in the Windows registry. aSec = \"HKEY_CURRENT_USER\\Software\\Microsoft\" _ & \"\\Office\\9.0\\Word\\Options\" System.PrivateProfileString(FileName:=\"\ Section:=aSec, Key:=\"DOC-PATH\") = \"C:\\\" Communicating with other applications In addition to working with Word data, you may want your application to exchange data with other applications, such as Microsoft Excel, PowerPoint, or Access. You can communicate with other applications by using Automation (formerly OLE Automation) or dynamic data exchange (DDE). Tip For detailed information about using Automation to control applications from Word, see How to obtain the Microsoft Office 2000/Visual Basic Programmer's Guide. Automating Word from another application Automation allows you to return, edit, and export data by referencing another application's objects, properties, and methods. Application objects that can be referenced by another application are called Automation objects. The first step toward making Word available to another application for Automation is to make a reference to the Word Application object. In Visual Basic, you use the CreateObject or GetObject function to return a reference to the Word Application object. For example, in a Microsoft Excel procedure, you could use the following instruction. Set wrd = CreateObject(\"Word.Application\") This instruction makes the Application object in Word available for Automation. Using the objects, properties, and methods of the Word Application object, you can control Word. For example, the following instruction creates a new Word document. wrd.Documents.Add The CreateObject function starts a Word session that Automation will not close when the object variable that references the Application object expires. Setting the object reference to the Nothing keyword will not close Word. Instead, use the Quit method to close the Word application. The following Microsoft Excel example displays the Word startup path. The Quit method is used to close the new instance of Word after the startup path is displayed. Set wrd = CreateObject(\"Word.Application\") MsgBox wrd.Options.DefaultFilePath(wdStartupPath) wrd.Quit Automating another application from Word To exchange data with another application using Automation from Word, you first obtain a reference to the application using the CreateObject or GetObject function. Then, using the objects, properties, and methods of the other application, you add, change, or delete information. When you finish making your changes, close the application. The following Word example displays the Microsoft Excel startup path. You can use the Set statement with the Nothing keyword to clear an object variable, which has the same effect as closing the application. Set myobject = CreateObject(\"Excel.Application\") MsgBox myobject.StartupPath Set myobject = Nothing Using dynamic data exchange (DDE) If an application doesn't support Automation, DDE may be an alternative. DDE is a protocol that permits two applications to communicate by continuously and automatically exchanging data through a DDE \"channel.\" To control a DDE conversation between two applications, you establish a channel, select a topic, request and send data, and then close the channel. The following table lists the tasks that Word performs with DDE and the methods used to control each task in Visual Basic. Using DAO from Microsoft Word You can use Data Access Objects (DAO) properties, objects, and methods the same way you reference and use Microsoft Word properties, objects, and methods. After you establish a reference to the DAO object library, you can open databases, design and run queries to extract a set of records, and bring the results back to Word. Referencing DAO Before you can use DAO, you must establish a reference to the DAO object library. Use the following steps to establish a reference to the DAO object library. 1. Switch to the Visual Basic Editor. 2. On the Tools menu, click References. 3. In the Available References box, click Microsoft DAO 3.6 Object Library. If you don't see Microsoft DAO 3.6 Object Library in the Available References box, run Office Professional Setup to install the Data Access Objects for Visual Basic. The Microsoft DAO 3.6 Object Library is not included with the standalone version of Word or Microsoft Office 2000 Standard. Example The following example opens the Northwind database and inserts the items from the Shippers table into the active document. Set Db = OpenDatabase _ (Name:=\"C:\\Microsoft Office\\Office\\\" _ & \"Samples\\fpnwind.mdb\") Set Rs = Db.OpenRecordset(Name:=\"Shippers\") For I = 0 To Rs.RecordCount - 1 Selection.InsertAfter Text:=Rs.Fields(1).Value Rs.MoveNext Selection.Collapse Direction:=wdCollapseEnd Selection.InsertParagraphAfter Next I Rs.Close Db.Close Use the OpenDatabase method to connect to a database and open it. After opening the database, use the OpenRecordset method to access a table or query for results. To navigate through the recordset, use the Move method. To find a specific record, use the Seek method. If you need only a subset of records instead of the entire recordset, use the CreateQueryDef method to design a customized query to select records that meet your criteria. When you finish working with a database, it's a good idea to close it using the Close method, to save memory. Note For more information about a specific DAO object, method, or property, see Data Access Objects Help. 自注:当然也可以用ADO,虽然 Help中未提到。 因篇幅问题不能全部显示,请点此查看更多更全内容