本主题包含下列任务的 Visual Basic 示例:
View 对象包含与窗口或窗格的视图属性相关的属性和方法(全部显示、域底纹、表格网格线等)。下列示例将视图更改为页面视图。
Sub ChangeView()
ActiveDocument.ActiveWindow.View.Type = wdPrintView
End Sub
由 Headers、Footers 和 HeaderFooter 属性返回 HeaderFooter 对象。下列示例更改当前页眉中的文字。
Sub AddHeaderText()
With ActiveDocument.ActiveWindow.View
.SeekView = wdSeekCurrentPageHeader
Selection.HeaderFooter.Range.Text = "Header text"
.SeekView = wdSeekMainDocument
End With
End Sub
该示例创建一个 Range 对象 (rngFooter
),该对象引用活动文档中第一节的主页脚。设置 Range 对象之后,删除现有的页脚文字,并在页脚中添加 FILENAME 域、两个制表符和 AUTHOR 域。
Sub AddFooterText()
Dim rngFooter As Range
Set rngFooter = ActiveDocument.Sections(1) _
.Footers(wdHeaderFooterPrimary).Range
With rngFooter
.Delete
.Fields.Add Range:=rngFooter, Type:=wdFieldFileName, Text:="\p"
.InsertAfter Text:=vbTab & vbTab
.Collapse Direction:=wdCollapseStart
.Fields.Add Range:=rngFooter, Type:=wdFieldAuthor
End With
End Sub
Options 对象包含的属性对应于“工具”菜单的“选项”对话框中的各项。下列示例设置 Word 的三个应用程序选项。
Sub SetOptions()
With Options
.AllowDragAndDrop = True
.ConfirmConversions = False
.MeasurementUnit = wdPoints
End With
End Sub
PageSetup 包含文档的所有页面设置属性(左边距、下边距、纸张大小等),并作为其自身的属性。下列示例设置活动文档的页边距。
Sub ChangeDocumentLayout()
With ActiveDocument.PageSetup
.LeftMargin = InchesToPoints(0.75)
.RightMargin = InchesToPoints(0.75)
.TopMargin = InchesToPoints(1.5)
.BottomMargin = InchesToPoints(1)
End With
End Sub
本示例循环遍历活动文档中的所有段落。如果某段落的段前间距为 6 磅,则本示例将该段前间距更改为 12 磅。
Sub LoopParagraphs()
Dim parCount As Paragraph
For Each parCount In ActiveDocument.Paragraphs
If parCount.SpaceBefore = 12 Then parCount.SpaceBefore = 6
Next parCount
End Sub
详细内容,请参阅循环遍历一个集合。
CommandBar 对象同时代表菜单和工具栏。可使用菜单或工具栏名称的 CommandBars 属性返回单独的 CommandBar 对象。Controls 属性返回一个 CommandBarControls 对象,该对象引用指定命令栏上的项。下列示例将“字数统计”命令添加至“常用”菜单。
Sub AddToolbarItem()
Dim btnNew As CommandBarButton
CustomizationContext = NormalTemplate
Set btnNew = CommandBars("Standard").Controls.Add _
(Type:=msoControlButton, ID:=792, Before:=6)
With btnNew
.BeginGroup = True
.FaceId = 700
.TooltipText = "Word Count"
End With
End Sub
下列示例将“双下划线”命令添至“格式”工具栏。
Sub AddDoubleUnderlineButton()
CustomizationContext = NormalTemplate
CommandBars("Formatting").Controls.Add _
Type:=msoControlButton, ID:=60, Before:=7
End Sub
打开宏录制器,并自定义一个菜单或工具栏,以确定某个命令的 ID 值(例如,ID 60 是 “双下划线”命令)。