0

我有一个带有现有页眉和页脚的 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

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

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

在此处输入图像描述

4

2 回答 2

0

为了访问文档页脚中的表格单元格,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
于 2019-07-02T14:48:56.240 回答
0

我发现以下方法可以解决我原来的问题:

    'Create a range from bookmark inside table cell
    Set firstRng = wDoc.Bookmarks("FirstCell").Range

    'Add or replace text in range created
    firstRng.Text = "Some text"

    'Create again the bookmark. It was deleted on the previous line 
    wDoc.Bookmarks.Add "FirstCell", firstRng

    Set secondRng = wDoc.Bookmarks("SecondCell").Range
    secondRng.Text = "More Text at center: hiperlink"
    wDoc.Bookmarks.Add "SecondCell", secondRng

    Set thirdRng = wDoc.Bookmarks("ThirdCell").Range
    thirdRng.Text = "Page 1 of 1"
    wDoc.Bookmarks.Add "ThirdCell", thirdRng

    Set fourthRng = wDoc.Bookmarks("FourCell").Range
    fourthRng.Text = "New Text in empty cell"
    wDoc.Bookmarks.Add "FourCell", fourthRng

    Set fifthRng = wDoc.Bookmarks("FifthCell").Range
    fifthRng.Text = "More New Text in empty cell"
    wDoc.Bookmarks.Add "FifthCell", fifthRng

运行代码后的页脚表。

要使上述代码正常工作,必须先在 Word 文档中创建书签。

此外,此方法适用于在文件中任何部分的任何位置编辑 Word 文档。

于 2019-07-04T19:41:41.610 回答