第一范文网 - 专业文章范例文档资料分享平台

Word VBA(2)

来源:用户分享 时间:2020-06-09 本文由雾涣风月 分享 下载这篇文档 手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

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.

搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新IT计算机Word VBA(2) 全文阅读和word下载服务。

Word VBA(2) .doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/wenku/1078297.html(转载请注明文章来源)
热门推荐
Copyright © 2018-2022 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top