我有一个包含现有页眉和页脚的Word文档。在页脚内部有一个表格,其中某些单元格包含信息。我想知道在页脚表中编辑并添加更多内容的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
在第三种方法的情况下,我得到以下信息:
第三个方法代码的页脚结果
答案 0 :(得分: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
答案 1 :(得分: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文档。