View
11
Download
0
Category
Preview:
Citation preview
WordObjectModelApplicationAddIns AutoCaptionsAutoCorrectAutoCorrectEntriesFirstLetterExceptionsHangulAndAlphabetExceptionsOtherCorrectionsExceptionsTwoInitialCapsExceptions
BrowserCaptionLabelsDialogsDictionariesDocumentsEmailOptionsEmailSignatureStyle
FileConvertersFontNames
HangulHanjaConversionDictionariesDictionary
KeyBindingKeyBindingsKeysBoundToLanguagesListGalleriesMailingLabel
SelectionBookmarksBordersCellsCharactersColumnsCommentsDocumentEditorsEndnoteOptionsEndnotesFieldsFindFontFootnoteOptionsFootnotesFormFieldsFramesHeaderFooterHTMLDivisionsHyperlinksInlineShapesPageSetupParagraphFormatParagraphs
SelectionShadingShapeRangeSmartTagsTablesWordsXMLNodeXMLNodes
SmartTagRecognizersSmartTagTypesSynonymInfoSystemTaskPanesTasksTemplateAutoTextEntriesListTemplates
TemplatesWindowsXMLNamespaces
Legend
CustomLabelsMailMessageOptionsRecentFiles
RangeRowsSectionsSentences
ObjectandcollectionObjectonly
PleaserefertothefollowingslinksformoreinformationonothernotableWordobjects
Bookmark
Subdocument
Table
NewObjectsVisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithMicrosoftOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsobjectsaddedtotheOfficeWord2003objectmodel.
NewObject Description
Break Representsindividualpage,column,andsectionbreaksinapage.
Breaks Representsacollectionofpage,column,orsectionbreaksinapage.
EditorRepresentsasingleuserwhohasbeengivenspecificpermissionstoeditportionsofadocument.
Editors
RepresentsacollectionofEditorobjectsthatrepresentsacollectionofusersorgroupsofuserswhohavebeengivenspecificpermissionstoeditportionsofadocument.
Line RepresentsanindividuallineoftextinaRectangleobject.
Lines RepresentsacollectionofLineobjectsthatrepresentsthelinesoftextinaRectangleobject.Page Representsapageinadocument.Pages Representsacollectionofpagesinadocument.
Rectangle Representsaportionoftextoragraphicinapage.
Rectangles RepresentsacollectionofRectangleobjectsinapagethatrepresentportionsoftextandgraphics.SmartTagAction Representsasingleactionforasmarttag.
SmartTagActionsRepresentsacollectionofactionsforanindividualsmarttagoratypeofsmarttag.
SmartTagRecognizer Representsaninstalledcomponentthatlabelsdatawithtypesofinformation.
SmartTagRecognizers Representsinstalledcomponentsthatlabeldatawithtypesofinformation.
SmartTagType Representsatypeofsmarttag.Asmarttagtypeisasingleiteminasmarttaglist.
SmartTagTypes RepresentsacollectionofSmartTagTypeobjects.
XMLChildNodeSuggestionRepresentsanodethatisapossiblechildelementofthecurrentelement,accordingtotheschema,butisnotguaranteedtobevalid.
XMLChildNodeSuggestionsRepresentsacollectionofelementsthatmaybevalidchildrenofthespecifiedelementaccordingtotheschema.
XMLNamespace RepresentsanindividualschemawithintheSchemaLibrary.
XMLNamespaces RepresentstheentirecollectionofschemasintheSchemaLibrary.
XMLNode RepresentsasingleXMLelementappliedtoadocument.
XMLNodesRepresentsthenodesinthetreeviewoftheXMLStructuretaskpane,whichindicatestheelementsthatauserhasappliedtoadocument.
XMLSchemaReference RepresentsanindividualXMLschemathatisattachedtoadocument.
XMLSchemaReferences Representsacollectionoftheuniquenamespacesthatareattachedtoadocument.
XSLTransform RepresentsasingleregisteredExtensibleStylesheetLanguageTransformation(XSLT)file.
XSLTransformsRepresentsalloftheExtensibleStylesheetLanguageTransformations(XSLTs)foraspecificXMLnamespace.
NewProperties(AlphabeticalList)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistspropertiesaddedtotheOfficeWord2003objectmodel(sortedalphabetically).
NewProperty Object(s)ActiveXControl SmartTagActionAlias XMLNamespace,XSLTransformAllowReadingMode OptionsAllowSaveAsXMLWithoutValidation XMLSchemaReferencesArbitraryXMLSupportAvailable ApplicationAttributes XMLNodeAutoFormatOverride DocumentAutomaticValidation XMLSchemaReferences
BaseName XMLChildNodeSuggestion,XMLNodeBreaks PageCheckboxState SmartTagActionChildNodes XMLNodeChildNodeSuggestions Document,XMLNodeCommentsColor OptionsDataFieldIndex MappedDataFieldDefaultTransform XMLNamespaceDisplayBackgrounds ViewDocumentLibraryVersions DocumentEditors Range,SelectionEnforceStyle DocumentEnhMetaFileBits Range,SelectionExpandDocumentFragment SmartTagAction
ExpandHelp SmartTagActionFriendlyName SmartTagTypeHasChildNodes XMLNodeIgnoreMixedContent XMLSchemaReferencesIsInk CommentLayoutInCell Shape,ShapeRangeLines RectangleLineType LineListSelection SmartTagAction
NamespaceURI XMLChildNodeSuggestion,XMLNode,XMLSchemaReferenceNextRange EditorNextSibling XMLNodeNodeType XMLNodeNodeValue XMLNodeOwnerDocument XMLNodePageIndex BreakPages PaneParentNode XMLNodePermission DocumentPlaceholderText XMLNodePresentInPane SmartTagActionPreviousSibling XMLNodePrintBackgrounds OptionsPrintXMLTag OptionsRadioGroupSelection SmartTagActionReadingLayout ViewReadingLayoutActualView ViewReadingLayoutAllowMultiplePages ViewReadingLayoutSizeX DocumentReadingLayoutSizeY DocumentReadingLayoutFrozen DocumentRectangles Line,Page
RectangleType RectangleRemoveDateAndTime DocumentRevisionsBalloonPrintOrientation OptionsRevisionsBalloonShowConnectingLines ViewShadeEditableRanges ViewSharedWorkspace DocumentShowInkAnnotations ViewShowMarkupOpenSave OptionsShowPlaceholderText XMLSchemaReferencesShowXMLMarkup ViewSmartCursoring OptionsSmartDocument DocumentSmartTag XMLNodeSmartTagActions SmartTag,SmartTagTypeSmartTagRecognizers Application,SmartTagTypeSmartTagTypes ApplicationSync DocumentSyncScrollingSideBySide WindowsTextboxText SmartTagActionThumbnails WindowUnderlineValidationErrors XMLSchemaReferencesURI XMLNamespaceValidationErrorText XMLNodeValidationStatus XMLNodeXMLHideNamespaces DocumentXMLNamespaces ApplicationXMLNode SmartTagXMLNodes Document,Range,SelectionXMLParentNode Range,SelectionXMLSaveDataOnly DocumentXMLSaveThroughXSLT DocumentXMLSchemaReference XMLChildNodeSuggestionXMLSchemaReferences Document
XMLSchemaViolations DocumentXMLShowAdvancedErrors DocumentXMLUseXSLTWhenSaving DocumentXSLTransforms XMLNamespace
NewProperties(byObject)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistspropertiesaddedtotheOfficeWord2003objectmodel(sortedbyobjectname).
Object NewPropertiesArbitraryXMLSupportAvailable
Application SmartTagRecognizers,SmartTagTypes,XMLNamespacesBreak PageIndexComment IsInk
Document
AutoFormatOverride,ChildNodeSuggestions,DocumentLibraryVersions,EnforceStyle,Permission,ReadingLayoutSizeX,ReadingLayoutSizeY,ReadingLayoutFrozen,RemoveDateAndTime,SharedWorkspace,SmartDocument,Sync,XMLHideNamespaces,XMLNodes,XMLSaveDataOnly,XMLSaveThroughXSLT,XMLSchemaReferences,XMLSchemaViolations,XMLShowAdvancedErrors,XMLUseXSLTWhenSaving
Editor NextRangeLine LineType,RectanglesMappedDataField DataFieldIndex
Options
AllowReadingMode,CommentsColor,PrintBackgrounds,PrintXMLTag,RevisionsBalloonPrintOrientation,ShowMarkupOpenSave,SmartCursoring
Page Breaks,Rectangles
Pane Pages
Range Editors,EnhMetaFileBits,XMLNodes,XMLParentNodeRectangle Lines,RectangleType
Selection Editors,EnhMetaFileBits,XMLNodes,XMLParentNodeShape LayoutInCellShapeRange LayoutInCellSmartTag SmartTagActions,XMLNode
SmartTagAction
ActiveXControl,CheckboxState,ExpandDocumentFragment,ExpandHelp,ListSelection,PresentInPane,RadioGroupSelection,TextboxText
SmartTagType FriendlyName,SmartTagActions,SmartTagRecognizers
View
DisplayBackgrounds,ReadingLayout,ReadingLayoutActualView,ReadingLayoutAllowMultiplePages,RevisionsBalloonShowConnectingLines,ShadeEditableRanges,ShowInkAnnotations,ShowXMLMarkup
Window ThumbnailsWindows SyncScrollingSideBySide
XMLChildNodeSuggestion BaseName,NamespaceURI,XMLSchemaReferenceXMLNamespace Alias,DefaultTransform,URI,XSLTransforms
XMLNode
Attributes,BaseName,ChildNodes,ChildNodeSuggestions,HasChildNodes,NamespaceURI,NextSibling,NodeType,NodeValue,OwnerDocument,ParentNode,PlaceholderText,PreviousSibling,SmartTag,ValidationErrorText,ValidationStatus
XMLSchemaReference NamespaceURI
XMLSchemaReferences
AllowSaveAsXMLWithoutValidation,AutomaticValidation,IgnoreMixedContent,ShowPlaceholderText,
UnderlineValidationErrorsXSLTransform Alias
NewMethods(AlphabeticalList)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsmethodsaddedtotheOfficeWord2003objectmodel(sortedalphabetically).
NewMethod ObjectAttachToDocument XMLNamespaceBreakSideBySide WindowsCompareSideBySideWith WindowsDeleteAll EditorDeleteAllEditableRanges DocumentDeleteAllInkAnnotations DocumentGoToEditableRange Range,SelectionInsertXML Range,SelectionInstallManifest XMLNamespacesPutFocusInMailHeader ApplicationReloadActions SmartTagActionsReloadAll SmartTagTypesReloadRecognizers SmartTagRecognizersRemoveChild XMLNodeRemoveLockedStyles DocumentResetPositionsSideBySideWindowsSelectAllEditableRanges DocumentSelectNodes Document,XMLNodeSelectSingleNode Document,XMLNodeSendFaxOverInternet DocumentSetValidationError XMLNodeSmartTagsByType SmartTags
ToggleShowAllReviewers WindowTransformDocument DocumentValidate XMLNode,XMLSchemaReferences
NewMethods(byObject)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsmethodsaddedtotheOfficeWord2003objectmodel(sortedbyobjectname).
Object NewMethodApplication PutFocusInMailHeader
Document
DeleteAllEditableRanges,DeleteAllInkAnnotations,RemoveLockedStyles,SelectAllEditableRanges,SelectNodes,SelectSingleNode,SendFaxOverInternet,TransformDocument
Editor DeleteAllRange GoToEditableRange,InsertXMLSelection GoToEditableRange,InsertXMLSmartTagActions ReloadActionsSmartTagRecognizers ReloadRecognizersSmartTags SmartTagsByTypeSmartTagTypes ReloadAll
Windows BreakSideBySide,CompareSideBySideWith,ResetPositionsSideBySideWindow ToggleShowAllReviewersXMLNamespace AttachToDocumentXMLNamespaces InstallManifest
XMLNode RemoveChild,SelectNodes,SelectSingleNode,SetValidationError,ValidateXMLSchemaReferences Validate
NewEventsVisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithMicrosoftOfficeWord2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistseventsaddedtotheOfficeWord2003objectmodel.
NewEvent ObjectDocumentSync ApplicationEPostageInsertEx ApplicationSync DocumentXMLAfterInsert DocumentXMLBeforeDelete DocumentXMLSelectionChange ApplicationXMLValidationError Application
AddInsCollectionObjectMultipleobjects AddIns
AddIn
AcollectionofAddInobjectsthatrepresentsalltheadd-insavailabletoWord,regardlessofwhetherornotthey'recurrentlyloaded.TheAddInscollectionincludesglobaltemplatesorWordadd-inlibraries(WLLs)displayedintheTemplatesandAdd-insdialogbox(Toolsmenu).
UsingtheAddInsCollection
UsetheAddInspropertytoreturntheAddInscollection.Thefollowingexampledisplaysthenameandtheinstalledstateofeachavailableadd-in.
ForEachadInAddInsIfad.Installed=TrueThenMsgBoxad.Name&"isinstalled"ElseMsgBoxad.Name&"isavailablebutnotinstalled"EndIfNextad
UsetheAddmethodtoaddanadd-intothelistofavailableadd-insand(optionally)installitusingtheInstallargument.
AddIns.AddFileName:="C:\Templates\Other\Letter.dot",Install:=True
Toinstallanadd-inshowninthelistofavailableadd-ins,usetheInstalledproperty.
AddIns("Letter.dot").Installed=True
UseAddIns(index),whereindexistheadd-innameorindexnumber,toreturnasingleAddInobject.Youmustexactlymatchthespelling(butnotnecessarilythecapitalization)ofthename,asit'sshownintheTemplatesandAdd-insdialogbox.Toinstallanadd-inshowninthelistofavailableadd-ins,usetheInstalledproperty.ThefollowingexampleloadstheLetter.dottemplateasaglobaltemplate.
AddIns("Letter.dot").Installed=True
NoteIftheadd-inisnotlocatedintheUserTemplates,WorkgroupTemplates,orStartupfolder,youmustspecifythefullpathandfilenamewhenindexinganadd-inbyname.
Remarks
UsetheCompiledpropertytodeterminewhetheranAddInobjectisatemplateoraWLL.
AdjustmentsObject
Multipleobjects Adjustments
ContainsacollectionofadjustmentvaluesforthespecifiedAutoShapeorWordArtobject.Eachadjustmentvaluerepresentsonewayanadjustmenthandlecanbeadjusted.Becausesomeadjustmenthandlescanbeadjustedintwoways—forinstance,somehandlescanbeadjustedbothhorizontallyandvertically—ashapecanhavemoreadjustmentvaluesthanithasadjustmenthandles.Ashapecanhaveuptoeightadjustments.
UsingtheAdjustmentsObject
UsetheAdjustmentspropertytoreturnanAdjustmentsobject.UseAdjustments(index),whereindexistheadjustmentvalue'sindexnumber,toreturnasingleadjustmentvalue.
Differentshapeshavedifferentnumbersofadjustmentvalues,differentkindsofadjustmentschangethegeometryofashapeindifferentways,anddifferentkindsofadjustmentshavedifferentrangesofvalidvalues.
NoteBecauseeachadjustableshapehasadifferentsetofadjustments,thebestwaytoverifytheadjustmentbehaviorforaspecificshapeistomanuallycreateaninstanceoftheshape,makeadjustmentswiththemacrorecorderturnedon,andthenexaminetherecordedcode.
Thefollowingtablesummarizestherangesofvalidadjustmentvaluesfordifferenttypesofadjustments.Inmostcases,ifyouspecifyavaluethat'sbeyondtherangeofvalidvalues,theclosestvalidvaluewillbeassignedtotheadjustment.
TypeofAdjustment Validvalues
Linear(horizontalorvertical)
Generallythevalue0.0representstheleftortopedgeoftheshapeandthevalue1.0representstherightorbottomedgeoftheshape.Validvaluescorrespondtovalidadjustmentsyoucanmaketotheshapemanually.Forexample,ifyoucanonlypullanadjustmenthandlehalfwayacrosstheshapemanually,themaximumvalueforthecorrespondingadjustmentwillbe0.5.Forshapessuchascallouts,wherethevalues0.0and1.0representthelimitsoftherectangledefinedbythestartingandendingpointsofthecalloutline,negativenumbersandnumbersgreaterthan1.0arevalidvalues.
Radial Anadjustmentvalueof1.0correspondstothewidthoftheshape.Themaximumvalueis0.5,orhalfwayacrosstheshape.
Angle Valuesareexpressedindegrees.Ifyouspecifyavalueoutsidetherange–180to180,itwillbenormalizedtobewithinthatrange.
Thefollowingexampleaddsaright-arrowcallouttotheactivedocumentandsetsadjustmentvaluesforthecallout.Notethatalthoughtheshapehasonlythreeadjustmenthandles,ithasfouradjustments.Adjustmentsthreeandfourbothcorrespondtothehandlebetweentheheadandneckofthearrow.
Setrac=ActiveDocument.Shapes_.AddShape(msoShapeRightArrowCallout,10,10,250,190)Withrac.Adjustments.Item(1)=0.5'adjustswidthoftextbox.Item(2)=0.15'adjustswidthofarrowhead.Item(3)=0.8'adjustslengthofarrowhead.Item(4)=0.4'adjustswidthofarrowneckEndWith
AutoCaptionsCollectionObjectMultipleobjects AutoCaptions
AutoCaption
AcollectionofAutoCaptionobjectsthatrepresentthecaptionsthatcanbeautomaticallyaddedwhenitemssuchastables,pictures,orOLEobjectsareinsertedintoadocument.
UsingtheAutoCaptionsCollection
UsetheAutoCaptionspropertytoreturntheAutoCaptionscollection.ThefollowingexampledisplaysthenamesoftheselecteditemsintheAutoCaptiondialogbox.
ForEachautoCapInAutoCaptionsIfautoCap.AutoInsert=TrueThenMsgBoxautoCap.Name&"isconfiguredforautoinsert"EndIfNextautoCap
TheAutoCaptionscollectioncontainsallthecaptionslistedintheAutoCaptiondialogbox(Insertmenu).AutoCaptionobjectscannotbeprogrammaticallyaddedtoordeletedfromtheAutoCaptionscollection.
UseAutoCaptions(index),whereindexisthecaptionnameorindexnumber,toreturnasingleAutoCaptionobject.ThecaptionnamescorrespondtotheitemslistedintheAutoCaptiondialogbox(Insertmenu).Youmustexactlymatchthespelling(butnotnecessarilythecapitalization)ofthename,asit'sshownintheAutoCaptiondialogbox.Thefollowingexampledisplaysthecaptiontext"MicrosoftWordTable."
MsgBoxAutoCaptions("MicrosoftWordTable").CaptionLabel.Name
TheindexnumberrepresentsthepositionoftheAutoCaptionobjectinthelistofcaptionsintheAutoCaptiondialogbox.ThefollowingexampledisplaysthenameofthefirstitemselectedintheAutoCaptiondialogbox.
MsgBoxAutoCaptions(1).Name
AutoCorrectEntriesCollectionObjectAutoCorrect AutoCorrectEntries
AutoCorrectEntry
AcollectionofAutoCorrectEntryobjectsthatrepresentalltheAutoCorrectentriesavailabletoWord.TheAutoCorrectEntriescollectionincludesalltheentriesintheAutoCorrectdialogbox(Toolsmenu).
UsingtheAutoCorrectEntriesCollection
UsetheEntriespropertytoreturntheAutoCorrectEntriescollection.ThefollowingexampledisplaysthenumberofAutoCorrectEntryobjectsintheAutoCorrectEntriescollection.
MsgBoxAutoCorrect.Entries.Count
UsetheAddortheAddRichTextmethodtoaddanAutoCorrectentrytothelistofavailableentries.Thefollowingexampleaddsaplain-textAutoCorrectentryforthemisspellingoftheword"their."
AutoCorrect.Entries.AddName:="thier",Value:="their"
ThefollowingexamplecreatesanAutoCorrectentrynamed"PMO"basedonthetextandformattingoftheselection.
AutoCorrect.Entries.AddRichTextName:="PMO",Range:=Selection.Range
UseEntries(index),whereindexistheAutoCorrectentrynameorindexnumber,toreturnasingleAutoCorrectEntryobject.Youmustexactlymatchthespelling(butnotnecessarilythecapitalization)ofthename,asit'sshownunderReplaceintheAutoCorrectdialogbox.ThefollowingexamplesetsthevalueofanexistingAutoCorrectentrynamed"teh."
AutoCorrect.Entries("teh").Value="the"
ThefollowingexampledisplaysthenameandvalueofthefirstAutoCorrententry.
MsgBox"Name="&AutoCorrect.Entries(1).Name&vbCr&_"Value"&AutoCorrect.Entries(1).Value
AutoTextEntriesCollectionObjectTemplate AutoTextEntries
AutoTextEntry
AcollectionofAutoTextEntryobjectsthatrepresenttheAutoTextentriesinatemplate.TheAutoTextEntriescollectionincludesalltheentrieslistedontheAutoTexttabintheAutoCorrectdialogbox(Toolsmenu).
UsingtheAutoTextEntriesObject
UsetheAutoTextEntriespropertytoreturntheAutoTextEntriescollection.ThefollowingexampledetermineswhetheranAutoTextEntryobjectnamed"test"isintheAutoTextEntriescollection.
ForEachiInNormalTemplate.AutoTextEntriesIfLCase(i.Name)="test"ThenMsgBox"AutoTextentryexists"Nexti
UsetheAddmethodtoaddanAutoTextentrytotheAutoTextEntriescollection.ThefollowingexampleaddsanAutoTextentrynamed"Blue"basedonthetextoftheselection.
NormalTemplate.AutoTextEntries.AddName:="Blue",_Range:=Selection.Range
UseAutoTextEntries(index),whereindexistheAutoTextentrynameorindexnumber,toreturnasingleAutoTextEntryobject.Youmustexactlymatchthespelling(butnotnecessarilythecapitalization)ofthename,asit'sshownontheAutoTexttabintheAutoCorrectdialogbox.ThefollowingexamplesetsthevalueofanexistingAutoTextentrynamed"cName."
NormalTemplate.AutoTextEntries("cName").Value=_"TheJohnsonCompany"
ThefollowingexampledisplaysthenameandvalueofthefirstAutoTextentryinthetemplateattachedtotheactivedocument.
SetmyTemplate=ActiveDocument.AttachedTemplateMsgBox"Name="&myTemplate.AutoTextEntries(1).Name&vbCr_&"Value"&myTemplate.AutoTextEntries(1).Value
BookmarksCollectionObjectMultipleobjects Bookmarks
BookmarkRange
AcollectionofBookmarkobjectsthatrepresentthebookmarksinthespecifiedselection,range,ordocument.
UsingtheBookmarksCollection
UsetheBookmarkspropertytoreturntheBookmarkscollection.Thefollowingexampleensuresthatthebookmarknamed"temp"existsintheactivedocumentbeforeselectingthebookmark.
IfActiveDocument.Bookmarks.Exists("temp")=TrueThenActiveDocument.Bookmarks("temp").SelectEndIf
UsetheAddmethodtosetabookmarkforarangeinadocument.Thefollowingexamplemarkstheselectionbyaddingabookmarknamed"temp".
ActiveDocument.Bookmarks.AddName:="temp",Range:=Selection.Range
UseBookmarks(index),whereindexisthebookmarknameorindexnumber,toreturnasingleBookmarkobject.Youmustexactlymatchthespelling(butnotnecessarilythecapitalization)ofthebookmarkname.Thefollowingexampleselectsthebookmarknamed"temp"intheactivedocument.
ActiveDocument.Bookmarks("temp").Select
TheindexnumberrepresentsthepositionofthebookmarkintheSelectionorRangeobject.FortheDocumentobject,theindexnumberrepresentsthepositionofthebookmarkinthealphabeticlistofbookmarksintheBookmarksdialogbox(clickNametosortthelistofbookmarksalphabetically).ThefollowingexampledisplaysthenameofthesecondbookmarkintheBookmarkscollection.
MsgBoxActiveDocument.Bookmarks(2).Name
Remarks
TheShowHiddenpropertyeffectsthenumberofelementsintheBookmarkscollection.IfShowHiddenisTrue,hiddenbookmarksareincludedintheBookmarkscollection.
BordersCollectionObjectMultipleobjects Borders
Border
AcollectionofBorderobjectsthatrepresentthebordersofanobject.
UsingtheBordersCollection
UsetheBorderspropertytoreturntheBorderscollection.Thefollowingexampleappliesthedefaultborderaroundthefirstparagraphintheactivedocument.
ActiveDocument.Paragraphs(1).Borders.Enable=True
BorderobjectscannotbeaddedtotheBorderscollection.ThenumberofmembersintheBorderscollectionisfiniteandvariesdependingonthetypeofobject.Forexample,atablehassixelementsintheBorderscollection,whereasaparagraphhasfour.
UseBorders(index),whereindexidentifiestheborder,toreturnasingleBorderobject.IndexcanbeoneofthefollowingWdBorderTypeconstants:wdBorderBottom,wdBorderDiagonalDown,wdBorderDiagonalUp,wdBorderHorizontal,wdBorderLeft,wdBorderRight,wdBorderTop,orwdBorderVertical.Someoftheseconstantsmaynotbeavailabletoyou,dependingonthelanguagesupport(U.S.English,forexample)thatyou’veselectedorinstalled.UsetheLineStylepropertytoapplyaborderlinetoaBorderobject.Thefollowingexampleappliesadouble-lineborderbelowthefirstparagraphintheactivedocument.
WithActiveDocument.Paragraphs(1).Borders(wdBorderBottom).LineStyle=wdLineStyleDouble.LineWidth=wdLineWidth025ptEndWith
Thefollowingexampleappliesasingle-lineborderaroundthefirstcharacterintheselection.
WithSelection.Characters(1).Font.Size=36.Borders.Enable=TrueEndWith
Thefollowingexampleaddsanartborderaroundeachpageinthefirstsection.
ForEachaBorderInActiveDocument.Sections(1).BordersWithaBorder.ArtStyle=wdArtSeattle.ArtWidth=20EndWithNextaBorder
BreaksCollectionPage Breaks
BreakRange
Acollectionofpage,column,orsectionbreaksinapage.UsetheBreakscollectionandtherelatedobjectsandpropertiestoprogrammaticallydefinepagelayoutinadocument.
UsingtheBreaksCollection
UsetheBreakspropertytoreturnaBreakscollection.Thefollowingexamplereturnsthebreaksinthefirstpageoftheactivedocument.
DimobjBreaksAsBreaks
SetobjBreaks=ActiveDocument.ActiveWindow_.Panes(1).Pages(1).Breaks
CanvasShapesCollectionMultipleobjects CanvasShapes
ShapeMultipleobjects
Representstheshapesinadrawingcanvas.
UsingtheCanvasShapescollection
UsetheCanvasItemspropertyofeitheraShapeorShapeRangeobjecttoreturnaCanvasShapescollection.Toaddshapestoadrawingcanvas,usethefollowingmethodsoftheCanvasShapescollection:AddCallout,AddConnectorAddCurve,AddLabel,AddLine,AddPicture,AddPolyline,AddShape,AddTextbox,AddTextEffect,orBuildFreeForm.Thefollowingexampleaddsadrawingcanvastotheactivedocumentandthenaddsthreeshapestothedrawingcanvas.
SubAddCanvasShapes()DimshpCanvasAsShapeDimshpCanvasShapesAsCanvasShapesDimshpCnvItemAsShape
'AddsanewcanvastothedocumentSetshpCanvas=ActiveDocument.Shapes_.AddCanvas(Left:=100,Top:=75,_Width:=50,Height:=75)SetshpCanvasShapes=shpCanvas.CanvasItems
'AddsshapestotheCanvasShapescollectionWithshpCanvasShapes.AddShapeType:=msoShapeRectangle,_Left:=0,Top:=0,Width:=50,Height:=50.AddShapeType:=msoShapeOval,_Left:=5,Top:=5,Width:=40,Height:=40.AddShapeType:=msoShapeIsoscelesTriangle,_Left:=0,Top:=25,Width:=50,Height:=50EndWithEndSub
UseCanvasItems(index),whereindexisthenameortheindexnumber,toreturnasingleshapeintheCanvasShapescollection.ThefollowingexamplesetstheLineandFillpropertiesandverticallyflipsthethirdshapeinadrawingcanvas.
SubCanvasShapeThree()WithActiveDocument.Shapes(1).CanvasItems(3).Line.ForeColor.RGB=RGB(50,0,255).Fill.ForeColor.RGB=RGB(50,0,255).FlipmsoFlipVerticalEndWith
EndSub
Eachshapeisassignedadefaultnamewhenitiscreated.Forexample,ifyouaddthreedifferentshapestoadocument,theymightbenamedRectangle2,TextBox3,andOval4.UsetheNamepropertytoreferencethedefaultnameortoassignamoremeaningfulnametoashape.
CaptionLabelsCollectionObjectMultipleobjects CaptionLabels
CaptionLabel
AcollectionofCaptionLabelobjectsthatrepresenttheavailablecaptionlabels.TheitemsintheCaptionLabelscollectionarelistedintheLabelboxintheCaptiondialogbox(Insertmenu).
UsingtheCaptionLabelsCollection
UsetheCaptionLabelspropertytoreturntheCaptionLabelscollection.Bydefault,theCaptionLabelscollectionincludesthethreebuilt-incaptionlabels:Figure,Table,andEquation.
UsetheAddmethodtoaddacustomcaptionlabel.Thefollowingexampleaddsacaptionlabelnamed"Photo."
CaptionLabels.AddName:="Photo"
UseCaptionLabels(index),whereindexisthecaptionlabelnameorindexnumber,toreturnasingleCaptionLabelobject.ThefollowingexamplesetsthenumberingstylefortheFigurecaptionlabel.
CaptionLabels("Figure").NumberStyle=_wdCaptionNumberStyleLowercaseLetter
TheindexnumberrepresentsthepositionofthecaptionlabelintheCaptionLabelscollection.Thefollowingexampledisplaysthefirstcaptionlabel.
MsgBoxCaptionLabels(1).Name
CellsCollectionObjectMultipleobjects Cells
Multipleobjects
AcollectionofCellobjectsinatablecolumn,tablerow,selection,orrange.
UsingtheCellsObject
UsetheCellspropertytoreturntheCellscollection.Thefollowingexampleformatsthecellsinthefirstrowintableoneintheactivedocumenttobe30pointswide.
ActiveDocument.Tables(1).Rows(1).Cells.Width=30
Thefollowingexamplereturnsthenumberofcellsinthecurrentrow.
num=Selection.Rows(1).Cells.Count
UsetheAddmethodtoaddaCellobjecttotheCellscollection.YoucanalsousetheInsertCellsmethodoftheSelectionobjecttoinsertnewcells.ThefollowingexampleaddsacellbeforethefirstcellinmyTable.
SetmyTable=ActiveDocument.Tables(1)myTable.Range.Cells.AddBeforeCell:=myTable.Cell(1,1)
UseCell(row,column),whererowistherownumberandcolumnisthecolumnnumber,orCells(index),whereindexistheindexnumber,toreturnaCellobject.Thefollowingexampleappliesshadingtothesecondcellinthefirstrowintableone.
SetmyCell=ActiveDocument.Tables(1).Cell(Row:=1,Column:=2)myCell.Shading.Texture=wdTexture20Percent
Thefollowingexampleappliesshadingtothefirstcellinthefirstrow.
ActiveDocument.Tables(1).Rows(1).Cells(1).Shading_.Texture=wdTexture20Percent
Remarks
UsetheAddmethodwiththeRowsorColumnscollectiontoaddaroworcolumnofcells.Thefollowingexampleaddsacolumntothefirsttableintheactivedocumentandtheninsertsnumbersintothefirstcolumn.
SetmyTable=ActiveDocument.Tables(1)SetaColumn=myTable.Columns.Add(BeforeColumn:=myTable.Columns(1))ForEachaCellInaColumn.CellsaCell.Range.DeleteaCell.Range.InsertAfternum+1num=num+1NextaCell
ShowAll
CharactersCollectionObjectMultipleobjects Characters
RangeMultipleobjects
Acollectionofcharactersinaselection,range,ordocument.ThereisnoCharacterobject;instead,eachitemintheCharacterscollectionisaRangeobjectthatrepresentsonecharacter.
UsingtheCharactersCollection
UsetheCharacterspropertytoreturntheCharacterscollection.Thefollowingexampledisplayshowmanycharactersareselected.
MsgBoxSelection.Characters.Count&"charactersareselected"
UseCharacters(index),whereindexistheindexnumber,toreturnaRangeobjectthatrepresentsonecharacter.TheindexnumberrepresentsthepositionofacharacterintheCharacterscollection.Thefollowingexampleformatsthefirstletterintheselectionas24-pointbold.
WithSelection.Characters(1).Bold=True.Font.Size=24EndWith
Remarks
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
AnAddmethodisn'tavailablefortheCharacterscollection.Instead,usetheInsertAfterorInsertBeforemethodtoaddcharacterstoaRangeobject.Thefollowingexampleinsertsanewparagraphafterthefirstparagraphintheactivedocument.
WithActiveDocument.Paragraphs(1).Range.InsertParagraphAfter.Paragraphs(2).Range.InsertBefore"NewText"EndWith
ColumnsCollectionObjectMultipleobjects Columns
Multipleobjects
AcollectionofColumnobjectsthatrepresentthecolumnsinatable.
UsingtheColumnsCollection
UsetheColumnspropertytoreturntheColumnscollection.ThefollowingexampledisplaysthenumberofColumnobjectsintheColumnscollectionforthefirsttableintheactivedocument.
MsgBoxActiveDocument.Tables(1).Columns.Count
Thefollowingexamplecreatesatablewithsixcolumnsandthreerowsandthenformatseachcolumnwithaprogressivelylarger(darker)shadingpercentage.
SetmyTable=ActiveDocument.Tables.Add(Range:=Selection.Range,_NumRows:=3,NumColumns:=6)ForEachcolInmyTable.Columnscol.Shading.Texture=2+ii=i+1Nextcol
UsetheAddmethodtoaddacolumntoatable.Thefollowingexampleaddsacolumntothefirsttableintheactivedocument,andthenitmakesthecolumnwidthsequal.
IfActiveDocument.Tables.Count>=1ThenSetmyTable=ActiveDocument.Tables(1)myTable.Columns.AddBeforeColumn:=myTable.Columns(1)myTable.Columns.DistributeWidthEndIf
UseColumns(index),whereindexistheindexnumber,toreturnasingleColumnobject.TheindexnumberrepresentsthepositionofthecolumnintheColumnscollection(countingfromlefttoright).Thefollowingexampleselectsthefirstcolumninthefirsttable.
ActiveDocument.Tables(1).Columns(1).Select
CommentsCollectionObjectMultipleobjects Comments
CommentRange
AcollectionofCommentobjectsthatrepresentthecommentsinaselection,range,ordocument.
UsingtheCommentsCollection
UsetheCommentspropertytoreturntheCommentscollection.ThefollowingexampledisplayscommentsmadebyDonFunkintheactivedocument.
ActiveDocument.ActiveWindow.View.SplitSpecial=wdPaneCommentsActiveDocument.Comments.ShowBy="DonFunk"
UsetheAddmethodtoaddacommentatthespecifiedrange.Thefollowingexampleaddsacommentimmediatelyaftertheselection.
Selection.CollapseDirection:=wdCollapseEndActiveDocument.Comments.AddRange:=Selection.Range,_Text:="reviewthis"
UseComments(index),whereindexistheindexnumber,toreturnasingleCommentobject.Theindexnumberrepresentsthepositionofthecommentinthespecifiedselection,range,ordocument.Thefollowingexampledisplaystheauthorofthefirstcommentintheactivedocument.
MsgBoxActiveDocument.Comments(1).Author
Thefollowingexampledisplaystheinitialsoftheauthorofthefirstcommentintheselection.
IfSelection.Comments.Count>=1ThenMsgBox_Selection.Comments(1).Initial
CustomLabelsCollectionObjectMailingLabel CustomLabels
CustomLabel
AcollectionofCustomLabelobjectsavailableintheLabelOptionsdialogbox.Thiscollectionincludescustomlabelsofallprintertypes(dot-matrix,laser,andink-jetprinters).
UsingtheCustomLabelsCollection
UsetheCustomLabelspropertytoreturntheCustomLabelscollection.Thefollowingexampledisplaysthenumberofavailablecustomlabels.
MsgBoxApplication.MailingLabel.CustomLabels.Count
UsetheAddmethodtocreateacustomlabel.Thefollowingexampleaddsacustommailinglabelnamed"MyLabel"andsetsthepagesize.
SetML=_Application.MailingLabel.CustomLabels.Add(Name:="MyLabels",_DotMatrix:=False)ML.PageSize=wdCustomLabelA4
UseCustomLabels(index),whereindexisthecustomlabelnameorindexnumber,toreturnasingleCustomLabelobject.Thefollowingexamplecreatesanewdocumentwithanexistingcustomlabellayoutnamed"MyLabels."
SetML=Application.MailingLabelIfML.CustomLabels("MyLabels").Valid=TrueThenML.CreateNewDocumentName:="MyLabels"ElseMsgBox"TheMyLabelscustomlabelisnotavailable"EndIf
TheindexnumberrepresentsthepositionofthecustommailinglabelintheCustomLabelscollection.Thefollowingexampledisplaysthenameofthefirstcustommailinglabel.
IfApplication.MailingLabel.CustomLabels.Count>=1ThenMsgBoxApplication.MailingLabel.CustomLabels(1).NameEndIf
CustomPropertiesCollectionSmartTag CustomProperties
CustomProperty
AcollectionofCustomPropertyobjectsthatrepresentsthepropertiesrelatedtoasmarttag.TheCustomPropertiescollectionincludesallthesmarttagcustompropertiesinadocument.
UsingtheCustomPropertiescollection
UsethePropertiespropertytoreturnasingleCustomPropertiesobject.UsetheAddmethodoftheCustomPropertiesobjectwithtocreateacustompropertyfromwithinaMicrosoftWordVisualBasicforApplicationsproject.ThisexamplecreatesanewpropertyforthefirstsmarttagintheactivedocumentanddisplaystheXMLcodeusedforthetag.
SubAddProps()WithThisDocument.SmartTags(1).Properties.AddName:="President",Value:=TrueMsgBox"TheXMLcodeis"&.XMLEndWithEndSub
UseProperties(index)toreturnasinglepropertyforasmarttag,whereindexisthenumberoftheproperty.Thisexampledisplaysthenameandvalueofthefirstpropertyofthefirstsmarttaginthecurrentdocument.
SubReturnProps()WithThisDocument.SmartTags(1).Properties(1)MsgBox"TheSmartTagnameis:"&.Name&vbLf&.ValueEndWithEndSub
UsetheCountpropertytoreturnthenumberofcustompropertiesforasmarttag.Thisexampleloopsthroughallthesmarttagsinthecurrentdocumentandthenlistsinanewdocumentthenameandvalueofthecustompropertiesforallsmarttagsthathavecustomproperties.
SubSmartTagsProps()DimdocNewAsDocumentDimstgTagAsSmartTagDimstgPropAsCustomPropertyDimintTagAsIntegerDimintPropAsInteger
SetdocNew=Documents.Add
'CreateheadinginfoinnewdocumentWithdocNew.Content
.InsertAfter"Name"&vbTab&"Value".InsertParagraphAfterEndWith
'LoopthroughsmarttagsincurrentdocumentForintTag=1ToThisDocument.SmartTags.Count
WithThisDocument.SmartTags(intTag)
'Verifythatthecustomproperties'forsmarttagsisgreaterthanzeroIf.Properties.Count>0Then
'LoopthroughthecustompropertiesForintProp=1To.Properties.Count
'AddcustompropertynametonewdocumentdocNew.Content.InsertAfter.Properties(intProp)_.Name&vbTab&.Properties(intProp).ValuedocNew.Content.InsertParagraphAfterNextElse
'DisplaymessageiftherearenocustompropertiesMsgBox"Therearenocustompropertiesforthe"&_"smarttagsinyourdocument."EndIfEndWithNext
'ConvertthecontentinthenewdocumentintoatabledocNew.Content.SelectSelection.ConvertToTableSeparator:=wdSeparateByTabs,NumColumns:=2
EndSub
DiagramNodesCollectionDiagram DiagramNodes
DiagramNodeMultipleobjects
AcollectionofDiagramNodeobjectsthatrepresentallthenodesinadiagram.TheDiagramNodescollectioncontainsallthediagramnodesinaspecifieddiagram.
UsingtheDiagramNodescollection
UsetheNodespropertytoreturntheDiagramNodescollection.UsetheSelectAllmethodtoselectandworkwithallnodesinadiagram.Thisexampleselectsallnodesinthespecifieddiagramandfillsthemwiththespecifiedpattern.Thefollowingexampleassumesthefirstshapeintheactivedocumentisadiagram.
SubFillDiagramNodes()ActiveDocument.Shapes(1).Diagram.Nodes.SelectAllSelection.ShapeRange.Fill.PatternedmsoPatternSmallConfettiEndSub
UsetheItemmethodtoselectandworkwithasinglediagramnodeinadiagram.Thisexampleselectsthefirstnodeinthespecifieddiagramanddeletesit.Thefollowingexampleassumesthefirstshapeintheactivedocumentisadiagram.
SubFillDiagramNode()ActiveDocument.Shapes(1).Diagram.Nodes.Item(1).DeleteEndSub
DialogsCollectionObjectMultipleobjects Dialogs
Dialog
AcollectionofDialogobjectsinWord.EachDialogobjectrepresentsabuilt-inWorddialogbox.
UsingtheDialogsCollection
UsetheDialogspropertytoreturntheDialogscollection.Thefollowingexampledisplaysthenumberofavailablebuilt-indialogboxes.
MsgBoxDialogs.Count
Youcannotcreateanewbuilt-indialogboxoraddonetotheDialogscollection.UseDialogs(index),whereindexistheWdWordDialogconstantthatidentifiesthedialogbox,toreturnasingleDialogobject.Thefollowingexampledisplaysthebuilt-inOpendialogbox.
dlgAnswer=Dialogs(wdDialogFileOpen).Show
Formoreinformation,seeDisplayingbuilt-inWorddialogboxes.
DictionariesCollectionObjectMultipleobjects Dictionaries
Dictionary
AcollectionofDictionaryobjectsthatincludestheactivecustomspellingdictionaries.
UsingtheDictionariesCollection
UsetheCustomDictionariespropertytoreturnthecollectionofcurrentlyactivecustomdictionaries.Thefollowingexampledisplaysthenamesofalltheactivecustomdictionaries.
ForEachdInCustomDictionariesMsgboxd.NameNextd
UsetheAddmethodtoaddanewcustomdictionarytothecollectionofactivecustomdictionaries.Ifthereisn'tafilewiththenamespecifiedbyFileName,Wordcreatesit.Thefollowingexampleadds"MyCustom.dic"tothecollectionofcustomdictionaries.
CustomDictionaries.AddFileName:="MyCustom.dic"
UsetheClearAllmethodtounloadallcustomdictionaries.Note,however,thatthismethoddoesn'tdeletethedictionaryfiles.Afteryouusethismethod,thenumberofcustomdictionariesinthecollectionis0(zero).Thefollowingexampleclearsthecustomdictionariesandcreatesanewcustomdictionaryfile.Thenewdictionaryissetastheactivecustomdictionary,towhichWordwillautomaticallyaddanynewwordsitencounters.
WithCustomDictionaries.ClearAll.AddFileName:="MyCustom.dic".ActiveCustomDictionary=CustomDictionaries(1)EndWith
Remarks
YousetthecustomdictionarytowhichnewwordsareaddedbyusingtheActiveCustomDictionaryproperty.Ifyoutrytosetthispropertytoadictionarythatisn'tacustomdictionary,anerroroccurs.
TheMaximumpropertyreturnsthemaximumnumberofsimultaneouscustomspellingdictionariesthattheapplicationcansupport.ForWord,thismaximumis10.
DocumentsCollectionObjectMultipleobjects Documents
DocumentMultipleobjects
AcollectionofalltheDocumentobjectsthatarecurrentlyopeninWord.
UsingtheDocumentsCollection
UsetheDocumentspropertytoreturntheDocumentscollection.Thefollowingexampledisplaysthenamesoftheopendocuments.
ForEachaDocInDocumentsaName=aName&aDoc.Name&vbCrNextaDocMsgBoxaName
UsetheAddmethodtocreateanewemptydocumentandaddittotheDocumentscollection.ThefollowingexamplecreatesanewdocumentbasedontheNormaltemplate.
Documents.Add
UsetheOpenmethodtoopenafile.Thefollowingexampleopensthedocumentnamed"Sales.doc."
Documents.OpenFileName:="C:\MyDocuments\Sales.doc"
UseDocuments(index),whereindexisthedocumentnameorindexnumbertoreturnasingleDocumentobject.Thefollowinginstructionclosesthedocumentnamed"Report.doc"withoutsavingchanges.
Documents("Report.doc").CloseSaveChanges:=wdDoNotSaveChanges
TheindexnumberrepresentsthepositionofthedocumentintheDocumentscollection.ThefollowingexampleactivatesthefirstdocumentintheDocumentscollection.
Documents(1).Activate
Remarks
ThefollowingexampleenumeratestheDocumentscollectiontodeterminewhetherthedocumentnamed"Report.doc"isopen.IfthisdocumentiscontainedintheDocumentscollection,thedocumentisactivated;otherwise,it'sopened.
ForEachdocInDocumentsIfdoc.Name="Report.doc"Thenfound=TrueNextdocIffoundTrueThenDocuments.OpenFileName:="C:\Documents\Report.doc"ElseDocuments("Report.doc").ActivateEndIf
EditorsCollectionMultipleobjects Editors
EditorRange
AcollectionofEditorobjectsthatrepresentsacollectionofusersorgroupsofuserswhohavebeengivenspecificpermissionstoeditportionsofadocument.
UsingtheEditorsCollection
UsetheAddmethodtogiveaspecifieduserorgrouppermissiontomodifyarangeorselectionwithinadocument.Thefollowingexamplegivesthecurrentusereditingpermissiontomodifytheactiveselection.
DimobjEditorAsEditor
SetobjEditor=Selection.Editors.Add(wdEditorCurrent)
EmailSignatureEntriesCollectionEmailSignature EmailSignatureEntries
EmailSignatureEntry
AcollectionofEmailSignatureEntryobjectsthatrepresentsallthee-mailsignatureentriesavailabletoWord.
UsingtheEmailSignatureEntriescollection
UsetheEmailSignatureEntriespropertytoreturntheEmailSignatureEntriescollection.UsetheAddmethodoftheEmailSignatureEntriesobjecttoaddane-mailsignaturetoWord.Thefollowingexamplecreatesanewe-mailsignatureentrybasedontheauthor'snameandaselectionintheactivedocument,andthenitsetsthenewsignatureentryasthedefaulte-mailsignaturetousefornewmessages.
SubNewEmailSignature()WithApplication.EmailOptions.EmailSignature.EmailSignatureEntries.Add"JeffSmith",Selection.Range.NewMessageSignature="JeffSmith"EndWithEndSub
EndnotesCollectionObjectMultipleobjects Endnotes
Range
AcollectionofEndnoteobjectsthatrepresentsalltheendnotesinaselection,range,ordocument.
UsingtheEndnotesCollection
UsetheEndnotespropertytoreturntheEndnotescollection.Thefollowingexamplesetsthelocationofendnotesintheactivedocument.
ActiveDocument.Endnotes.Location=wdEndOfSection
UsetheAddmethodtoaddanendnotetotheEndnotescollection.Thefollowingexampleaddsanendnoteimmediatelyaftertheselection.
Selection.CollapseDirection:=wdCollapseEndActiveDocument.Endnotes.AddRange:=Selection.Range,_Text:="TheWillowTree,(LoneCreekPress,1996)."
UseEndnotes(index),whereindexistheindexnumber,toreturnasingleEndnoteobject.Theindexnumberrepresentsthepositionoftheendnoteinaselection,range,ordocument.Thefollowingexampleappliesredformattingtothefirstendnoteintheselection.
IfSelection.Endnotes.Count>=1ThenSelection.Endnotes(1).Reference.Font.ColorIndex=wdRedEndIf
FieldsCollectionObjectMultipleobjects Fields
FieldMultipleobjects
AcollectionofFieldobjectsthatrepresentallthefieldsinaselection,range,ordocument.
UsingtheFieldsCollection
UsetheFieldspropertytoreturntheFieldscollection.Thefollowingexampleupdatesallthefieldsintheselection.
Selection.Fields.Update
UsetheAddmethodtoaddafieldtotheFieldscollection.ThefollowingexampleinsertsaDATEfieldatthebeginningoftheselectionandthendisplaystheresult.
Selection.CollapseDirection:=wdCollapseStartSetmyField=ActiveDocument.Fields.Add(Range:=Selection.Range,_Type:=wdFieldDate)MsgBoxmyField.Result
UseFields(index),whereindexistheindexnumber,toreturnasingleFieldobject.Theindexnumberrepresentsthepositionofthefieldintheselection,range,ordocument.Thefollowingexampledisplaysthefieldcodeandtheresultofthefirstfieldintheactivedocument.
IfActiveDocument.Fields.Count>=1ThenMsgBox"Code="&ActiveDocument.Fields(1).Code&vbCr_&"Result="&ActiveDocument.Fields(1).Result&vbCrEndIf
Remarks
UsetheFieldspropertywithaMailMergeobjecttoreturntheMailMergeFieldscollection.
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
FileConvertersCollectionObjectMultipleobjects FileConverters
FileConverter
AcollectionofFileConverterobjectsthatrepresentallthefileconvertersavailableforopeningandsavingfiles.
UsingtheFileConvertersCollection
UsetheFileConverterspropertytoreturntheFileConverterscollection.ThefollowingexampledetermineswhetheraWordPerfect6.0converterisavailable.
ForEachconvInFileConvertersIfconv.FormatName="WordPerfect6.x"ThenMsgBox"WordPerfect6.0converterisinstalled"EndifNextconv
TheAddmethodisn'tavailablefortheFileConverterscollection.FileConverterobjectsareaddedduringinstallationofMicrosoftOfficeorbyinstallingsupplementalconverters.
UseFileConverters(index),whereindexisaclassnameorindexnumber,toreturnasingleFileConverterobject.ThefollowingexampledisplaystheextensionsassociatedwtihtheMicrosoftExcelworksheetconverter.
MsgBoxFileConverters("MSBiff").Extensions
TheindexnumberrepresentsthepositionofthefileconverterintheFileConverterscollection.Thefollowingexampledisplaystheformatnameofthefirstfileconverter.
MsgBoxFileConverters(1).FormatName
Remarks
FileconvertersforsavingdocumentsarelistedintheSaveAsdialogbox.FileconvertersforopeningdocumentsappearinadialogboxiftheConfirmconversionatOpencheckboxisselectedontheGeneraltabintheOptionsdialogbox(Toolsmenu).
FirstLetterExceptionsCollectionObjectAutoCorrect FirstLetterExceptions
FirstLetterException
AcollectionofFirstLetterExceptionobjectsthatrepresenttheabbreviationsexcludedfromautomaticcorrection.
NoteThefirstcharacterfollowingaperiodisautomaticallycapitalizedwhentheCorrectSentenceCapspropertyissettoTrue.TheFirstLetterExceptionscollectionincludesexceptionstothisbehavior(forexample,abbreviationssuchas"addr."and"apt.").
UsingtheFirstLetterExceptionsCollection
UsetheFirstLetterExceptionspropertytoreturntheFirstLetterExceptionscollection.Thefollowingexampledeletestheabbreviation"addr."ifit'sincludedintheFirstLetterExceptionscollection.
ForEachaExceptInAutoCorrect.FirstLetterExceptionsIfaExcept.Name="addr."ThenaExcept.DeleteNextaExcept
ThefollowingexamplecreatesanewdocumentandinsertsalltheAutoCorrectfirst-letterexceptionsintoit.
Documents.AddForEachaExceptInAutoCorrect.FirstLetterExceptionsWithSelection.InsertAfteraExcept.Name.InsertParagraphAfter.CollapseDirection:=wdCollapseEndEndWithNextaExcept
UsetheAddmethodtoaddanabbreviationtothelistoffirst-letterexceptions.Thefollowingexampleaddstheabbreviation"addr."tothislist.
AutoCorrect.FirstLetterExceptions.AddName:="addr."
UseFirstLetterExceptions(index),whereindexistheabbreviationortheindexnumber,toreturnasingleFirstLetterExceptionobject.Thefollowingexampledeletestheabbreviation"appt."fromtheFirstLetterExceptionscollection.
AutoCorrect.FirstLetterExceptions("appt.").Delete
ThefollowingexampledisplaysthenameofthefirstitemintheFirstLetterExceptionscollection.
MsgBoxAutoCorrect.FirstLetterExceptions(1).Name
FontNamesObjectMultipleobjects FontNames
Representsalistofthenamesofalltheavailablefonts.
UsingtheFontNamesObject
UsetheFontNames,LandscapeFontNames,orPortraitFontNamespropertytoreturntheFontNamesobject.Thefollowingexampledisplaysthenumberofportraitfontsavailable.
MsgBoxPortraitFontNames.Count&"fontsavailable"
ThisexamplelistsallthefontnamesintheFontNamesobjectattheendoftheactivedocument.
ForEachaFontInFontNamesActiveDocument.Range.InsertAfteraFont&vbCrNextaFont
UseFontNames(index),whereindexistheindexnumber,toreturnthenameofafont.ThefollowingexampledisplaysthefirstfontnameintheFontNamesobject.
MsgBoxFontNames(1)
Remarks
Youcannotaddnamestoorremovenamesfromthelistofavailablefontnames.
FootnotesCollectionObjectMultipleobjects Footnotes
Range
AcollectionofFootnoteobjectsthatrepresentallthefootnotesinaselection,range,ordocument.
UsingtheFootnotesCollection
UsetheFootnotespropertytoreturntheFootnotescollection.Thefollowingexamplechangesallofthefootnotesintheactivedocumenttoendnotes.
ActiveDocument.Footnotes.SwapWithEndnotes
UsetheAddmethodtoaddafootnotetotheFootnotescollection.Thefollowingexampleaddsafootnoteimmediatelyaftertheselection.
Selection.CollapseDirection:=wdCollapseEndActiveDocument.Footnotes.AddRange:=Selection.Range,_Text:="TheWillowTree,(LoneCreekPress,1996)."
UseFootnotes(index),whereindexistheindexnumber,toreturnasingleFootnoteobject.Theindexnumberrepresentsthepositionofthefootnoteintheselection,range,ordocument.Thefollowingexampleappliesredformattingtothefirstfootnoteintheselection.
IfSelection.Footnotes.Count>=1ThenSelection.Footnotes(1).Reference.Font.ColorIndex=wdRedEndIf
Remarks
FootnotespositionedattheendofadocumentorsectionareconsideredendnotesandareincludedintheEndnotescollection.
FormFieldsCollectionObjectMultipleobjects FormFields
FormFieldMultipleobjects
AcollectionofFormFieldobjectsthatrepresentalltheformfieldsinaselection,range,ordocument.
UsingtheFormFieldsCollection
UsetheFormFieldspropertytoreturntheFormFieldscollection.Thefollowingexamplecountsthenumberoftextboxformfieldsintheactivedocument.
ForEachaFieldInActiveDocument.FormFieldsIfaField.Type=wdFieldFormTextInputThencount=count+1NextaFieldMsgBox"Thereare"&count&"textboxesinthisdocument"
UsetheAddmethodwiththeFormFieldsobjecttoaddaformfield.Thefollowingexampleaddsacheckboxatthebeginningoftheactivedocumentandthenselectsthecheckbox.
Setffield=ActiveDocument.FormFields.Add(_Range:=ActiveDocument.Range(Start:=0,End:=0),_Type:=wdFieldFormCheckBox)ffield.CheckBox.Value=True
UseFormFields(index),whereindexisabookmarknameorindexnumber,toreturnasingleFormFieldobject.ThefollowingexamplesetstheresultoftheText1formfieldto"DonFunk."
ActiveDocument.FormFields("Text1").Result="DonFunk"
Theindexnumberrepresentsthepositionoftheformfieldintheselection,range,ordocument.Thefollowingexampledisplaysthenameofthefirstformfieldintheselection.
IfSelection.FormFields.Count>=1ThenMsgBoxSelection.FormFields(1).NameEndIf
FramesCollectionObjectMultipleobjects Frames
FrameMultipleobjects
AcollectionofFrameobjectsinaselection,range,ordocument.
UsingtheFramesCollection
UsetheFramespropertytoreturntheFramescollection.Thefollowingexampleremovesbordersfromallframesintheactivedocument.
ForEachaFrameInActiveDocument.FramesaFrame.Borders.Enable=FalseNextaFrame
UsetheAddmethodtoaddaframearoundarange.Thefollowingexampleaddsaframearoundthefirstparagraphintheactivedocument.
ActiveDocument.Frames.Add_Range:=ActiveDocument.Paragraphs(1).Range
UseFrames(index),whereindexistheindexnumber,toreturnasingleFrameobject.Theindexnumberrepresentsthepositionoftheframeintheselection,range,ordocument.Thefollowingexamplecausestexttowraparoundthefirstframeinthefirstsectionoftheactivedocument.
ActiveDocument.Sections(1).Range.Frames(1).TextWrap=True
Remarks
YoucanwraptextaroundShapeorShapeRangeobjectsbyusingtheWrapFormatproperty.YoucanpositionaShapeorShapeRangeobjectbyusingtheTopandLeftproperties.
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
GroupShapesCollectionObjectMultipleobjects GroupShapes
ShapeMultipleobjects
Representstheindividualshapeswithinagroupedshape.EachshapeisrepresentedbyaShapeobject.UsingtheItemmethodwiththisobject,youcanworkwithsingleshapeswithinagroupwithouthavingtoungroupthem.
UsingTheGroupshapesCollection
UsetheGroupItemspropertytoreturntheGroupShapescollection.UseGroupItems(index),whereindexisthenumberoftheindividualshapewithinthegroupedshape,toreturnasingleshapefromtheGroupShapescollection.Thefollowingexampleaddsthreetrianglestotheactivedocument,groupsthem,setsacolorfortheentiregroup,andthenchangesthecolorforthesecondtriangleonly.
WithActiveDocument.Shapes.AddShape(msoShapeIsoscelesTriangle,_10,10,100,100).Name="shpOne".AddShape(msoShapeIsoscelesTriangle,_150,10,100,100).Name="shpTwo".AddShape(msoShapeIsoscelesTriangle,_300,10,100,100).Name="shpThree"With.Range(Array("shpOne","shpTwo","shpThree")).Group.Fill.PresetTexturedmsoTextureBlueTissuePaper.GroupItems(2).Fill.PresetTexturedmsoTextureGreenMarbleEndWithEndWith
HangulAndAlphabetExceptionsCollectionObjectAutoCorrect HangulAndAlphabetExceptions
HangulAndAlphabetException
AcollectionofHangulAndAlphabetExceptionobjectsthatrepresentsallHangulandalphabetAutoCorrectexceptions.ThislistcorrespondstothelistofAutoCorrectexceptionsontheKoreantabintheAutoCorrectExceptionsdialogbox(AutoCorrectcommand,Toolsmenu).
UsingtheHangulAndAlphabetExceptionsCollection
UsetheHangulAndAlphabetExceptionspropertytoreturntheHangulAndAlphabetExceptionscollection.Thefollowingexampledisplaystheitemsinthiscollection.
ForEachaHanInAutoCorrect.HangulAndAlphabetExceptionsMsgBoxaHan.NameNextaHan
IfthevalueoftheHangulAndAlphabetAutoAddpropertyisTrue,wordsareautomaticallyaddedtothelistofHangulandalphabetAutoCorrectexceptions.UsetheAddmethodtoaddanitemtotheHangulAndAlphabetExceptionscollection.Thefollowingexampleadds"hello"tothelistofalphabetAutoCorrectexceptions.
AutoCorrect.HangulAndAlphabetExceptions.AddName:="hello"
UseHangulAndAlphabetExceptions(index),whereindexistheHanguloralphabetAutoCorrectexceptionnameortheindexnumber,toreturnasingleHangulAndAlphabetExceptionobject.ThefollowingexampledeletesthealphabetAutoCorrectexceptionnamed"goodbye."
AutoCorrect.HangulAndAlphabetExceptions("goodbye").Delete
TheindexnumberrepresentsthepositionofthehanguloralphabetAutoCorrectexceptionintheHangulAndAlphabetExceptionscollection.ThefollowingexampledisplaysthenameofthefirstitemintheHangulAndAlphabetExceptionscollection.
MsgBoxAutoCorrect.HangulAndAlphabetExceptions(1).Name
Remarks
FormoreinformationonusingWordwithEastAsianlanguages,seeWordfeaturesforEastAsianlanguages.
mk:@MSITStore:wdmain11.chm::/html/wdrefFeaturesAvailableInWordWhenAsianLanguagesAreEnabled.htm
HeadersFootersCollectionObjectSection HeadersFooters
HeaderFooterMultipleobjects
AcollectionofHeaderFooterobjectsthatrepresenttheheadersorfootersinthespecifiedsectionofadocument.
UsingtheHeadersFootersCollection
UsetheHeadersorFooterspropertytoreturntheHeadersFooterscollection.Thefollowingexampledisplaysthetextfromtheprimaryfooterinthefirstsectionoftheactivedocument.
WithActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary)If.Range.TextvbCrThenMsgBox.Range.TextElseMsgBox"Footerisempty"EndIfEndWith
NoteYoucannotaddHeaderFooterobjectstotheHeadersFooterscollection.
UseHeaders(index)orFooters(index),whereindexisoneoftheWdHeaderFooterIndexconstants(wdHeaderFooterEvenPages,wdHeaderFooterFirstPage,orwdHeaderFooterPrimary),toreturnasingleHeaderFooterobject.Thefollowingexamplechangesthetextofboththeprimaryheaderandtheprimaryfooterthefirstsectionoftheactivedocument.
WithActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text="Headertext".Footers(wdHeaderFooterPrimary).Range.Text="Footertext"EndWith
YoucanalsoreturnasingleHeaderFooterobjectbyusingtheHeaderFooterpropertywithaSelectionobject.
Remarks
UsetheDifferentFirstPageHeaderFooterpropertywiththePageSetupobjecttospecifyadifferentfirstpage.Thefollowingexampleinsertstextintothefirstpagefooterintheactivedocument.
WithActiveDocument.PageSetup.DifferentFirstPageHeaderFooter=True.Sections(1).Footers(wdHeaderFooterFirstPage)_.Range.InsertBefore_"WrittenbyKateEdson"EndWith
UsetheOddAndEvenPagesHeaderFooterpropertywiththePageSetupobjecttospecifydifferentoddandevenpageheadersandfooters.IftheOddAndEvenPagesHeaderFooterpropertyisTrue,youcanreturnanoddheaderorfooterbyusingwdHeaderFooterPrimary,andyoucanreturnanevenheaderorfooterbyusingwdHeaderFooterEvenPages.
UsetheAddmethodwiththePageNumbersobjecttoaddapagenumbertoaheaderorfooter.Thefollowingexampleaddspagenumberstothefirstpagefooterinthefirstsectionintheactivedocument.
WithActiveDocument.Sections(1).PageSetup.DifferentFirstPageHeaderFooter=True.Footers(wdHeaderFooterPrimary).PageNumbers.Add_FirstPage:=TrueEndWith
HeadingStylesCollectionObjectMultipleobjects HeadingStyles
HeadingStyle
AcollectionofHeadingStyleobjectsthatrepresentthestylesusedtocompileatableoffiguresortableofcontents.
UsingtheHeadingStylesCollection
UsetheHeadingStylespropertytoreturntheHeadingStylescollection.ThefollowingexampledisplaysthenumberofitemsintheHeadingStylescollectionforthefirsttableofcontentsintheactivedocument.
MsgBoxActiveDocument.TablesOfContents(1).HeadingStyles.Count
UsetheAddmethodtoaddastyletotheHeadingStylescollection.ThefollowingexampleaddsatableofcontentsatthebeginningoftheactivedocumentandthenaddstheTitlestyletothelistofstylesusedtobuildatableofcontents.
SetmyToc=ActiveDocument.TablesOfContents.Add_(Range:=ActiveDocument.Range(0,0),UseHeadingStyles:=True,_LowerHeadingLevel:=3,UpperHeadingLevel:=1)myToc.HeadingStyles.AddStyle:="Title",Level:=2
UseHeadingStyles(index),whereindexistheindexnumber,toreturnasingleHeadingStyleobject.TheindexnumberrepresentsthepositionofthestyleintheHeadingStylescollection.Thefollowingexampleadds(atthebeginningoftheactivedocument)atableoffiguresbuiltfromtheTitlestyle,andthendisplaysthenameofthefirststyleintheHeadingStylescollection.
SetmyTOF=ActiveDocument.TablesOfFigures.Add_(Range:=ActiveDocument.Range(0,0),AddedStyles:="Title")MsgBoxmyTOF.HeadingStyles(1).Style
HTMLDivisionsCollectionMultipleobjects HTMLDivisions
HTMLDivisionMultipleobjects
AcollectionofHTMLDivisionobjectsthatrepresentstheHTMLdivisionsthatexistinaWebdocument.
UsingtheHTMLDivisionscollection
UsetheHTMLDivisionspropertytoreturntheHTMLDivisionscollection.UsetheAddmethodtoaddanHTMLdivisiontoaWebdocument.ThisexampleaddsanewHTMLdivisiontotheactivedocument,addstexttothedivision,andformatsthebordersaroundthedivision.
SubNewDivision()
WithActiveDocument.HTMLDivisions.Add.Item(Index:=1).Range.Text="ThisisanewHTMLdivision."With.Item(1)With.Borders(wdBorderBottom).LineStyle=wdLineStyleTriple.LineWidth=wdLineWidth025pt.Color=wdColorRedEndWithWith.Borders(wdBorderTop).LineStyle=wdLineStyleDot.LineWidth=wdLineWidth050pt.Color=wdColorBlueEndWithWith.Borders(wdBorderLeft).LineStyle=wdLineStyleDouble.LineWidth=wdLineWidth075pt.Color=wdColorBrightGreenEndWithWith.Borders(wdBorderRight).LineStyle=wdLineStyleDashDotDot.LineWidth=wdLineWidth075pt.Color=wdColorTurquoiseEndWithEndWithEndWith
EndSub
HyperlinksCollectionObjectMultipleobjects Hyperlinks
HyperlinkMultipleobjects
RepresentsthecollectionofHyperlinkobjectsinadocument,range,orselection.
UsingtheHyperlinksCollection
UsetheHyperlinkspropertytoreturntheHyperlinkscollection.Thefollowingexamplechecksallthehyperlinksindocumentoneforalinkthatcontainstheword"Microsoft"intheaddress.Ifahyperlinkisfound,it'sactivatedwiththeFollowmethod.
ForEachhLinkInDocuments(1).HyperlinksIfInStr(hLink.Address,"Microsoft")0ThenhLink.FollowExitForEndIfNexthLink
UsetheAddmethodtocreateahyperlinkandaddittotheHyperlinkscollection.ThefollowingexamplecreatesanewhyperlinktotheMSNWebsite.
ActiveDocument.Hyperlinks.AddAddress:="http://www.msn.com/",_Anchor:=Selection.Range
UseHyperlinks(index),whereindexistheindexnumber,toreturnasingleHyperlinkobjectinadocument,range,orselection.Thefollowingexampleactivatesthefirsthyperlinkintheselection.
IfSelection.HyperLinks.Count>=1ThenSelection.HyperLinks(1).FollowEndIf
Remarks
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
IndexesCollectionObjectDocument Indexes
IndexRange
AcollectionofIndexobjectsthatrepresentsalltheindexesinthespecifieddocument.
UsingtheIndexesCollection
UsetheIndexespropertytoreturntheIndexescollection.Thefollowingexampleformatsindexesintheactivedocumentwiththeclassicformat.
ActiveDocument.Indexes.Format=wdIndexClassic
UsetheAddmethodtocreateanindexandaddittotheIndexescollection.Thefollowingexamplecreatesanindexattheendoftheactivedocument.
SetmyRange=ActiveDocument.ContentmyRange.CollapseDirection:=wdCollapseEndActiveDocument.Indexes.AddRange:=myRange,Type:=wdIndexRunin
UseIndexes(index),whereindexistheindexnumber,toreturnasingleIndexobject.TheindexnumberrepresentsthepositionoftheIndexobjectinthedocument.Thefollowingexampleupdatesthefirstindexintheactivedocument.
IfActiveDocument.Indexes.Count>=1ThenActiveDocument.Indexes(1).UpdateEndIf
InlineShapesCollectionObjectMultipleobjects InlineShapes
InlineShapeMultipleobjects
AcollectionofInlineShapeobjectsthatrepresentalltheinlineshapesinadocument,range,orselection.
UsingtheInlineShapesCollection
UsetheInlineShapespropertytoreturntheInlineShapescollection.ThefollowingexampleconvertseachinlineshapeintheactivedocumenttoaShapeobject.
ForEachiShapeInActiveDocument.InlineShapesiShape.ConvertToShapeNextiShape
UsetheNewmethodtocreateanewpictureasaninlineshape.YoucanusetheAddPictureandAddOLEObjectmethodstoaddpicturesorOLEobjectsandlinkthemtoasourcefile.UsetheAddOLEControlmethodtoaddanActiveXcontrol.
Remarks
Shapeobjectsareanchoredtoarangeoftextbutarefree-floatingandcanbepositionedanywhereonthepage.YoucanusetheConvertToInlineShapemethodandtheConvertToShapemethodtoconvertshapesfromonetypetotheother.Youcanconvertonlypictures,OLEobjects,andActiveXcontrolstoinlineshapes.
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
WhenyouopenadocumentcreatedinanearlierversionofWord,picturesareconvertedtoinlineshapes.
KeyBindingsCollectionObjectMultipleobjects KeyBindings
KeyBinding
AcollectionofKeyBindingobjectsthatrepresentthecustomkeyassignmentsinthecurrentcontext.CustomkeyassignmentsaremadeintheCustomizeKeyboarddialogbox.
UsingtheKeyBindingsCollection
UsetheKeyBindingspropertytoreturntheKeyBindingscollection.ThefollowingexampleinsertsaftertheselectionthecommandnameandkeycombinationforeachitemintheKeyBindingscollection.
CustomizationContext=NormalTemplateForEachaKeyInKeyBindingsSelection.InsertAfteraKey.Command&vbTab_&aKey.KeyString&vbCrSelection.CollapseDirection:=wdCollapseEndNextaKey
UsetheAddmethodtoaddaKeyBindingobjecttotheKeyBindingscollection.ThefollowingexampleaddstheCTRL+ALT+HkeycombinationtotheHeading1styleintheactivedocument.
CustomizationContext=ActiveDocumentKeyBindings.AddKeyCategory:=wdKeyCategoryStyle,_Command:="Heading1",_KeyCode:=BuildKeyCode(wdKeyControl,wdKeyAlt,wdKeyH)
UseKeyBindings(index),whereindexistheindexnumber,toreturnasingleKeyBindingobject.ThefollowingexampledisplaysthecommandassociatedwiththefirstKeyBindingobjectintheKeyBindingscollection.
MsgBoxKeyBindings(1).Command
KeysBoundToCollectionObjectMultipleobjects KeysBoundTo
KeyBinding
AcollectionofKeyBindingobjectsassignedtoacommand,style,macro,orotheriteminthecurrentcontext.
UsingtheKeysBoundToCollection
UsetheKeysBoundTopropertytoreturntheKeysBoundTocollection.ThefollowingexampledisplaysthekeycombinationsassignedtotheFileNewcommandintheNormaltemplate.
CustomizationContext=NormalTemplateForEachmyKeyInKeysBoundTo(KeyCategory:=wdKeyCategoryCommand,_Command:="FileNew")myStr=myStr&myKey.KeyString&vbCrNextmyKeyMsgBoxmyStr
Thefollowingexampledisplaysthenameofthedocumentortemplatewherethekeysforthemacronamed"Macro1"arestored.
Setkb=KeysBoundTo(KeyCategory:=wdKeyCategoryMacro,_Command:="Macro1")MsgBoxkb.Context.Name
LanguagesCollectionObjectMultipleobjects Languages
LanguageDictionary
AcollectionofLanguageobjectsthatrepresentlanguagesusedforproofingorformattinginWord.
UsingtheLanguagesCollection
UsetheLanguagespropertytoreturntheLanguagescollection.Thefollowingexampledisplaysthelocalizednameforeachlanguage.
ForEachlaInLanguagesMsgboxla.NameLocalNextla
UseLanguages(index)toreturnasingleLanguageobject,whereindexcanbethevalueoftheNameproperty,thevalueoftheNameLocalproperty,oneoftheWdLanguageIDconstants,oroneoftheMsoLanguageIDconstants.(ForthelistofvalidWdLanguageIDorMsoLanguageIDconstants,seetheObjectBrowserintheVisualBasicEditor.)
Remarks
TheCountpropertyreturnsthenumberoflanguagesforwhichyoucanmarktext(languagesforwhichproofingtoolsareavailable).Tocheckproofing,youmustinstalltheappropriatetoolsforeachlanguageyouintendtocheck.Youneedbotha.dllfileandan.lexfileforeachofthefollowing:thethesaurus,spellingchecker,grammarchecker,andhyphenationtools.
IfyoumarktextaswdNoProofing,Wordskipsthemarkedtextwhenrunningaspellingorgrammarcheck.Tomarktextforaspecifiedlanguageorfornoproofing,usetheSetLanguagecommand(Toolsmenu,Languagesubmenu).
LinesCollectionRectangle Lines
LineMultipleobjects
AcollectionofLineobjectsthatrepresentsthelinesinaRectangleobjectthatisoftypewdTextRectangle.
UsingtheLinesCollection
UsetheLinespropertytoreturnacollectionoflinesforaspecifiedrectangle.Thefollowingexampleaccessesthelinesinthefirstrectangleinthefirstpageintheactivedocument.
DimobjLinesAsLines
SetobjLines=ActiveDocument.ActiveWindow.Panes(1)_.Pages(1).Rectangles(1).Lines
UsetheRectangleTypepropertyofthespecifiedRectangleobjecttodeterminewhethertheRectangleobjectisoftypewdTextRectangle.Thefollowingexamplereturnsthecollectionoflinesinthefirstrectangleinthefirstpageoftheactivedocumentifthespecifiedrectanglecontainstext.
DimobjRectangleAsRectangleDimobjLinesAsLines
SetobjRectangle=ActiveDocument.ActiveWindow_.Panes(1).Pages(1).Rectangles(1)
IfobjRectangle.RectangleType=wdTextRectangleThen_SetobjLines=objRectangle.Lines
ListEntriesCollectionObjectDropDown ListEntries
ListEntry
AcollectionofListEntryobjectsthatrepresentalltheitemsinadrop-downformfield.
UsingtheListEntriesCollection
UsetheListEntriespropertytoreturntheListEntriescollection.Thefollowingexampledisplaystheitemsthatappearintheformfieldnamed"Drop1."
ForEachleIn_ActiveDocument.FormFields("Drop1").DropDown.ListEntriesMsgBoxle.NameNextle
UsetheAddmethodtoaddanitemtoadrop-downformfield.Thefollowingexampleinsertsadrop-downformfieldandthenadds"red,""blue,"and"green"totheformfield.
SetmyField=_ActiveDocument.FormFields.Add(Range:=Selection.Range,_Type:=wdFieldFormDropDown)WithmyField.DropDown.ListEntries.AddName:="Red".AddName:="Blue".AddName:="Green"EndWith
UseListEntries(index),whereindexisthelistentrynameortheindexnumber,toreturnasingleListEntryobject.Theindexnumberrepresentsthepositionoftheentryinthedrop-downformfield(thefirstitemisindexnumber1).Thefollowingexampledeletesthe"Blue"entryfromthedrop-downformfieldnamed"Color."
ActiveDocument.FormFields("Color").DropDown_.ListEntries("Blue").Delete
Thefollowingexampledisplaysthefirstiteminthedrop-downformfieldnamed"Color."
MsgBox_ActiveDocument.FormFields("Color").DropDown.ListEntries(1).Name
ListLevelsCollectionObjectListTemplate ListLevels
ListLevelMultipleobjects
AcollectionofListLevelobjectsthatrepresentsallthelistlevelsofalisttemplate,eithertheonlylevelforabulletedornumberedlistoroneoftheninelevelsofanoutlinenumberedlist.
UsingtheListLevelsCollection
UsetheListLevelspropertytoreturntheListLevelscollection.Thefollowingexamplesetsthevariablemytemptothefirstlisttemplateintheactivedocumentandthenmodifieseachleveltouselowercaselettersforitsnumberstyle.
Setmytemp=ActiveDocument.ListTemplates(1)ForEachlevInmytemp.ListLevelslev.NumberStyle=wdListNumberStyleLowercaseLetterNextlev
UseListLevels(index),whereindexisanumberfrom1through9,toreturnasingleListLevelobject.Thefollowingexamplesetslistleveloneoflisttemplateoneintheactivedocumenttostartatfour.
ActiveDocument.ListTemplates(1).ListLevels(1).StartAt=4
NoteYoucannotaddnewlevelstoalisttemplate.
Remarks
Toapplyalistlevel,firstidentifytherangeorlist,andthenusetheApplyListTemplatemethod.Eachtabatthebeginningoftheparagraphistranslatedintoalistlevel.Forexample,aparagraphthatbeginswiththreetabswillbecomealevel-threelistparagraphaftertheApplyListTemplatemethodisused.
ListParagraphsCollectionObjectMultipleobjects ListParagraphs
ParagraphMultipleobjects
AcollectionofParagraphobjectsthatrepresentstheparagraphsofthespecifieddocument,list,orrangethathavelistformattingapplied.
UsingtheListParagraphsCollection
UsetheListParagraphspropertytoreturntheListParagraphscollection.Thefollowingexampleapplieshighlightingtothecollectionofparagraphswithlistformattingintheactivedocument.
ForEachparainActiveDocument.ListParagraphspara.Range.HighlightColorIndex=wdTurquoiseNextpara
UseListParagraphs(index),whereindexistheindexnumber,toreturnasingleParagraphobjectwithlistformatting.
Remarks
Paragraphscanhavetwotypesoflistformatting.Thefirsttypeincludesanautomaticallyaddednumberorbulletatthebeginningofeachparagraphinthelist.ThesecondtypeincludesLISTNUMfields,whichcanbeplacedanywhereinsideaparagraph.TherecanbemorethanoneLISTNUMfieldperparagraph.
Toaddlistformattingtoparagraphs,youcanusetheApplyListTemplate,ApplyBulletDefault,ApplyNumberDefault,orApplyOutlineNumberDefaultmethod.YouaccessthesemethodsthroughtheListFormatobjectforaspecifiedrange.
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
ListsCollectionObjectDocument Lists
ListMultipleobjects
AcollectionofListobjectsthatrepresentallthelistsinthespecifieddocument.
UsingtheListsCollection
UsetheListspropertytoreturntheListscollection.Thefollowingexampledisplaysthenumberofitemsineachlistintheactivedocument.
ForEachliInActiveDocument.ListsMsgBoxli.CountNumberedItemsNextli
UseLists(index),whereindexistheindexnumber,toreturnasingleListobject.Thefollowingexampleappliesthefirstlistformat(excludingNone)ontheNumberedtabintheBulletsandNumberingdialogboxtothesecondlistintheactivedocument.
Settemp1=ListGalleries(wdNumberGallery).ListTemplates(1)ActiveDocument.Lists(2).ApplyListTemplateListTemplate:=temp1
Remarks
WhenyouuseaForEach...NextlooptoenumeratetheListscollection,thelistsinadocumentarereturnedinreverseorder.Thefollowingexamplecountstheitemsforeachlistintheactivedocument,fromthebottomofthedocumentupward.
ForEachliInActiveDocument.ListsMsgBoxli.CountNumberedItemsNextli
Toaddanewlisttoadocument,usetheApplyListTemplatemethodwiththeListFormatobjectforaspecifiedrange.
YoucanmanipulatetheindividualListobjectswithinadocument,butformoreprecisecontrolyoushouldworkwiththeListFormatobject.
Picture-bulletedlistsarenotincludedintheListscollection.
ListTemplatesCollectionObjectMultipleobjects ListTemplates
ListTemplateListLevels
AcollectionofListTemplateobjectsthatrepresentthesevenpredefinedlistformatsoneachtabintheBulletsandNumberingdialogbox.
UsingtheListTemplatesCollection
UsetheListTemplatespropertytoreturntheListTemplatescollection.Thefollowingexampledisplaysamessagewiththelevelstatus(singleormultiple-level)foreachlisttemplateintheactivedocument.
ForEachltInActiveDocument.ListTemplatesMsgBox"Thisisamultiple-levellisttemplate-"_<.OutlineNumberedNextLT
UsetheAddmethodtoaddalisttemplatetothecollectioninthespecifieddocumentortemplate.Thefollowingexampleaddsanewlisttemplatetotheactivedocumentandappliesittotheselection.
SetmyLT=ActiveDocument.ListTemplates.AddSelection.Range.ListFormat.ApplyListTemplateListTemplate:=myLT
UseListTemplates(index),whereindexisanumber1through7,toreturnasinglelisttemplatefromalistgallery.Thefollowingexamplesetsanobjectvariableequaltothelisttemplateusedinthethirdlistintheactivedocument,andthenitappliesthatlisttemplatetotheselection.
Setmylt=ActiveDocument.ListTemplates(3)Selection.Range.ListFormat.ApplyListTemplateListTemplate:=mylt
NoteSomepropertiesandmethods—ConvertandAdd,forexample—won'tworkwithlisttemplatesthatareaccessedfromalistgallery.Youcanmodifytheselisttemplates,butyoucannotchangetheirlistgallerytype(wdBulletGallery,wdNumberGallery,orwdOutlineNumberGallery).
ResettingaListTemplateintheGallery
ToseewhetherthespecifiedlisttemplatecontainstheformattingbuiltintoWord,usetheModifiedpropertywiththeListGalleryobject.Toresetformattingtotheoriginallistformat,usetheResetmethodfortheListGalleryobject.
Remarks
AfteryouhavereturnedaListTemplateobject,useListLevels(index),whereindexisanumberfrom1through9,toreturnasingleListLevelobject.WithaListLevelobject,youhaveaccesstoalltheformattingpropertiesforthespecifiedlistlevel,suchasAlignment,Font,NumberFormat,NumberPosition,NumberStyle,andTrailingCharacter.
UsetheConvertmethodtoconvertamultiple-levellisttemplatetoasingle-leveltemplate.
MailMergeDataFieldsCollectionObjectMailMergeDataSource MailMergeDataFields
MailMergeDataField
AcollectionofMailMergeDataFieldobjectsthatrepresentthedatafieldsinamailmergedatasource.
UsingtheMailMergeDataFieldsCollection
UsetheDataFieldspropertytoreturntheMailMergeDataFieldscollection.Thefollowingexampledisplaysthenamesofallthefieldsintheattacheddatasource.
ForEachafieldInActiveDocument.MailMerge.DataSource.DataFieldsMsgBoxafield.NameNextafield
YoucannotaddfieldstotheMailMergeDataFieldscollection.Whenadatafieldisaddedtoadatasource,thefieldisautomaticallyincludedintheMailMergeDataFieldscollection.UsetheEditDataSourcemethodtoeditthecontentsofadatasource.Thefollowingexampleaddsadatafieldnamed"Author"toatableintheattacheddatasource.
IfActiveDocument.MailMerge.DataSource.Type=_wdMergeInfoFromWordThenActiveDocument.MailMerge.EditDataSourceWithActiveDocument.Tables(1).Columns.Add.Cell(Row:=1,Column:=.Columns.Count).Range.Text="Author"EndWithEndIf
UseDataFields(index),whereindexisthedatafieldnameortheindexnumber,toreturnasingleMailMergeDataFieldobject.Theindexnumberrepresentsthepositionofthedatafieldinthemailmergedatasource.ThefollowingexampleretrievesthefirstvaluefromtheFNamefieldinthedatasourceattachedtotheactivedocument.
first=_ActiveDocument.MailMerge.DataSource.DataFields("FName").Value
Thefollowingexampledisplaysthenameoffirstdatafieldinthedatasourceattachedtotheactivedocument.
MsgBoxActiveDocument.MailMerge.DataSource.DataFields(1).Name
MailMergeFieldNamesCollectionObjectMailMergeDataSource MailMergeFieldNames
MailMergeFieldName
AcollectionofMailMergeFieldNameobjectsthatrepresentthefieldnamesinamailmergedatasource.
UsingtheMailMergeFieldNamesCollection
UsetheFieldNamespropertytoreturntheMailMergeFieldNamescollection.Thefollowingexampledisplaysthenamesofthefieldsinthedatasourceattachedtotheactivedocument.
ForEachafieldInActiveDocument.MailMerge.DataSource.FieldNamesMsgBoxafield.NameNextafield
YoucannotaddnamestotheMailMergeFieldNamescollection.Whenafieldisaddedtoadatasource,thefieldnameisautomaticallyincludedintheMailMergeFieldNamescollection.UsetheEditDataSourcemethodtoeditthecontentsofadatasource.Thefollowingexampleaddsadatafieldnamed"Author"toatableinthedatasourceattachedtotheactivedocument.
IfActiveDocument.MailMerge.DataSource.Type=_wdMergeInfoFromWordThenActiveDocument.MailMerge.EditDataSourceWithActiveDocument.Tables(1).Columns.Add.Cell(Row:=1,Column:=.Columns.Count).Range.Text="Author"EndWithEndIf
MailMergeFieldsCollectionObjectMailMerge MailMergeFields
MailMergeFieldMultipleobjects
AcollectionofMailMergeFieldobjectsthatrepresentthemailmergerelatedfieldsinadocument.
UsingtheMailMergeFieldsCollection
UsetheFieldspropertytoreturntheMailMergeFieldscollection.ThefollowingexampleaddsanASKfieldafterthelastmailmergefieldintheactivedocument.
SetmyMMFields=ActiveDocument.MailMerge.FieldsmyMMFields(myMMFields.Count).SelectSelection.MoveRightUnit:=wdWord,Count:=1,Extend:=wdMoveActiveDocument.MailMerge.Fields.AddAskRange:=Selection.Range,_Name:="Name",Prompt:="Typeyourname",AskOnce:=True
UsetheAddmethodtoaddamergefieldtotheMailMergeFieldscollection.ThefollowingexamplereplacestheselectionwithaMiddleInitialmergefield.
ActiveDocument.MailMerge.Fields.AddRange:=Selection.Range,_Name:="MiddleInitial"
UseFields(index),whereindexistheindexnumber,toreturnasingleMailMergeFieldobject.Thefollowingexampledisplaysthefieldcodeofthefirstmailmergefieldintheactivedocument.
MsgBoxActiveDocument.MailMerge.Fields(1).Code
Remarks
TheMailMergeFieldscollectionhasadditionalmethods,suchasAddAskandAddFillIn,foraddingfieldsrelatedtoamailmergeoperation.
ShowAll
MappedDataFieldsCollectionMailMergeDataSource MappedDataFields
MappedDataField
AcollectionofMappedDataFieldobjectsthatrepresentsallthemappeddatafieldsavailableinMicrosoftWord.
UsingtheMappedDataFieldscollection
UsetheMappedDataFieldspropertyoftheMailMergeDataSourceobjecttoreturntheMappedDataFieldscollection.ThisexamplecreatesatabbedlistofthemappeddatafieldsavailableinWordandthefieldsinthedatasourcetowhichtheyaremapped.Thisexampleassumesthatthecurrentdocumentisamailmergedocumentandthatthedatasourcefieldshavecorrespondingmappeddatafields.
SubMappedFields()DimintCountAsIntegerDimdocCurrentAsDocumentDimdocNewAsDocument
OnErrorResumeNext
SetdocCurrent=ThisDocumentSetdocNew=Documents.Add
'AddleadertabtonewdocumentdocNew.Paragraphs.TabStops.Add_Position:=InchesToPoints(3.5),_Leader:=wdTabLeaderDots
WithdocCurrent.MailMerge.DataSource
'InsertheadingparagraphfortabbedcolumnsdocNew.Content.InsertAfter"WordMappedDataField"_&vbTab&"DataSourceField"
DointCount=intCount+1
'InsertWordmappeddatafieldnameandthe'correspondingdatasourcefieldnamedocNew.Content.InsertAfter.MappedDataFields(_Index:=intCount).Name&vbTab&_.MappedDataFields(Index:=intCount)_.DataFieldName
'InsertparagraphdocNew.Content.InsertParagraphAfterLoopUntilintCount=.MappedDataFields.Count
EndWith
EndSub
OtherCorrectionsExceptionsCollectionObjectAutoCorrect OtherCorrectionsExceptions
OtherCorrectionsException
AcollectionofOtherCorrectionsExceptionobjectsthatrepresentsthelistofwordsthatMicrosoftWordwon'tcorrectautomatically.ThislistcorrespondstothelistofAutoCorrectexceptionsontheOtherCorrectionstabintheAutoCorrectExceptionsdialogbox(AutoCorrectcommand,Toolsmenu).
UsingtheOtherCorrectionsExceptionsCollection
UsetheOtherCorrectionsExceptionspropertytoreturntheOtherCorrectionsExceptionscollection.Thefollowingexampledisplaystheitemsinthiscollection.
ForEachaCapInAutoCorrect.OtherCorrectionsExceptionsMsgBoxaCap.NameNextaCap
IfthevalueoftheOtherCorrectionsAutoAddpropertyisTrue,wordsareautomaticallyaddedtothelistofAutoCorrectexceptions.UsetheAddmethodtoaddanitemtotheOtherCorrectionsExceptionscollection.Thefollowingexampleadds"TipTop"tothelistofAutoCorrectexceptions.
AutoCorrect.OtherCorrectionsExceptions.AddName:="TipTop"
UseOtherCorrectionsExceptions(index),whereindexisthenameortheindexnumber,toreturnasingleOtherCorrectionsExceptionobject.Thefollowingexampledeletes"WTop"fromthelistofAutoCorrectexceptions.
AutoCorrect.OtherCorrectionsExceptions("WTop").Delete
TheindexnumberrepresentsthepositionoftheAutoCorrectexceptionintheOtherCorrectionsExceptionscollection.ThefollowingexampledisplaysthenameofthefirstitemintheOtherCorrectionsExceptionscollection.
MsgBoxAutoCorrect.OtherCorrectionsExceptions(1).Name
PageNumbersCollectionObjectHeaderFooter PageNumbers
PageNumber
AcollectionofPageNumberobjectsthatrepresentthepagenumbersinasingleheaderorfooter.
UsingthePageNumbersCollection
UsethePageNumberspropertytoreturnthePageNumberscollection.Thefollowingexamplestartspagenumberingat3forthefirstsectionintheactivedocument.
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary)_.PageNumbers.StartingNumber=3
UsetheAddmethodtoaddpagenumberstoaheaderorfooter.Thefollowingexampleaddsapagenumbertotheprimaryfooterinthefirstsection.
WithActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.Add_PageNumberAlignment:=wdAlignPageNumberLeft,_FirstPage:=FalseEndWith
Toaddorchangepagenumbersinadocumentwithmultiplesections,modifythepagenumbersineachsectionorsettheLinkToPreviouspropertytoTrue.
UsePageNumbers(index),whereindexistheindexnumber,toreturnasinglePageNumberobject.Inmostcases,aheaderorfootercontainsonlyonepagenumber,whichisindexnumber1.Thefollowingexamplecentersthefirstpagenumberintheprimaryheaderinthefirstsection.
ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary)_.PageNumbers(1).Alignment=wdAlignPageNumberCenter
PagesCollectionPane Pages
PageMultipleobjects
Acollectionofpagesinadocument.UsethePagescollectionandtherelatedobjectsandpropertiesforprogrammaticallydefiningpagelayoutinadocument.
UsingthePagesCollection
UsethePagespropertytoreturnaPagescollection.Thefollowingexampleaccessesallpagesintheactivedocument.
DimobjPagesAsPages
SetobjPage=ActiveDocument._ActiveWindow.Panes(1).Pages
UsetheItemmethodtoaccessanindividualPageobjectthatrepresentsanindividualpageinadocument.Thefollowingexampleaccessesthefirstpageintheactivedocument.
DimobjPageAsPage
SetobjPage=ActiveDocument.ActiveWindow_.Panes(1).Pages.Item(1)
PanesCollectionObjectWindow Panes
PaneMultipleobjects
AcollectionofPaneobjectsthatrepresentthewindowpanesforasinglewindow.
UsingthePanesCollection
UsethePanespropertytoreturnthePanescollection.Thefollowingexamplesplitstheactivewindowandhidestherulerforeachpane.
ActiveDocument.ActiveWindow.Split=TrueForEachaPaneInActiveDocument.ActiveWindow.PanesaPane.DisplayRulers=FalseNextaPane
UsetheAddmethodortheSplitpropertytoaddawindowpane.Thefollowingexamplesplitstheactivewindowat20percentofthecurrentwindowsize.
ActiveDocument.ActiveWindow.Panes.AddSplitVertical:=20
Thefollowingexamplesplitstheactivewindowinhalf.
ActiveDocument.ActiveWindow.Split=True
YoucanusetheSplitSpecialpropertytoshowcomments,footnotes,orendnotesinaseparatepane.
Remarks
Awindowhasmorethanonepaneifit'ssplit,oriftheactiveviewisn'tprintlayoutviewandinformationsuchasfootnotesorcommentsisdisplayed.Thefollowingexampledisplaysthefootnotepaneinnormalviewandthenpromptstheusertoclosethepane.
ActiveDocument.ActiveWindow.View.Type=wdNormalViewIfActiveDocument.Footnotes.Count>=1ThenActiveDocument.ActiveWindow.View.SplitSpecial=wdPaneFootnotesresponse=_MsgBox("Doyouwanttoclosethefootnotespane?",vbYesNo)Ifresponse=vbYesThen_ActiveDocument.ActiveWindow.ActivePane.CloseEndIf
ParagraphsCollectionObjectMultipleobjects Paragraphs
Multipleobjects
AcollectionofParagraphobjectsinaselection,range,ordocument.
UsingtheParagraphsCollection
UsetheParagraphspropertytoreturntheParagraphscollection.Thefollowingexampleformatstheselectedparagraphstobedouble-spacedandright-aligned.
WithSelection.Paragraphs.Alignment=wdAlignParagraphRight.LineSpacingRule=wdLineSpaceDoubleEndWith
UsetheAdd,InsertParagraph,InsertParagraphAfter,orInsertParagraphBeforemethodtoaddanewparagraphtoadocument.Thefollowingexampleaddsanewparagraphbeforethefirstparagraphintheselection.
Selection.Paragraphs.AddRange:=Selection.Paragraphs(1).Range
Thefollowingexamplealsoaddsaparagraphbeforethefirstparagraphintheselection.
Selection.Paragraphs(1).Range.InsertParagraphBefore
UseParagraphs(index),whereindexistheindexnumber,toreturnasingleParagraphobject.Thefollowingexamplerightalignsthefirstparagraphintheactivedocument.
ActiveDocument.Paragraphs(1).Alignment=wdAlignParagraphRight
Remarks
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.
ProofreadingErrorsCollectionObjectMultipleobjects ProofreadingErrors
RangeMultipleobjects
Acollectionofspellingandgrammaticalerrorsforthespecifieddocumentorrange.ThereisnoProofreadingErrorobject;instead,eachitemintheProofreadingErrorscollectionisaRangeobjectthatrepresentsonespellingorgrammaticalerror.
UsingtheProofreadingErrorsCollection
UsetheSpellingErrorsorGrammaticalErrorspropertytoreturntheProofreadingErrorscollection.Thefollowingexamplecountsthespellingandgrammaticalerrorsintheselectionanddisplaystheresultsinamessagebox.
Setpr1=Selection.Range.SpellingErrorssc=pr1.CountSetpr2=Selection.Range.GrammaticalErrorsgc=pr2.CountMsgbox"Spellingerrors:"&sc&vbCr_&"Grammaticalerrors:"&gc
UseSpellingErrors(index),whereindexistheindexnumber,toreturnasinglespellingerror(representedbyaRangeobject).Thefollowingexamplefindsthesecondspellingerrorintheselectionandthenselectsit.
SetmyRange=Selection.Range.SpellingErrors(2)myRange.Select
UseGrammarErrors(index),whereindexistheindexnumber,toreturnasinglegrammaticalerror(representedbyaRangeobject).Thefollowingexamplereturnsthesentencethatcontainsthefirstgrammaticalerrorintheselection.
SetmyRange=Selection.Range.GrammaticalErrors(1)MsgboxmyRange.Text
Remarks
TheCountpropertyforthiscollectioninadocumentreturnsthenumberofitemsinthemainstoryonly.TocountitemsinotherstoriesusethecollectionwiththeRangeobject.Ifallthewordsinthedocumentorrangearespelledcorrectlyandaregrammaticallycorrect,theCountpropertyfortheProofreadingErrorsobjectreturns0(zero)andtheSpellingCheckedandGrammarCheckedpropertiesreturnTrue.
ReadabilityStatisticsCollectionObjectMultipleobjects ReadabilityStatistics
ReadabilityStatistic
AcollectionofReadabilityStatisticobjectsforadocumentorrange.
UsingtheReadabilityStatisticsCollection
UsetheReadabilityStatisticspropertytoreturntheReadabilityStatisticscollection.Thefollowingexampleenumeratesthereadabilitystatisticsfortheselectionanddisplayseachoneinamessagebox.
ForeachrsinSelection.Range.ReadabilityStatisticsMsgboxrs.Name&"-"&rs.ValueNextrs
UseReadabilityStatistics(index),whereindexistheindexnumber,toreturnasingleReadabilityStatisticobject.Thestatisticsareorderedasfollows:Words,Characters,Paragraphs,Sentences,SentencesperParagraph,WordsperSentence,CharactersperWord,PassiveSentences,FleschReadingEase,andFlesch-KincaidGradeLevel.Thefollowingexamplereturnsthewordcountfortheactivedocument.
SetmyRange=ActiveDocument.Contentwordval=myRange.ReadabilityStatistics(1).ValueMsgboxwordval
RecentFilesCollectionObjectMultipleobjects RecentFiles
RecentFile
AcollectionofRecentFileobjectsthatrepresentsthefilesthathavebeenusedrecently.TheitemsintheRecentFilescollectionaredisplayedatthebottomoftheFilemenu.
UsingtheRecentFilesCollection
UsetheRecentFilespropertytoreturntheRecentFilescollection.ThefollowingexamplesetsfiveasthemaximumnumberoffilesthattheRecentFilescollectioncancontain.
RecentFiles.Maximum=5
UsetheAddmethodtoaddafiletotheRecentFilescollection.Thefollowingexampleaddstheactivedocumenttothelistofrecently-usedfiles.
IfActiveDocument.Saved=TrueThenRecentFiles.AddDocument:=ActiveDocument.FullName,_ReadOnly:=TrueEndIf
UseRecentFiles(index),whereindexistheindexnumber,toreturnasingleRecentFileobject.TheindexnumberrepresentsthepositionofthefileontheFilemenu.ThefollowingexampleopensthefirstdocumentintheRecentFilescollection.
IfRecentFiles.Count>=1ThenRecentFiles(1).Open
Remarks
TheSaveAsandOpenmethodsincludeanAddToRecentF
Recommended