首页 > 解决方案 > 在现有的 Word 文档页脚表格中编辑和添加内容

问题描述

我有一个带有现有页眉和页脚的 Word Doc。在页脚内部有一个表格,其中包含一些单元格中的信息。我想知道在页脚表中编辑和添加更多内容的 Excel VBA 代码(例如更新单元格的信息或在空单元格中添加信息)。我面临的最大问题是我不知道如何引用页脚表中的单元格位置。

在此处输入图像描述

我正在使用 Office 2013 并尝试了以下方法:

- wDoc.Sections(1).Footers(wdHeaderFooterPrimary)

- wDoc.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter

-   Set rngFooter = wDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range
    With rngFooter
        .ParagraphFormat.Alignment = 1
        .Text = "Some text"
        .Move Unit:=wdColumn, Count:=1
        .Text = "More Text at center: hyperlink"
        .Move Unit:=wdColumn, Count:=1
        .Text = "Page 1 of 1"
        .Move Unit:=wdRow, Count:=1
        .Text = "New Text in empty cell"
        With .Font
          .Size = 9
          .Name = "Arial Narrow"
        End With
    End With

- wDoc.Sections(1).Footers.Select

在第三种方法的情况下,我得到以下信息:

第三种方法代码的页脚结果

在此处输入图像描述

标签: excelvbams-wordfooter

解决方案


为了访问文档页脚中的表格单元格,Table需要一个对象。从那里,可以通过它们的单元格索引值访问各个单元格。下面的代码示例假定单元格的内容应该被替换,而不是附加到。

注意:更正确的是,不应直接应用整个页脚的格式。相反,应该更改页脚样式的定义。

Dim rngFooter as Word.Range
Dim tbl as Word.Table
Dim rngCell as Word.Range

    Set rngFooter = wDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range
    With rngFooter
        Set tbl = rngFooter.Tables(1)
        SEt rngCell = tbl.Cell(1,1).Range
        With rngCell
          .ParagraphFormat.Alignment = 1
          .Text = "Some text"
        End With
        Set rngCell = tbl.Cell(1,2).Range
        rngCell.Text = "More Text at center: hyperlink"

        Set rngCell = tbl.Cell(1,3).Range
        rngCell.Text = "Page 1 of 1"

        With .Font
          .Size = 9
          .Name = "Arial Narrow"
        End With
    End With

推荐阅读