使用VBA在Word 2010页面标题中插入两个字段 [英] Insert two fields in Word 2010 page header using VBA

查看:135
本文介绍了使用VBA在Word 2010页面标题中插入两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在页面标题中插入两个字段。我可以在当前选择中插入它们(请参阅下面的代码),但我不希望在插入字段之前选择页眉。

I am trying to insert two fields in a page header. I am able to insert them at the current selection (see code below), but I would prefer not having to select the page header before inserting the fields. Can this be done?

Sub insertFields()
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True
End Sub


推荐答案

文档放置字段以及头部类型( wdHeaderFooterPrimary wdHeaderFooterFirstPage

If you specify the section of the document to place the field in as well as the type of header (wdHeaderFooterPrimary, wdHeaderFooterFirstPage or wdHeaderFooterEvenPages) you can use this code:

Dim myRange As Range
Set myRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="DOCPROPERTY LastSavedTime ", PreserveFormatting:=True

其他信息回复评论

您可以使用 Collapse 方法将插入点放置在范围的开始或结束位置,以在标题中插入多个字段。添加适当的附加代码以插入空格,格式化或回车符:

You can use the Collapse method, which places the insertion point at the start or end position of a range, to insert multiple fields within the header. Add appropriate additional code to insert spaces, formatting or carriage returns:

myRange.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="FileName", PreserveFormatting:=True

这篇关于使用VBA在Word 2010页面标题中插入两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆