Word VBA(2)

更新时间:2023-09-23 21:16:01 阅读量: IT计算机 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Microsoft Word VBA (2)

Application/Global, Documents,Templates, Tables, Cells, Bookmarks, FormFields, Variables

Windows, View, Panes

Dialogs

Application Object

注:任何Word object都有Parent,Creator,Application属性。

Obj.Parent:返回Obj的Parent object。Parent关系一般可由Object model中的层次关系看出。例如Find object的Parent是某 Range或Selection object。w

Dim r As Range

Set r = ActiveDocument.Paragraphs(1).Range

MsgBox TypeName(r.Parent) ? Document r.Select

MsgBox TypeName(Selection.Parent) ? Pane

MsgBox TypeName(Selection.Find.Parent) ? Selection MsgBox TypeName(Dialogs(2).Parent) ? Application

注: Selection object的Parent总是当前selection所在的pane object。

Obj.Creator: Long 返回建立该 object所在的application的4字符标识。对任何Obj ,Creator都返回值1297307460,即Hex “4D535744”,它是 字符串 “MSWD”的Ascii编码。Macintosh only. Obj.Application: 对任何Obj,总是返回当前的Application object。

Application object 启动Microsoft Word,建立一个Application object。再一次启动Microsoft Word,又建立一个

Application object。这两个Application objects是Word.Application class的两个Instances。 在每个Word instance中,你可以打开多个文档。虽然每个文档用一个独立的窗口显示(By default , 它的window.Visible=True),但它们属于同一 Application。你可以通过Application.Documents集合看到其中的每个文档,或者交互地通过Windows菜单看到。不同的Word instance有不同的Application.Documents集合。

Application object有 Visible属性。当交互地启动Microsoft Word时,By default它是True,当用 code启动Word(例如在Excel中或在已有的Word instance中)时,如执行:

Dim WdApp As Word.Application

Set WdApp=CreateObject(“Word.Application”) ‘建立一Word instance

By default,WdApp.Visible=False。你可以让它可见:执行语句WdApp.Visible=True。如果执行语句WdApp.Visible=False,该 Application的所有文档窗口都不可见了。(不要让自己不可见,例如执行 Application.Visible=False,因为无法再让它可见,除非它的VB Editor窗口未关,你再执行Application. Visible=True。注意,每个Word instance都可打开自己的VB Editor窗口。)

个别Document窗口可以用code(only)让它可见或不可见,使用document.Windows(1).Visible属性。注意,一个Document也能打开多个窗口,用NewWindow方法(交互式Windows->New Window),但总是包含相同的内容(容许不同的当前指针)。但通常是用单个窗口,即document.Windows(1)。

为在其他应用(如Access2000)中,参照当前的Word Application(而不建立新的Word instance),可以用以下GetObject函数:

Dim wdApp As Word.Application ? or As Object or As Variant if Word not referenced Set wdApp = GetObject( , \

如果当前Word 从未启动,上面的语句导致Err=429。于是你可写:

Dim wdApp As Word.Application On Error Resume Next

Set wdApp = GetObject( , \Select Case Err.Number

Case 0 ? Word has been started Case 429 ? Word not started yet

Set wdApp = CreateObject(\ Case Else ? other error Msgbox … End Select

注:Excel, Access, Outlook也类似,支持多个instances。但每个Access2000 instance只能打开单个.mdb。Outlook打开的Personal folders文件只依赖于 users (由User profiles指定 )。同一 user启动2个Outlook instances,内容是一样的。

Application object and Global Object

Global object Contains top-level properties and methods that don't need to be preceded by the Application property. For example, the following two statements have the same result.

Documents(1).Content.Bold = True

Application.Documents(1).Content.Bold = True

Application object的属性:

* 以下top-level properties

也是Global object的属性:

ActiveDocument, ActiveWindow, ActivePrinter, Selection

Documents,Templates,Tasks,Windows, Dialogs NormalTemplate, Options,

StatusBar(Write-only,String),ShowVisualBasicEditor, System(object,System info),SynonymInfo, PrintPreview,RecentFiles, CommandBars,FileConverters,

FontNames,LandscapeFonrNames,PortraitFontNames, IsObjectValid,

KeyBindings(Adds a shortcut key for a macro, built-in command, font, AutoText entry, style, or symbol. Saved in a template)

KeysBoundTo(Returns a KeyBindings collection), FindKey(Returns a KeyBinding object), Languages,LanguageSetting, ListGalleries,

CustomDictionaries,CustomizationContext, AddIns,AnswerWizard,Assistant,VBE, AutoCaptions,CaptionLabels,AutoCorrect, Name,Application,Creator,Parent,WordBasic

* Application object的其他属性:

Caption, UserControl,WindowState,Visible,

DisplayStatusBar(R/W,Boolean), DisplayScrollBars, DisplayScreenTips, DisplayRecentFiles, DisplayAutoCompleteTips, DisplayAlerts,ScreenUpdating, EnableCancelKey,

Language,FileSearch,MicroContainer,

MailSystem,MailMessage,EmailOptions,MAPIAvailable, FocusInmailHeader BackgroundPrintingStatus, BackgroundSavingStatus, Browser,BrowseExtraFileType,

Build,Version,CapsLock,NumLock,International, Path,PathSeparator,StartupPath, UserAddress,UserName,

Height,Left,Top,Width,UsableHeight,UsableWidth, FeatureInstall,CheckLanguage,COMAddINs, DefaultSaveFormat,DefaultTableSenarator, MouseAvailavle,MathCoprocessorAvailable,

Application object的方法:

* 以下top-level methods也是Global object的方法:

NewWindow,Repeat, BuildKeyCode,KeyString,

CleanString,CheckSpelling,GetSpellingSuggestions, Help,

ChangeFileOpenDirectory, DDEExecute,DDE…,

CentimetersToPoints,InchesToPoints,LinesToPoints,MillimetersToPoints, PicasToPoints,PixelsToPoints,

PointsToCentimeters/Inches/Picas/Pixels/Millimeters

* Application object的其他方法:

Activate,ScreenRefresh, GoForward,GoBack,Move, SubstituteFont, ResetIgnoreAll,

Run,PrintOut,Quit,Resize, OnTime,SendFax,ShowMe ListCommands, LookupNameProperties,

Keyboard,KeyboardBidi,KeyboardLatin,ToggleKeyboard,

AddAddress,GetAddress,Set/GetDefaultTheme,GetSpellingSuggestion, AutomaticChange,CheckGrammar, OrganizerCopy/Delete/Rename, HelpTool,

DefaultWebOptions,

Application object 的事件:

NewDocument, DocumentOpen, DocumentChange(当ActiveDocument属性改变时), DocumentBeforeClose, DocumentBeforePrint, DocumentBeforeSave

WindowActivate, WindowDeactivate, WindowSelectionChange, WindowBeforeDoubleClock, WindowBeforeRightClick, Quit

注:在Word中,除Application object外,只有Document object响应3个事件 :New,Open,Close。

此外,在Document上的ActiveX Cobtrols也。对每一FormField可以指定On Entry和On Exit宏,相当于 GotFocus和LostFocus事件过程。当然在Word VB Project中建立的UserForms及其上的Controls也响应事件。

Application.Run Method

Runs a Visual Basic macro in the Word Application.

Syntax App.Run(MacroName, varg1, varg2, varg3, ? , varg30)

MacroName : Required String. The name of the macro. Can be any combination of template, module, and macro name.

varg1...varg30 : Optional Variant. Macro parameter values. You can pass up to 30 parameter values to the specified macro.

For example, the following statements are all valid.

Application.Run \‘ ok Application.Run \‘ ok

Application.Run \‘自注:ERROR !

If you specify the document name, your code can only run macros in documents related to the current context — not just any macro in any document. Remarks

Although Visual Basic code can call a macro directly (without this method being used), this method is useful when the macro name is stored in a variable (for more information, see the example for this topic). The following statements are functionally equivalent.

Normal.Module2.Macro1

Call Normal.Module2.Macro1

Application.Run MacroName:=\

自注:Normal是Normal.dot的Project Name。你可以在 VBEditor中为一个 .doc的VBProject指定Projact Name ( By default, it is “Project” for all documents),通过Project Properties对话框(右击“Project”)。在一Module中的Macro(Public Sub/Function)的全名是:

[ProjectName.ModuleName.]MacroName

如果不重名,前缀限定可以省。

在Automation中从其他应用执行Word Project的Macros只能用Word的Application.Run方法。例如假设当前在Word中打开了2个.doc文件,其Project名分别为Project1和Project2,它们各有一Module1,其中都有一个SUB DISPLAY1(),而Project1有SUB Display2。在Access2000中执行以下过程:

Sub RunWordMacro()

Dim wdApp As Word.Application

Set wdApp = GetObject(, \

MsgBox wdApp.Documents(1).Name ? ok wdApp.Documents(\

wdApp.Run \? Error.说明ModuleName不能省 wdApp.Run \? ok wdApp.Run \?DOC1.doc?!Module1.Display1\? Error wdApp.Run \? ok wdApp.Run \? ok End Sub

可是,实验表明,仅当Doc1.doc是当前ActiveDocument才对。但执行Template(Normal)中的Macro总是对的。

Documents collection

Document collection 是当前所有 Document objects 的集合,即当前Open的所有文挡。不包括所基于的.dot文件(属于Template object),但包括独立打开的(如用File->Open)的.dot文件(属于Document object)。

属性:Count, Parent, Application, Creater 方法:Add, Item, Open, Save, Close 事件:No

Add Method (Documents)

Adds a new, empty document to the collection of open documents. Returns a Document object. Documents.Add(Template, NewTemplate, DocumentType, Visible)

Template: Optional Variant(string).

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(Long)

wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. Visible: True/False.

例: Documents.Add Template:=\ & \ Set wdDoc = Applicatipn.Documents.Add()

Item Method (Documents)

Item(Index) ,returns a Document object. (default method) Index: 1,2,…, Count, or Document Name (string) 例: Application.Documents(1)

Application.Documents.Item(1) Documents(\

Open Method

Opens the specified document and adds it to the Documents collection. Returns a Document object.

Syntax: Open(FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument,

PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible)

FileName: Required Variant. The name of the document (paths are accepted).

ConfirmConversions: Optional Variant. True to display the Convert File dialog box if the file isn't in Microsoft Word format.

ReadOnly : Optional Variant. True to open the document as read-only.

AddToRecentFiles: Optional Variant. True to add the file name to the list of recently used files at the bottom of the File menu.

PasswordDocument: Optional Variant. The password for opening the document. PasswordTemplate: Optional Variant. The password for opening the template.

Revert: Optional Variant. Controls what happens if Name is the file name of an open document. True to discard any unsaved changes to the open document and reopen the file. False to activate the open document.

WritePasswordDocument: Optional Variant. The password for saving changes to the document.

WritePasswordTemplate: Optional Variant. The password for saving changes to the template.

Format: Optional Variant. The file converter to be used to open the document:

wdOpenFormatAllWord, wdOpenFormatAuto, wdOpenFormatDocument,

wdOpenFormatEncodedText, wdOpenFormatRTF, wdOpenFormatTemplate, wdOpenFormatText, wdOpenFormatUnicodeText, or wdOpenFormatWebPages. The default value is wdOpenFormatAuto.

To specify an external file format, apply the OpenFormat property to a FileConverter object to determine the value to use with this argument.

Encoding : Optional Variant. The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. For the list of valid MsoEncoding constants, see the Object Browser in the Visual Basic Editor. The default is the system code page. Read/write Long.

Visible: Optional Variant. True if the document is opened in a visible window. The default is True.

Examples:

This example opens MyDoc.doc as a read-only document.

Documents.Open FileName:=\

This example opens the most recent version of Report.doc.

Set myDoc = Documents(\

myDoc.Versions(myDoc.Versions.Count).Open

Save Method (Documents,Document,Template,Version)

Syntax 1: Saves the specified document or template. If the document or template hasn't been saved before, the Save As dialog box prompts the user for a file name.

Document or Template.Save

Syntax 2: Saves all the documents in the Documents collection. If a document hasn't been saved before, the Save As dialog box prompts the user for a file name.

Documents.Save(NoPrompt, OriginalFormat)

NoPrompt: Optional Variant. True to have Word automatically save all documents. False to have Word prompt the user to save each document that has changed since it was last saved.

OriginalFormat: Optional Variant. Specifies the way the documents are saved. Can be one of the following WdOriginalFormat constants: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument.

Syntax 3: Saves a version of the specified document with a comment.

version.Save(Comment)

Comment: Optional Variant. The comment string that's saved with the version.

Examples:

This example saves the active document if it's changed since it was last saved.

If ActiveDocument.Saved = False Then ActiveDocument.Save

This example saves each document in the Documents collection without first prompting the user.

Documents.Save NoPrompt:=True, OriginalFormat:=wdOriginalDocumentFormat

Close Method (Documents,Document)

Closes the specified document or all open documents.

Documents. or Document.Close(SaveChanges, OriginalFormat, RouteDocument) SaveChanges: Optional Variant. Specifies the save action for the document: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. OriginalFormat: Optional Variant. Specifies the save format for the document wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument.

RouteDocument: Optional Variant. True to route the document to the next recipient. If the document doesn't have a routing slip attached, this argument is ignored.

Example:

On Error GoTo errorHandler ActiveDocument.Close _

SaveChanges:=wdPromptToSaveChanges, _ OriginalFormat:=wdPromptUser errorHandler:

If Err = 4198 Then MsgBox \

Document object

Document object的属性:

Subdocuments (Subdocument), Versions (Version) AttachedTemplate,

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),TablesOfContents (TablesOfContent), TableOfFigures (TableOfFigure), TablesOfAuthorities(TablesOfAuthority), PageSetup, DocumentProperties(DocumentProperty), LetterContent, Envelope,

Email, Scrips (Script), Frames (Frame),

MailMerge( MailMergeDataSource, MailMergeFields (MailMergeField)) CommandBars (CommabdBar), VBProject, HTMLProject, WebOptions

Windows (Window),ActiveWindow BackGround,

BuiltInDocumentProperties(DocumentProperty), CustomaerDocumentProperties(DocumentProperty),

Name,Path,FullName, (FullName= Path & “\\” & Name) Type, Kind, TrackRevisions, Versions,

HasPassword ,Password, ProtectionType, WritPassword, WriteReserved, Content,Container,StoryRanges, IsMasterDocument,IsSubdocument, ReadOnly, ReadOnlyRecommend, OpenEncoding, SaveEncoding,

Saved, SaveFormat, SaveFormsData, SaveSubsetFonts,

PrintFormsData,PrintFractionalWidths,PrintPostScriptOverText,PrintRevisions, Lists,ListParagraphs,ListTemplates, NoLineBreakBefore/After,

LanguageDetected,KerningByAlgorithm,

ReadabilityStatistics,SummaryLength,SummaryViewMode,

ActiveTheme, ActiveThemeDisplayNem, ActiveWritingStyle(language), AutoHyphenation,ConsecutiveHyphenLimit,HyphenateCaps,HyphenationZone, DefaultTypeStop,JustificationMode, EmbedTrueTypeFonts,

FarEastLineBreakLanguage,FarEastLineLevel, Compatibility,ClickAndTypeParagraph

FormDesign,SnapToGrid,SnapToShape, CodeName,

SpellingChecked,SpellingErrors,GrammarChecked,GrammaticalErrors, ShowGrammaticalErrors,ShowRevisions,ShowSpellingErrors,

GridDistanceHorizontal/Vertical,GridSpaceBetweenHorizontalLines/VerticalLines, GridOriginHorizontal/Vertical/FromMargin, HasRoutingSlip,Royted,RoutingSlip,

Document object的方法:

Activate,Close,Compare,Protect,Unprotect, Reload, ReloadAs, RunAutoMacro, Range, Select,

CopyStylesFromTemplate,FitToPages,

FollowHyperlink, GoTo, Redo, Undo, UndoClear,

CreateLetterContent, SetLetterContent, GetLetterContent, RunLetterWizard, Merge,

Route, SendFax, SendMail, Post, PresentIt, GetCrossReferenceItems, Save, SaveAs,

PrintPreview, ClosePrintView, PrintOut, Repaginate, WebPagePreview, ToggleFormDesign,DetectForm, DetectLanguage, makeCompatibilityDefault, AcceptAllRevisions, RejectAllRevisions, AddToFavorites, ApplyTheme, RemoveTheme, UpdateStyles, ConvertNemersToText,

AutoFormat,AutoSummarize,ComputeStatistics, UpdateSummaryProperties,

CountNumberdItems, RemoveNumbers,

CheckConsistency,CheckGrammar,CheckSpelling, ManualHyphenation,

ViewCode, ViewPropertyBrowser Saved属性 ( Document )

True/False , Read/Write.

当Document刚打开时,Saved=True。Saved=True表示文档不需再Save,因为没有改变。 一旦文档被编辑或编辑了它的VBA code(Custom工具栏不算在内),Saved变成False,表示还未Save。一旦Save,又变成 True。

当你Close文档时,在执行完Close Event后,系统判断Saved属性, 如果当前Saved=False,就问你是否要Save文档,如果Saved=True,就不问而立即 Close。

Saved属性也是可写的。 因此你可以在Close Event里,即使Saved=False,也可人为地置Saved = True,指示不要问,也不Save,直接关闭文档。

Range方法 ( Document )

document.Range(Start, End) 起点:0

例. 前5个字符: MsgBox ActiveDocument.Range(0,5).Text 第3-6段:

Set myRange = aDoc.Range(aDoc.Paragraphs(3).Range.Start, _ aDoc.Paragraphs(6).Range.End)

GoTo 方法 (Document,Range,Selection)

For Document or Range object:

Returns a Range object ( a Insert point )that represents the start position of the specified item, such as a page, bookmark, or field.

For Selection object:

Moves the insertion point to the character position immediately preceding the specified item, and returns a Range object (except for the wdGoToGrammaticalError, wdGoToProofreadingError, or wdGoToSpellingError constant).

Note When you use this method with the wdGoToGrammaticalError, wdGoToProofreadingError, or wdGoToSpellingError constant, the Range that's returned includes any grammar error text or spelling error text.

语法: object.GoTo(What, Which, Count, Name) object : a Document, Range, or Selection object.

What: Optional Variant. The kind of item that the range or selection is to be moved to. Can be one of the following WdGoToItem constants:

wdGoToBookmark wdGoToComment wdGoToEndnote wdGoToEquation wdGoToField wdGoToFootnote wdGoToGrammaticalError wdGoToGraphic wdGoToHeading, wdGoToLine wdGoToObject wdGoToPage wdGoToPercent wdGoToProofreadingError wdGoToSection wdGoToTable or wdGoToSpellingError

Which: Optional Variant. The item that the range or selection is to be moved to.Can be one of the following WdGoToDirection constants:

wdGoToAbsolute, wdGoToFirst, wdGoToLast, wdGoToNext, wdGoToPrevious, or wdGoToRelative.

The following examples are functionally equivalent, they both move the selection to the first heading in the document.

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToFirst

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1

Count : Optional Variant. The number of the item in the document. The default value is 1. The following example moves the selection to the fourth line in the document.

Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=4

Only positive values are valid. To specify an item that precedes the range or selection, use wdGoToPrevious as the Which argument and specify a Count value. The following example moves the selection up two lines.

Selection.GoTo What:=wdGoToLine, Which:=wdGoToPrevious, Count:=2

Name : Optional Variant. If the What argument is wdGoToBookmark, wdGoToComment, wdGoToField, or wdGoToObject, this argument specifies a name. The following example moves to the next DATE field.

Selection.GoTo What:=wdGoToField, Name:=\

Templates Collection Object

A collection of Template objects that represent all the templates that are currently available. This collection includes open templates, templates attached to open documents, and global templates loaded in the Templates and Add-ins dialog box (Tools menu).

Templates property (Application object)

return the Templates collection.

For Each aTemp In Templates ‘ i.e. Application.Templates MsgBox aTemp.FullName Next aTemp

Application.Templates集合包括:

? ? ?

Templates collection do not support Add method. Instead, you can add a template to the Templates collection by doing any of the following:

?

Using the Open method with the Documents collection to open a document based on a template or a template ( 同File -> Open -> .dot file ,这样打开的.dot文件即属于Template集合,也属于Documents集合)

Using the Add method with the Documents collection to open a new document based on a template (同上)

Using the Add method with the Addins collection to load a global template

Using the AttachedTemplate property with the Document object to attach a template to a document

当前打开的所有Doc文件的模板.Dot文件; 已Load的所有Global模板.Dot文件;

作为 Document打开的.Dot文件(注:这些打开的.dot文件也同时属于Documents集合)

? ? ?

Use Templates(index), where index is the template name or the index number, to return a single Template object. The following example saves the Dot1.dot template.

Templates(\

Use the Application?s NormalTemplate property to return a template object that refers to the Normal template. Use the Document?s AttachedTemplate property to return the template attached to the specified document.

Use the DefaultFilePath property to determine the location of user or workgroup templates (that is, the folder where you want to store these templates). The following example displays the user template folder from the File Locations tab in the Options dialog box (Tools menu).

MsgBox Options.DefaultFilePath(wdUserTemplatePath)

Templates collection (Application object)

属性:Count, Parent, Application, Creater 方法:Item

Template object

属性:

Name,Path,FullName, (FullName= Path & “\\” & Name) Type,Saved,

BuiltInDocumentProperties(DocumentProperty), CustomaerDocumentProperties(DocumentProperty), FarEastLineBreakLanguage,FarEastLineLevel, KerningByAlgorithm, JustificationMode, NoLineBreakBefore/After, ListTemplates, VBProject,

(Document object也有以上属性) AutoTextEntries(AutoTextEntry),

LanguageID,LanguageIDFarEast,NoProofing, Parent, Application, Creater 方法:OpenAsDocument,Save

NoProofing属性: True if the spelling and grammar checker ignores documents based on this template. Read/write Long.

Bookmarks

Bookmarks Collection

A collection of Bookmark objects that represent the bookmarks in the specified selection, range, or document.

属性:Count,ShowHidden,DefaultSorting, Creater,Parent,Application 方法:Item,Exists,Add

Use the Bookmarks property of selection/range/ documentto return the Bookmarks collection. Use the Bookmarks(index) to return a single Bookmark object: Object.Bookmarks(index)

where index is the bookmark name or index number. You must exactly match the spelling (but not necessarily the capitalization) of the bookmark name. The index number represents the

position of the bookmark in the Selection or Range object. For the Document object, the index number represents the position of the bookmark in the alphabetic list of bookmarks in the Bookmarks dialog box (click Name to sort the list of bookmarks alphabetically).

MsgBox ActiveDocument.Bookmarks(2).Name

MsgBox ActiveDocument.Bookmarks(“Bookmark1”).Range.Text

The following example ensures that the bookmark named \before selecting the bookmark.

If ActiveDocument.Bookmarks.Exists(\ ActiveDocument.Bookmarks(\End If

Use the Add method to set a bookmark for a range in a document. The following example marks the selection by adding a bookmark named \

ActiveDocument.Bookmarks.Add Name:=\

Remarks

The ShowHidden property effects the number of elements in the Bookmarks collection. The Hidden bookmarks are included in the Bookmarks collection only if ShowHidden is True.

Bookmark Object

Use the BookmarkID property with a range or selection object to return the index number of the Bookmark object in the Bookmarks collection. The following example displays the index number of the bookmark named \

MsgBox ActiveDocument.Bookmarks(\

You can use predefined bookmarks with the Bookmarks property. The following example sets the bookmark named \

ActiveDocument.Bookmarks(\

Predefined Bookmarks

Word sets and automatically updates a number of reserved bookmarks. You can use these

predefined bookmarks just as you use the ones that you place in documents, except that you don't have to set them and they are not listed on the Go To tab in the Find and Replace dialog box (Edit menu).

The following table describes the predefined bookmarks available in Word. BOOKMARK \\Sel \\PrevSel1 DESCRIPTION Current selection or the insertion point. Most recent selection where editing occurred; going to this bookmark is equivalent to running the GoBack method once. Second most recent selection where editing occurred; going to this bookmark is equivalent to running the GoBack method twice. Start of the current selection. End of the current selection. Current line or the first line of the current selection. If the insertion point is at the end of a line that is not the last line in the paragraph, \\PrevSel2 \\StartOfSel \\EndOfSel \\Line the bookmark includes the entire next line. \\Char Current character, which is the character following the insertion point if there is no selection, or the first character of the selection. Current paragraph, which is the paragraph containing the insertion point or, if more than one paragraph is selected, the first paragraph of the selection. Note that if the insertion point or selection is in the last paragraph of the document, the \paragraph mark. Current section, including the break at the end of the section, if any. The current section contains the insertion point or selection. If the selection contains more than one section, the \first section in the selection. Entire contents of the active document, with the exception of the final paragraph mark. Current page, including the break at the end of the page, if any. The current page contains the insertion point. If the current selection contains more than one page, the \selection. Note that if the insertion point or selection is in the last page of the document, the \paragraph mark. Beginning of the document. End of the document. Current cell in a table, which is the cell containing the insertion point. If one or more cells of a table are included in the current selection, the \ Current table, which is the table containing the insertion point or selection. If the selection includes more than one table, the \bookmark is the entire first table of the selection, even if the entire table is not selected. \\Para \\Section \\Doc \\Page \\StartOfDoc \\EndOfDoc \\Cell \\Table \\HeadingLevel The heading that contains the insertion point or selection, plus any subordinate headings and text. If the current selection is body text, the \and text subordinate to that heading.

Bookmark Object

属性:Name,Range,Empty,Column,Start,End,StoryType, Creator,Parent,Application 方法:Select, Cope, Delete

Start Property (Selection, Range, and Bookmark objects)

Returns or sets the starting character position of a selection, range, or bookmark. Read/write Long.

Note If this property is set to a value larger than that of the End property, the End property is set to the same value as that of Start property.

Selection, Range, and Bookmark objects have starting and ending character positions. The starting position refers to the character position closest to the beginning of the story. This property returns the starting character position relative to the beginning of the story. The main text story (wdMainTextStory) begins with character position 0 (zero). You can change the size of a selection, range, or bookmark by setting this property.

End Property (Selection, Range, and Bookmark objects) Read/write Long.

This property returns the ending character position relative to the beginning of the story.

You can change the size of a selection, range, or bookmark by setting Start and End property.

StoryType Property (Selection, Range, and Bookmark objects)

Read-only Long. 该Range,Selection或Bookmark 所在的Story的类型。Can be one of the following WdStoryType constants:

wdCommentsStory, wdEndnotesStory, wdEvenPagesFooterStory, wdEvenPagesHeaderStory, wdFirstPageFooterStory, wdFirstPageHeaderStory, wdFootnotesStory, wdMainTextStory, wdPrimaryFooterStory, wdPrimaryHeaderStory, or wdTextFrameStory.

StoryLength Property (Selection and Range objects)

Read-only Long. 该range or selection 所在的Story(如wdMainTextStory)的长度(字符数)

Column Property (Bookmark and Cell objects)

Bookmark object: Read-only Boolean.

True if the specified bookmark is a table column. Cell object: Read-only, object.

Returns a Column object that represents the table column containing the specified cell.

Empty Property ( Bookmark objects )

Read-only Boolean.

True if the specified bookmark is empty. An empty bookmark marks a location (a collapsed selection); it doesn't mark any text.

Note An error occurs if the specified bookmark doesn't exist. Use the Exists method of Bookmarks collection to determine whether a given bookmark exists:

Range Property ( for many objects)

Read-only.

Returns a Range object that represents the portion of a document that's contained in the specified bookmark object.

If ActiveDocument.Bookmarks.Exists(\…

自注:更新Bookmark下的Text

如果Bookmark是一插入点,则以下语句是在此插入 “Smith”,其后text右移,该Bookmark的位置保持不变:

ActiveDocument.Bookmarks(\“Smith”

但如果Bookmark是一范围,上述语句更新原范围中的text后,该Bookmark也被Deleted了。例如 执行该语句,把EmpName bookmark下的Text换为“Smith”(实际是先删后插,不管原Text有多长。即Range的新范围(End位置)按新Text长度确定。对任何Range,写其Text属性总是这样),但是Bookmark “EmpName” 也删去了。为保持原Bookmark ,只能再加上:

Dim r1 As Range

Set r1 = ActiveDocument.Bookmarks(\ ?保留Range object

r1.Text = CmbEmpID.Value ? 更新text,r1范围大小可能变了 ActiveDocument.Bookmarks.Add Name:=\ ?恢复Bookmark代表新范围

当然,可用Bookmarks(\方法插入text,此时Bookmark不会被删,但原来的text仍在。可以在插入后删去原Text:

Dim r As Range, N As Integer, i As Integer

If ActiveDocument.Bookmarks.Exists(\ ActiveDocument.Bookmarks(\Select

‘Options.ReplaceSelection = False 不影响collapse后插入 N = Selection.Characters.Count

Selection.Collapse wdCollapseStart Selection.TypeText \

Selection.Delete wdCharacter, N End If

Tables

Tables Collection Object

A collection of Table objects that represent the tables in a selection, range, or document.

属性:Count,NestingLevel, Creater,Parent,Application 方法:Item, Add

Use the Tables property to return the Tables collection. The following example applies a border around each of the tables in the active document.

For Each aTable In ActiveDocument.Tables

aTable.Borders.OutsideLineStyle = wdLineStyleSingle aTable.Borders.OutsideLineWidth = wdLineWidth025pt aTable.Borders.InsideLineStyle = wdLineStyleNone Next aTable

Use the Add method to add a table at the specified range. The following example adds a 3x4 table at the beginning of the active document.

Set myRange = ActiveDocument.Range(Start:=0, End:=0)

ActiveDocument.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=4

Use Tables(index), where index is the index number(Table无Name), to return a single Table object. The index number represents the position of the table in the selection, range, or document. The following example converts the first table in the active document to text.

ActiveDocument.Tables(1).ConvertToText Separator:=wdSeparateByTabs

Remarks

The Count property for this collection in a document returns the number of items in the main story only. To count items in other stories use the collection with the Range object.

Add Method (Tables Collection)

Adds a new, blank table to a document. Syntax

Table.Add(Range, NumRows, NumColumns, DefaultTableBehavior, AutoFitBehavior)

Range Required, Range. The range where you want the table to appear. The table replaces the range, if the range isn't collapsed. (可以是一插入点)

NumRows Required, Long. The number of rows you want to include in the table. NumColumns Required, Long. The number of columns you want to include in the table. DefaultTableBehavior Optional, Variant. Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells? contents (AutoFit). Can be either of the following constants:

wdWord8TableBehavior (AutoFit disabled) wdWord9TableBehavior (AutoFit enabled).

AutoFitBehavior Optional Variant. Sets the AutoFit rules for how Word sizes tables. Can be one of the following WdAutoFitBehavior constants: wdAutoFitContent, wdAutoFitFixed, or wdAutoFitWindow.

If DefaultTableBehavior is set to wdWord8TableBehavior, this argument is ignored.

例: Set myRange = ActiveDocument.Range(Start:=0, End:=0)

ActiveDocument.Tables.Add Range:=myRange, NumRows:=3, NumColumns:=4

Table object

属性: AllowAutoFit, AllowPageBreak, AutoFormatType,

LeftPadding, RightPadding, TopPadding, BottomPadding, PreferredWidth, PreferredWidthType, NestingLevel, TableDirection, Uniform, Rows, Columns, Range, Borders, Tables (Nested), Shading, Spacing,

Creator, Parent ,Application

ID (label for the specified object when saved as a Web page)

注:Table无Name 属性。可给Table或它的任何部分指定一Bookmark,用来标认它。 方法: AutoFitBehavior,AutoFormat,UpdateAutoFormat, Cell,

Select,Delete,Sort,SortAsceding,SortDescending, Split

Range 属性:指向Range object,其Range是整个table。

注:这样的Range,Selection及Row,Column objects有Cells属性,指向其内的Cells集合。 Table object还有Cell(row,col)方法,返回Cell object.

Columns和 Rows属性:指向Columns和 Rows集合。Row和Column objects有Cells属性。

Cell Method

Returns a Cell object that represents a cell in a table. Syntax

Table.Cell(Row, Column)

Row Required Long. The number of the row in the table to return. Can be an integer between 1 and the number of rows in the table.

Column Required Long. The number of the cell in the table to return. Can be an integer between 1 and the number of columns in the table.

Table Cells

Cells Collection (of Column,Row,Range,Selection object)

A collection of Cell objects in a table column, table row, selection, or range. 属性:Count, Borders,Shading,NestingLevel,

Width,Height,HeightRule,PreferredWidth,PrefferredWidthType,VerticalAlignment, Creator, Parent ,Application

方法:Item, Delete, Merge, Split,

AutoFit, DistributeHeight, DistibuteWidth, SetHeight, SetWidth

Using the Cells Object

Use the Cells property to return the Cells collection. The following example formats the cells in the first row in table one in the active document to be 30 points wide.

ActiveDocument.Tables(1).Rows(1).Cells.Width = 30

The following example returns the number of cells in the current row.

num = Selection.Rows(1).Cells.Count

Use the Add method to add a Cell object to the Cells collection. You can also use the

InsertCells method of the Selection object to insert new cells. The following example adds a cell before the first cell in myTable.

Set myTable = ActiveDocument.Tables(1)

myTable.Range.Cells.Add BeforeCell:=myTable.Cell(1, 1)

Cell object

Use Cell(row, column) method(Table object), where row is the row number and column is the column number, or Cells(index) method(Item方法), where index is the index number, to return a Cell object. The following example applies shading to the second cell in the first row in table one.

Set myCell = ActiveDocument.Tables(1).Cell(Row:=1, Column:=2) myCell.Shading.Texture = wdTexture20Percent

Insert text into a cell:

msgbox myCell.Range.Text

myCell.Range.Text = “Cell entry” ? Replace the original text

myCell.Range.InsertBefore “Cell entry” ?Insert before the Start of the range myCell.Range.InsertAfter “Cell entry” ?Insert after the Start of the range

The following example applies shading to the first cell in the first row.

ActiveDocument.Tables(1).Rows(1).Cells(1).Shading.Texture = wdTexture20Percent

Remarks

Use the Add method with the Rows or Columns collection to add a row or column of cells. The following example adds a column to the first table in the active document and then inserts numbers into the first column.

Set myTable = ActiveDocument.Tables(1)

Set aColumn = myTable.Columns.Add(BeforeColumn:=myTable.Columns(1)) For Each aCell In aColumn.Cells aCell.Range.Delete

aCell.Range.InsertAfter num + 1 num = num + 1 Next aCell

Cell Object

表示Table中的个别cell。

属性:Borders,Shading,FitText,NestingLevel,ID, Left/Right/Top/BottomPadding,

Range,Column(object),ColumnIndex(列号),Row,RowIndex,Tables, Next,Previoue,

Width,Height,HeightRule,PreferredWidth,PrefferredWidthType,VerticalAlignment, Creator, Parent ,Application

方法:Select, Delete, Merge, Split, Formula, AutoSum, SetHeight, SetWidth

注:Cell无Text属性,须用Cell.Range.Text属性或Cell.Range.InsertBefore/InsertAfter()方法 存取 cell中的字符串。例如: dim c as cell

or: set c = ActiveDocument.tables(1).rows(3).cells(5) set c = ActiveDocument.tables(1).cell(3,5) Read: Msgbox c.range.text

Write: c.range.text = “New contect” ? Owerwrites the original text in the cell or c.range.insertBefore “Added string”

? “Added string” is insert before the original text 注:但Cell.range.text返回的text包含最后的Cell end mark。

Cell End mark是2个字符:Chr(13)(i.e.return)和Chr(7),因是不可印刷字符,所以在 MsgBox()或Debug.print时看不见。

当用code 读Cell.range.text时要去掉End mark才行:

Set myRange = ActiveDocument.Range(Start:=c.Range.Start, _ End:=c.Range.End - 1) 或 Set myRange = c.Range

MyRange.moveEnd unit:=wdCharacter,Count:=-1

Dim S as string S = MyRange.text

自注:Cell的End mark是2个字符:Chr(13)和Chr(7),不知为什么只回退一个。

但回退一个确实是对的(已实验).

Dim c As Range

Set c = ActiveDocument.Tables(1).Cell(1, 1).Range ? 设cell(1,1)含 “ABCDEFG”

MsgBox c.Text & \? Len=9

MsgBox Left(c.Text, Len(c.Text) - 1) & “*” ? “ABCDEFG”+Chr(13)+”*” MsgBox Left(c.Text, Len(c.Text) - 2) & “*” ? “ABCDEFG*” also Ok c.MoveEnd Unit:=wdCharacter, Count:=-1

MsgBox c.Text & \“*” ? “ABCDEFG*” Len=7 Ok

The following example sets a range (myRange) that references the first two cells in the first table. After the range is set, the cells are combined by the Merge method.

Set myTable = ActiveDocument.Tables(1)

Set myRange = ActiveDocument.Range(myTable.Cell(1, 1) _ .Range.Start, myTable.Cell(1, 2).Range.End) myRange.Cells.Merge

Remarks

Use the Add method with the Rows or Columns collection to add a row or column of cells. Use the Information property with a Selection object to return the current row and column number. The following example changes the width of the first cell in the selection and then displays the cell's row number and column number.

If Selection.Information(wdWithInTable) = True Then With Selection

.Cells(1).Width = 22

MsgBox \ & \ End With End If

FormFields

FormFields Collection

A collection of FormField objects that represent all the form fields in a selection, range, or document.

属性:Count, Shaded(T/F), Parent, Creator, Application 方法:Item,Add

Use the FormFields property to return the FormFields collection. The following example counts the number of text box form fields in the active document.

For Each aField In ActiveDocument.FormFields

If aField.Type = wdFieldFormTextInput Then count = count + 1 Next aField

MsgBox \

Use the Add method with the FormFields object to add a form field. The following example adds a check box at the beginning of the active document and then selects the check box.

Set ffield = ActiveDocument.FormFields.Add( _

Range:=ActiveDocument.Range(Start:=0,End:=0), _ Type:=wdFieldFormCheckBox) ffield.CheckBox.Value = True

Use FormFields(index), where index is a bookmark name or index number, to return a single FormField object. The following example sets the result of the Text1 form field to \Funk.\

ActiveDocument.FormFields(\

The index number represents the position of the form field in the selection, range, or

document. The following example displays the name of the first form field in the selection.

If Selection.FormFields.Count >= 1 Then MsgBox Selection.FormFields(1).Name End If

Lock Fomfields for typing in form fields(相当于按“锁”工具按钮)

(交互式:Tools -> Protect Document -> Protect Form)

使用Document的Protect(type,noreset,password)方法Lock form fields:

ActiveDocument.Protect Password:=\

Noreset= False to reset form fields to their default values.

Type: wdAllowOnlyComments(1), wdAllowOnlyFormFields(2), wdAllowOnlyRevisions(0), or WdNoProtection(-1)

使用Document的Unprotect(password)方法Unlock form fields:

使用Document的ProtectionType属性(Read only)可知当前对document设置了何保护,其值是 上述4个常数之一。

另,Section object 有ProtectedForForms 属性(Read/Write,Boolean),好象也能用,但以下 语句并不成功:

ActiveDocument.Sections(1).ProtectedForForms = True

注:如果Form locked,光标只能进入Form Fields(及ActiveX Controls),从而不能再编辑文档的其他部分,用Code也只能写FormFields(但 “=Formula” Fields 可以更新,自动地或者使用Update命令(F9)或 Field object的Update方法)。仅当在Unlocked的情况下,才能编辑文档,以及添加FormFields,设置它们的属性等。此时虽仍可在TextInput FormFields中键入Text,但在键入后该FormField(及其BookMark)会被自动去掉,留下来的只是你键入的Text。此时也不能单击CheckBox来改变True/false,在DropDown FormFields右边的箭头按钮也不可见,从而不能打开DropDown list进行选择。在Unlocked情形,EntryMacro和ExitMacro也不会执行。因此,一般说,如果在文档中使用FormFields,就只能在Lock FormFields下“填表”,而Unlock情形时用于设计FormFields的。

注意,如果在你已编辑完Form fields后,你Unlock后再按工具栏Lock button重新Lock,则所有的编辑都废了,各Form Fields回到其default值。因为该工具栏Lock button使用的Document. Protect()方法中的NoReset=False。你可以自己建立工具栏Lock button,用NoReset=True。

Private Sub Document_Open() CreateToolbar

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then ActiveDocument.Unprotect Password:=\End If

LockUnlockFormClick ? Lock form fields End sub

Sub CreateToolbar()

Dim c As Office.CommandBarButton ' CommandBarControl

On Error Resume Next

Set c = Application.CommandBars(\ ' If c does not exist, Err=5. If Err = 0 Then

Application.CommandBars(\ Exit Sub End If

mailMerge.Execute(Pause)

Pause Optional Variant. True to have Word pause and display a troubleshooting dialog box if a mail merge error is found. False to report errors in a new document.

Performs the specified mail merge operation.

This example executes a mail merge if the active document is a main document with an attached data source.

Set myMerge = ActiveDocument.MailMerge

If myMerge.State = wdMainAndDataSource Then MyMerge.Execute

Update 方法 (Dialog object)

Syntax dialogObj.Update

Updates the values shown in a built-in Microsoft Word dialog box.

This example returns a Dialog object that refers to the Font dialog box. The font

applied to the Selection object is changed to Arial, the dialog values are updated, and the Font dialog box is displayed.

Set myDialog = Dialogs(wdDialogFormatFont) Selection.Font.Name = \myDialog.Update myDialog.Show

自注:DialogObj.Update方法(也不显示对话框) 是用当前Selection 来更新dialogObj对话框中的Options。然后你可接着再Display, Show,或Execute。

附注:Field/Fields ,Index, TableOfAuthorities, TableOfContents, TableOfFigures,和LinkFormat object也有Update方法。

Built-in dialog type ( WdWordDialog constant )

Many of the built-in Microsoft Word dialog boxes have arguments that you can use to set or get values from a dialog box.

WdWordDialog constant:Argument list(s)

wdDialogConnect:Drive, Path, Password wdDialogCopyFile:FileName, Directory

wdDialogEditFind:Find, Replace, Direction, MatchCase, WholeWord, PatternMatch, SoundsLike,

FindNext, ReplaceOne, ReplaceAll, Format, Wrap, FindAllWordForms, MatchByte, FuzzyFind, Destination, CorrectEnd, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl

wdDialogEditGoTo:Find, Replace, Direction, MatchCase, WholeWord, PatternMatch, SoundsLike,

FindNext, ReplaceOne, ReplaceAll, Format, Wrap, FindAllWordForms, MatchByte, FuzzyFind, Destination, CorrectEnd, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl

wdDialogEditGoToOld:(none)

wdDialogEditLinks:UpdateMode, Locked, SavePictureInDoc, UpdateNow, OpenSource, KillLink,

Link, Application, Item, FileName

wdDialogEditObject:Verb

wdDialogEditPasteSpecial:IconNumber, Link, DisplayIcon, Class, DataType, IconFileName,

Caption, Floating

wdDialogEditReplace:Find, Replace, Direction, MatchCase, WholeWord, PatternMatch,

SoundsLike, FindNext, ReplaceOne, ReplaceAll, Format, Wrap, FindAllWordForms, MatchByte, FuzzyFind, Destination, CorrectEnd, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl

wdDialogEditTOACategory:Category, CategoryName wdDialogEmailOptions:(none)

wdDialogFileFind:SearchName, SearchPath, Name, SubDir, Title, Author, Keywords, Subject,

Options, MatchCase, Text, PatternMatch, DateSavedFrom, DateSavedTo, SavedBy, DateCreatedFrom, DateCreatedTo, View, SortBy, ListBy, SelectedFile, Add, Delete, ShowFolders, MatchByte

wdDialogFileNew:Template, NewTemplate, DocumentType, Visible

wdDialogFileOpen:Name, ConfirmConversions, ReadOnly, LinkToSource, AddToMru, PasswordDoc,

PasswordDot, Revert, WritePasswordDoc, WritePasswordDot, Connection, SQLStatement, SQLStatement1, Format, Encoding, Visible

wdDialogFilePageSetup:Tab, PaperSize, TopMargin, BottomMargin, LeftMargin, RightMargin,

Gutter, PageWidth, PageHeight, Orientation, FirstPage, OtherPages, VertAlign, ApplyPropsTo, Default, FacingPages, HeaderDistance, FooterDistance, SectionStart, OddAndEvenPages,

DifferentFirstPage, Endnotes, LineNum, StartingNum, FromText, CountBy, NumMode, TwoOnOne, GutterPosition, LayoutMode, CharsLine, LinesPage, CharPitch, LinePitch, DocFontName, DocFontSize, PageColumns, TextFlow, FirstPageOnLeft, SectionType, RTLAlignment

wdDialogFilePrint:Background, AppendPrFile, Range, PrToFileName, From, To, Type,

NumCopies, Pages, Order, PrintToFile, Collate, FileName, Printer, OutputPrinter, DuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight

wdDialogFilePrintOneCopy:(For information about this constant, consult the language

reference Help included with Microsoft Office 98 Macintosh Edition.)

wdDialogFilePrintSetup:Printer, Options, Network, DoNotSetAsSysDefault

wdDialogFileRoutingSlip:Subject, Message, AllAtOnce, ReturnWhenDone, TrackStatus,

Protect, AddSlip, RouteDocument, AddRecipient, OldRecipient, ResetSlip, ClearSlip, ClearRecipients, Address

wdDialogFileSaveAs:Name, Format, LockAnnot, Password, AddToMru, WritePassword,

RecommendReadOnly, EmbedFonts, NativePictureFormat, FormsData, SaveAsAOCELetter, WriteVersion, VersionDesc

wdDialogFileSaveVersion:(none)

wdDialogFileSummaryInfo:Title, Subject, Author, Keywords, Comments, FileName, Directory,

Template, CreateDate, LastSavedDate, LastSavedBy, RevisionNumber, EditTime, LastPrintedDate, NumPages, NumWords, NumChars, NumParas, NumLines, Update, FileSize

wdDialogFileVersions:AutoVersion, VersionDesc wdDialogFormatBulletsAndNumbering:(none)

wdDialogFormatDefineStyleLang:Language, CheckLanguage, Default, NoProof wdDialogFormat?

wdDialogFormFieldOptions:Entry, Exit, Name, Enable, TextType, TextWidth, TextDefault,

TextFormat, CheckSize, CheckWidth, CheckDefault, Type, OwnHelp, HelpText, OwnStat, StatText, Calculate

wdDialogInsertBookmark:Name, SortBy, Add, Delete, Goto, Hidden wdDialogInsertBreak:Type

wdDialogInsertDatabase:Format, Style, LinkToSource, Connection, SQLStatement,

SQLStatement1, PasswordDoc, PasswordDot, DataSource, From, To, IncludeFields, WritePasswordDoc, WritePasswordDot

wdDialogInsertField:Field

wdDialogInsertFile:Name, Range, ConfirmConversions, Link, Attachment

wdDialogInsertHyperlink:(none)

wdDialogInsertMergeField:MergeField, WordField

wdDialogInsertObject:IconNumber, FileName, Link, DisplayIcon, Tab, Class, IconFileName,

Caption, Floating

wdDialogInsertPicture:Name, LinkToFile, New, FloatOverText

wdDialogMailMerge:CheckErrors, Destination, MergeRecords, From, To, Suppression,

MailMerge, QueryOptions, MailSubject, MailAsAttachment, MailAddress

wdDialogMailMergeCheck:CheckErrors

wdDialogMailMergeCreateDataSource:FileName, PasswordDoc, PasswordDot, HeaderRecord,

MSQuery, SQLStatement, SQLStatement1, Connection, LinkToSource, WritePasswordDoc

wdDialogMailMergeCreateHeaderSource:FileName, PasswordDoc, PasswordDot, HeaderRecord,

MSQuery, SQLStatement, SQLStatement1, Connection, LinkToSource, WritePasswordDoc

wdDialogMailMergeFindRecord:Find, Field wdDialogMailMergeHelper:Merge, Options wdDialogMailMergeInsert?

wdDialogMailMergeQueryOptions:SQLStatement, SQLStatement1 wdDialogMailMergeUseAddressBook:AddressBookType

wdDialogToolsAdvancedSettings:Application, Option, Setting, Delete, Set

wdDialogToolsMacro:Name, Run, Edit, Show, Delete, Rename, Description, NewName, SetDesc wdDialogToolsOptions:Tab wdDialogToolsOptions? wdDialogWindowActivate:Window

Application.CommandBars.Add(Name:=\ True 'Position:=msoBarFloating,

Set c = Application.CommandBars(\

(Type:=msoControlButton) With c

.Caption = \

.OnAction = \LockUnlockFormClick\ .FaceId = 225

.Style = msoButtonIcon .State = msoButtonDown

.TooltipText = \ .BeginGroup = True End With

'如果添加系统的Menu命令Tools->Protect ->Form到ZmToolbar1上, 可写: ' Set c =Application.CommandBars(\

(Type:=msoControlButton, ID:=225) 'ID=225, Its FaceID is also 225 ' With C

' .BeginGroup = True ' End With End Sub

Sub LockUnlockFormClick()

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then ActiveDocument.Unprotect Password:=\

Application.CommandBars(\ Else

ActiveDocument.Protect NoReset:=True, Type:=wdAllowOnlyFormFields, Password:=\ Application.CommandBars(\

msoButtonDown End If End Sub

FormField object

属性:Name(即Bookmark),Type, Range,Result,

TextInput,CheckBox,DropDown, Next,Previous, OwnStatus,StatusText,

CalculateOnExit, Enabled, EntryMacro,ExitMacro, Creator, Parent ,Application

方法:Select, Delete, Copy, Cut

注:FormFields无Update方法。 FormFields虽然也属于Fields collection,但Fields的Update方法也不更新FormFields(见TextInput Formfield)。

上述是3种Type的FormFields共有的属性,特有的属性由下属的TextInput, CheckBox, 和DropDown object的属性给出。

Type属性:Read only, Long:

WdFieldFormTextInput, WdFieldFormCheckBox,wdFieldFormDropDown

用FormFields.Add方法可指定Type。

Enabled属性:Read/write,True/False.

True:用户可以编辑该FormField。 Result属性:Read/write, String

Returns the result of the specified form field.

例: For Each aField In ActiveDocument.FormFields

MsgBox aField.Result ? or aField.Range.Text Next aField

如果Text Form field为空,aField.Result是空串,而aField.Range.Text是5个“?”号。 CalculateOnExit属性:Read/write,True/False

True: 当光标离开时,(在ExitMacro执行之后)重新计算Document上所有的Fields(不限于..FormFields,如依赖于它的 { REF bookmark } fields及 = Formula fields也跟着更新,好象也不限于只依赖于该FormField的Fields,已实验)。

注:仅当Document.ProtectionType= wdAllowOnlyFormFields(2)情况(即Lock Form Fields)下,而且光标移到了另一FormField,才重新计算。注意,如果你是用单击某 ActiceX control的方式使光标离开FormField(到ActiveX Control上),并不重新计算(也不执行ExitMacro),但如果使用 Tab键使光标离开,无论到FormField或ActiveX Control上,则都重新计算(及执行ExitMacro)。 EntryMacro,ExitMacro属性:Read/write, String.

当光标进入或离开时要执行的Macro name(Sub名)。参见CalculateOnExit属性的注释。 TextInput,CheckBox,DropDown属性:Read only

分别指向TextInput, CheckBox, 和DropDown object。

如果用错了对象(与Type不一致),引用本属性并不Error,而是置Valid属性为False。 CheckBo object: 属性:Value(True/False),Default,Size,AsutoSize,Valid 方法:No

TextInput object: 属性:Type,Width,Default,Format,Valid 方法:Clear,EditType Type属性:Read-only Long.the type of TextInput form field. Can be one of the following WdTextFormFieldType constants: wdCalculationText, wdCurrentDateText, wdCurrentTimeText, wdDateText, wdNumberText, or wdRegularText(default).

在wdCalculationText类型的TextInput field中可以写 “ = 公式 ”,计算型 FormField。 注:因为FormFields无Update方法,所以使用普通的 =(Formula) Fields应该更好些。 Default属性:Read/write, String. 指定FormField的default值。

Format属性:Read-only String. Returns the text formatting for the specified text box. Use the EditType method of the TextInput object to set the text formatting.

DropDown object: 属性:Value(选择Item的行号), ListEntries, Default,Valid 方法:No

ListEntries属性: Read-only. Returns a ListEntries collection that represents all the items in a DropDown object

Use the Add method to add an item to a drop-down form field. The following example inserts a drop-down form field and then adds \drop-down list of the form field.

Set myField = ActiveDocument.FormFields.Add(Range:=Selection.Range, _ Type:=wdFieldFormDropDown) With myField.DropDown.ListEntries .Add Name:=\ .Add Name:=\ .Add Name:=\End With

Valid 属性:Read-only Boolean. ( CheckBox, DropDown, or TextInput object)

True if the specified form field object is a valid check box form field, drop down form field, or text form field. False if it isn't valid. If ActiveDocument.FormFields(1).TextInput.Valid = True Then

ActiveDocument.FormFields(1).Result = \End If

如果FormFields(1)不是TextInput,FormFields(1).TextInput.Valid是False。

例子:

This example protects the active document for forms and deletes the contents of the form field named \

ActiveDocument.Protect Type:=wdAllowOnlyFormFields ActiveDocument.FormFields(\TextInput.Clear

If the first form field in the active document is a text form field that accepts regular text, this example sets the contents of the form field.

Set myField = ActiveDocument.FormFields(1) If myField.Type = wdFieldFormTextInput And _ myField.TextInput.Type = wdRegularText Then myField.Result = \End If

The following example checks the type of the first form field in the active document. If it's a drop-down form field, the second item of the list is selected.

If ActiveDocument.FormFields(1).Type = wdFieldFormDropDown Then ActiveDocument.FormFields(1).DropDown.Value = 2 End If

The following example adds a check box at the beginning of the active document, sets the name to \

With ActiveDocument.FormFields.Add(Range:=ActiveDocument.Range _ (Start:=0,End:=0), Type:=wdFieldFormCheckBox) .Name = \

.CheckBox.Value = True End With

Document Variables

可以建立Document Variables,存放值。这些值和Document一起存储。这与在Modules或ThisDocument声明的Public/Private变量是不同的。因为当.doc下一次打开时,这些Public/Private变量被重新初始化,而Document Variables仍保留其以前的值。也可以把Document Variables的值显示在文档上,例如使用DOCVARIABLE field。

Variables Property (Document object) Document的Variables属性指向该Document的。

使用Variables collection的Add方法建立新的Variable object。Variable object的Default 属性是它的Value属性。

Variables collection

属性:Count, Creator, Parent ,Application

方法:Item, Add

Add(Name, Value) 方法:

建立一Document Variable:

Name : String. 变量名

Value : Optional Variant. 变量的值。也可以用Variable object的Value属性赋值。

Document variables are invisible to the user unless a DOCVARIABLE field is inserted with the appropriate variable name. If you try to add a variable with a name that already exists in the Variables collection, an error occurs.

* With ActiveDocument

.Variables.Add Name:=\

.Fields.Add Range:=Selection.Range, Type:=wdFieldDocVariable, Text:=\End With

ActiveDocument.ActiveWindow.View.ShowFieldCodes = False

ScreenUpdating = False

* This example stores the user name (from the Options dialog box) in the template attached to the active document.

With ActiveDocument.AttachedTemplate.OpenAsDocument

.Variables.Add Name:=\ .Close SaveChanges:=wdSaveChanges End With

Item(index)方法: index=1,2,…; 或 = Variable Name

MsgBox ActiveDocument.Variables(\

Variable object

属性:Name,Value,Index, Creator, Parent ,Application

方法:Delete

Value属性: Read/Write Variant. Default属性。

With ActiveDocument

.Variables.Add Name:=\

.Variables(\‘.Value MsgBox .Variables(\End With

Windows Collection

A collection of Windows objects that represent all the available windows. The Windows

collection for the Application object contains all the windows in the application, whereas the Windows collection for the Document object contains only the windows that display the specified document.

Windows Property (Application, Document object)

For Application object: Returns a Windows collection that represents all document windows. The collection corresponds to the window names that appear at the bottom of the Window menu. Read-only.

For Document object: Returns a Windows collection that represents all document windows for the specified document (for example, Sales.doc:1 and Sales.doc:2).

Using the Windows Collection

Use the Windows property to return the Windows collection. The following example tiles all the windows so that they don't overlap one another.

Windows.Arrange ArrangeStyle:=wdTiled

Use the Add method or the NewWindow method to add a new window to the Windows collection. Each of the following statements creates a new window for the document in the active window.

ActiveDocument.ActiveWindow.NewWindow

NewWindow Windows.Add

Use Windows(index), where index is the window caption or the index number, to return a single Window object. The following example maximizes the Document1.doc window.

Windows(\.doc\

The index number is the number to the left of the window name on the Window menu.。 Remarks

A colon (:) and a number appear in the window caption when more than one window is open for a document.

The following example displays the captions of all the windows in the Windows collection.

ActiveDocument.ActiveWindow.NewWindow Dim w As Window

For Each w In Windows Debug.Print w.Caption Next

Printed : “Word2000VBA.doc:1” 和 “Word2000VBA.doc:2”

当为一Document开了多个窗口后,它们总是显示同样的内容,在一窗口中做的Edit会立即显示在其他窗口中

When you switch the view to print preview, a new window is created. This window is removed from the Windows collection when you close print preview.

Windows collection:

属性:Count, Creator, Parent ,Application

方法:Item, Add, Arrange

Window object:

属性:

Caption,Active,ActivePane,Selection,Document, Next,Previous,

WindowNumber,Index,WindowState,IMEmode Split,SplitVertical,Panes,

Horizontal/VerticalPercentScrolled, DocumentMap,DocumentMapPercentWidth, Visible,EnvelopeVisible,

left,Top,Height, Width,UseableWidth/Height,StyleAreaWidth DisplayRulers, DisplayVerticalRulers,

DisplayVerticalScrollbar,DisplayHorizontalScrollbar, DisplayScreenTips, View,

Creator, Parent ,Application 方法:

Activate,NewWindow,Close,PrintOut,SetFocus LargeScroll,SmallScroll,PageScroll,ScrollIntoView, RangeFromPoint,GetPoint,

SplitVertical属性:Read/write Long. (Window object)

一个window可以split,即分为上下2个panes。未split的window只有单个pane。

属性值N = 0 – 100。把window分成上下2个panes,上pane的高度占window高度的N%。每个pane显示的是同一文档,但有自己的Scrollbar, 有自己的Selection或插入点,从而可以看到文档的不同部分。在每个pane上进行的编辑,在另一pane上当然也可看到,因为是同一文档。 即使在Normal View,下pane也可以不显示正文,而专门显示如Comments,Footnotes等,由window.View.SplitSpecial属性<>0指示。

N=0表示取消split,即window是单个Pane,与Split=False同效。 也可以用window.Panes.Add方法来split。

(交互式:Wibdow->Split 或 Window-Remove Split ) Split 属性:read/write True/False. (Window object)

Read: 返回T/F,表示window当前是否已分panes。

Write: 如果window还未split,则置Split属性为True时,该window被平分成上下2个panes,同window.SplitVertical=50。如果已split,写True则等于没写,写False则是去掉Panes,即整个window变成单个Pane。

View属性(Window object, Pane Object)

指向View object。

在Tools->Options->View tab中的options设置要通过ActiveDocument.ActiveWindow.View的属性来读写。

View object

注:Window和Pane objects都有下属的View object。View object的有些属性/方法只能用于 window.View object,而不能用于window.Pans(i).View object。 属性: Type,FullScreen,SplitSpecial

ShowStatusbar,ShowBookmarks,ShowFieldCodes,ShowParagraphs, ShowHiddenText,ShowTextBoundaries,ShowTabs,ShowSpaces, ShowDrawings, … …

方法: ShowHeading, AhowAllHeadings,

ExpandOutline,CollapseOutline, NextHeaderFooter,PreviousHeaderFooter

Type属性:Read/write Long. (window.View object) Returns or sets the view type.

Can be one of the following WdViewType constants:

WdMasterView(5), wdNormalView(1), wdOutlineView(2),

WdPrintPreview(4), wdPrintView(3), or wdWebView(6). SplitSpecial属性: ( window.View object only) Read/write Long.

Returns or sets the active window pane. Can be one of the following WdSpecialPane constants:

wdPaneNone(0)

wdPaneCurrentPageFooter, wdPaneCurrentPageHeader wdPaneFirstPageFooter, wdPaneFirstPageHeader wdPanePrimaryFooter, wdPanePrimaryHeader

wdPaneEvenPagesFooter, wdPaneEvenPagesHeader, WdPaneComments(15)

wdPaneFootnoteContinuationNotice, wdPaneFootnoteContinuationSeparator

wdPaneFootnotes, wdPaneFootnoteSeparator

wdPaneEndnoteContinuationNotice, wdPaneEndnoteContinuationSeparator wdPaneEndnotes, wdPaneEndnoteSeparator

写SplitSpecial属性可以Split(如果原未Split),并指定低pane用来显示什么。

但再一次置SplitSpecial属性为同一值,则取消split了(SplitSpecial变成wdPaneNone)。 例:下面的pane,用来显示Footnotes:

If ActiveDocument.ActiveWindow.Panes.Count=1 Then With ActiveDocument.ActiveWindow.View .Type = wdNormalView

.SplitSpecial = wdPaneFootnotes End With End If

Panes属性 (window object) Panes collection

属性: Count 方法: Item,Add Pane object

属性: Index, BrowseWidth,DisplayRulers,DisplayVerticaRuler, HorizontalPercentScrolled, VerticalPercentScrolled, MinimunFontSize, Frameset,

Next,Previous,Selection, Document, View, Zooms, Parent,Creator,Application 方法: Activate,Close,

AutoScroll,LargeScroll,SmallScroll,PageScroll, NewFrameset,TOCInFrameset

Zooms Property (Pane object)

Read-only. Returns a Zooms collection. Zooms Collection

包含6 个Zoom objects 。

方法/属性:只有 Item; Parent,Creator,Application Zooms(index)返回Zoom object ,其中index是 View Type:

WdMasterView(5), wdNormalView(1), wdOutlineView(2), WdPrintPreview(4), wdPrintView(3), or wdWebView(6).

Zoom object

每个pane用一Zoom对象window.Panes(i).Zooms(k)表示在特定view 类型k下的zoom 特性. window如果未split,用window.View.Zoom指向该View类型下的Zoom对象。即如果当前的 View.Type=k时,window.View.Zoom和window.Panes(1).Zooms(k)同效。 Zoom object 只有以下属性,用来表示zoom 特性:

Percentage, PageFit, PageRows, PageColumns (and Parent,Creator,Application)

Percentage属性:值N 表示Pane显示内容的缩放比例为 N%, N<100:缩小,N>100:放大。 N=100 表示恢复原状,不缩放。

注:window本身的size不变。放的太大,一行只能看到前面的部分了。

写Percentage属性后PageFit自动变成default(WdPageFitNone)。因此 Percentage和PageFit,只能用其一来zoom。彼此相互Override。

例:

With ActiveDocument.ActiveWindow.View .Type = wdNormalView

.Zoom.Percentage = .Zoom.Percentage + 10 End With

With ActiveDocument.ActiveWindow.ActivePane

.Zooms(wdNormalView).Percentage = .Zooms(wdNormalView).Percentage + 10 End With

PageFit属性: Read/write Long. 值可以是:

wdPageFitBestFit:随当前window size自动调整Percentage,使每行都完整显示,但放大 的比例尽可能大。

WdPageFitFullPage: in print view only 。 显示整页。 WdPageFitNone: default,只按Percentage缩放。 WdPageFitTextFit:(看不到效果。) 例:

With ActiveDocument.ActiveWindow.View .Type = wdNormalView

.Zoom.PageFit = wdPageFitBestFit End With

PageRows属性: Read/write Long. 值m, default=1 。 PageColumns属性: Read/write Long. 值n, default=1 。

在窗口中显示MxN页。呈 m行n列状。in print layout view/Preview only。 例.显示上下2页:

PrintPreview = True

With ActiveDocument.ActiveWindow.View.Zoom .PageColumns = 1 .PageRows = 2 End With

Dialogs

Dialogs Property ( Application/Global object)

Returns a Dialogs collection that represents all the built-in dialog boxes in Word.

Dialogs Collection

属性/方法: Count,Parent,Creator,Application; Item

Dialogs(index): index必须是wdWordDialig常数,如

wdWorgDialogFileOpen, wdWordDialogEditFind, …… 常数名的构成规则是 wdWordDialog + Menu名+Command名。 例:

With Dialogs(wdDialogFileOpen) .Name = \

.Show End With

Dialogs(wdDialogFilePrint).Execute

Dialog object

属性:Type,CommandName,DefaultTab,Parent,Creator,Application 方法:Display,Show, Execute,Update

Type属性:Read only. 是该Dialog的wdWordDialig常数 CommandName属性:Read only.是该Dialog的Procedure名。

例如: MsgBox Dialogs(wdDialogCopyFile).Type ?300, i.e. wdDialogCopyFile MsgBox Dialogs(wdDialogCopyFile).CommandName ?CopyFileA MsgBox Dialogs(wdDialogFileOpen).CommandName ?FileOpen

DefaultTab 属性:Read /Write, WdWordDialogTab constants

指定当该Dialog Box显示时,对话框的哪一tab(如果有多个tabs)被激活。 如wdDialogFormatFont dialog box有3个tabs:

WdWordDialogFormatFontTabFont, WdWordDialogFormatFontTabCharracterSpacing, WdWordDialogFormatFontTabAnimation

其他属性:Dialog object还有其他属性,依赖于dialog.Type。

你可设置这些属性,相当于在对话框上设置options。例如:

With Dialogs(wdDialogEditFind)

.Find = \‘ set “Find What” text .Show End With

With Dialogs(wdDialogFileOpen) .Name = \ .Show End With

Display方法 (Dialog object)

Displays the specified built-in Word dialog box until either the user closes it or the specified amount of time has passed. Syntax dialogObj.Display(TimeOut)

TimeOut Optional Variant. The amount of time that Word will wait before closing the dialog box automatically. One unit is approximately 0.001 second. Concurrent system activity may increase the effective time value. If this argument is omitted, the dialog box is closed only when the user closes it.

Returns a Long that indicates which button was clicked to close the dialog box:

Return value Description

-2 The Close button.

-1 The OK button. (自注:For SaveAs Dialog box, Save button) 0 (zero) The Cancel button.

(自注:For SaveAs Dialog, Cancel button or Close Button) > 0 (zero) A command button: 1 is the first button, 2 is the second button, and so on.

Note Any actions initiated or settings specified while a dialog box is displayed using

Display method aren't carried out. Use the Show method to display a dialog box and carry out actions or apply settings.

Example This example displays the About dialog box.

Set aDialog = Dialogs(wdDialogHelpAbout) aDialog.Display

Show 方法 ( Dialog object )

Displays and carries out actions initiated in the specified built-in Word dialog box. Syntax dialogObj.Show(TimeOut) 返回值同Display方法。

自注:Display方法只显示对话框,不管用户按都不会对文档产生任何效果。而Show方法显示对话框后(还可再设置options)按Ok则有效(相当于Execute方法),按Cancel则无效(相当于Display方法)。Execute方法则相当于Show并OK,但没有显示对话框,因而也不能交互式补充设置Options。以上记录被下述程序证实:

ActiveDocument.Paragraphs(8).Range.Select With Dialogs(wdDialogFormatParagraph)

.KeepWithNext = 1 (Checkbox = true, 置-1是灰的) .Display 'Show 'Execute End With

DialogObj.Update方法(也不显示对话框)是用当前Selection 来更新dialogObj对话框中的Options。然后你可接着再Display, Show,或Execute。

但若对话框提供的不是按钮,例如EditFind对话框,情形又不太一样。如有程序:

ActiveDocument.Paragraphs(9).Range.Select With Dialogs(wdDialogEditFind) .Find = \

.Display 'Execute 'Show End With

Show时,立刻执行了查找并找到了第一个 “W”(假设有),你可以再按(类似于OK,但不Close)或Cancel。Display时,显示了对话框,但并未查找。仅当按才找第一个 “W”。你也可以再按FindNext或Cancel。Execute时,不显示对话框,立刻找到了第一个 “W”,只此而已。

Execute方法 ( Dialog Objects)

Syntax dialogObj.Execute

Applies the current settings of a Word dialog box. Execute方法并不显示对话框。作用相当于.Show后按了按钮。

The following example enables the Keep with next check box on the Line and Page Breaks tab in the Paragraph dialog box .

ActiveDocument.Paragraphs(1).Range.Select With Dialogs(wdDialogFormatParagraph) .KeepWithNext = 1

.Execute 将wdDialogFormatParagraph对话框的 Format设置应用于Paragraph 1。 End With

附:KeyBinding Object和MailMerge object也有Execute方法

KeyBindingObj.Execute

Runs the command associated with the specified key combination.

This example assigns the CTRL+SHIFT+C key combination to the FileClose command and then executes the key combination (the document is closed).

CustomizationContext = ActiveDocument.AttachedTemplate Keybindings.Add KeyCode:=BuildKeyCode(wdKeyControl, _

wdKeyShift, wdKeyC), KeyCategory:=wdKeyCategoryCommand, _ Command:=\

FindKey(BuildKeyCode(wdKeyControl, wdKeyShift, wdKeyC)).Execute

本文来源:https://www.bwwdw.com/article/xvzd.html

Top