首页 > 解决方案 > 使用 vba 编辑 Microsoft Word 标题中的锚点位置

问题描述

我正在研究一个 VBA 宏,我自己只编写了它的一部分,用于改变页面方向的 MS-Word,然后将前一页的页眉和页脚复制到新页面和其他一些东西:

Selection.PageSetup.Orientation = wdOrientLandscape
ActiveDocument.Sections.Last.PageSetup.DifferentFirstPageHeaderFooter = False

ActiveDocument.Sections(ActiveDocument.Sections.Last.index - 1).Headers(wdHeaderFooterPrimary).Range.Select
Selection.Copy

ActiveDocument.Sections.Last.Headers(wdHeaderFooterPrimary).Range.Select
Selection.Paste

ActiveDocument.Sections.Last.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
ActiveDocument.Sections.Last.Footers(wdHeaderFooterPrimary).LinkToPrevious = False

formatHeader wdHeaderFooterPrimary
formatHeader wdHeaderFooterFirstPage

TextBox 中有一个文本锚定到标题。我现在要做的是更改其在“横向”方向的页面上的位置。

如何更改布局选项(见下图)?我一直找不到任何信息。

这是将页面方向更改为“横向”后我的文档的样子:

如您所见,TextBox 中侧面的段落不在中间。所以我想把它移高一点。您还可以在此图像中看到锚点。

这就是我作为用户在 Word 中的操作方式:

在此处输入图像描述 在此处输入图像描述

标签: vbams-wordanchorword-2010

解决方案


关键是设置应从 ( RelativeHorizontalPosition) 进行测量的位置,然后使用 Shape 的Left设置。相对于几乎任何东西,除了wdCharacter水平位置之外,在编辑文本时页面上的位置都是静态的;垂直,wdLine相当于wdParagraph使用“移动文本”。

通过为最后一个部分和形状声明和使用对象,我已经简化了您发布的代码。

此代码不是复制和粘贴,而是用于Range.FormattedText将内容从一个标头复制传输到另一个标头。对于那些可以工作的情况(在任何两个单词范围之间),这比使用剪贴板更可取。

Dim secLast as Word.Section
Dim shp as Word.Shape

Set secLast = ActiveDocument.Sections.Last
secLast.PageSetup.Orientation = wdOrientLandscape
secLast.PageSetup.DifferentFirstPageHeaderFooter = False
secLast.Headers(wdHeaderFooterPrimary).Range.FormattedText = _
  ActiveDocument.Sections(secLast.index - 1).Headers(wdHeaderFooterPrimary).Range.FormattedText

secLast.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
secLast.Footers(wdHeaderFooterPrimary).LinkToPrevious = False

formatHeader wdHeaderFooterPrimary
formatHeader wdHeaderFooterFirstPage

Set shp = secLast.Range.Shapes(1)
shp.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage 
shp.Left = 33 ' Or you can use, for example CentimetersToPoints(1.4)
shp.RelativeVerticalPosition = wdRelativeVerticalPositionPage
shp.Top = CentimetersToPoints(14)

推荐阅读