我已在相应的MSDN article中测试了示例代码:
Sub WorkWithPages()
' Fill random data:
Range("A1", "R100").Formula = "=RANDBETWEEN(1, 100)"
Dim pgs As Pages
Set pgs = PageSetup.Pages
PageSetup.DifferentFirstPageHeaderFooter = True
' Look in the Immediate window for this output:
Debug.Print "The current sheet can be printed on " & _
pgs.Count & " page(s)."
Dim pg As Page
Set pg = pgs(1)
pg.CenterHeader.Text = "This is the first page's header"
Set pg = pgs(2)
pg.CenterFooter.Text = "This is the second page's footer"
Set pg = pgs(pgs.Count)
pg.CenterFooter.Text = "This is the last page's center footer."
pg.LeftHeader.Text = "This is the last page's header"
' Note that Excel supports only distinct headers/footers
' for the first page, so headers and footers on the second
' and other pages are combined--the last value set overwrites
' the header/footer.
' See the values in the Immediate window.
' Note that the code disregards errors that occur--attempting
' to retrieve a header/footer setting that doesn't exist raises an error:
On Error Resume Next
Debug.Print "First page (CenterHeader) : " & pgs(1).CenterHeader.Text
Debug.Print "Second page (CenterHeader): " & pgs(2).CenterHeader.Text
Debug.Print "Second page (CenterFooter): " & pgs(2).CenterFooter.Text
Debug.Print "Third page (CenterFooter) : " & pgs(3).CenterFooter.Text
Debug.Print "Last page (LeftHeader) : " & pgs(pgs.Count).LeftHeader.Text
Debug.Print "Last page (CenterFooter) : " & pgs(pgs.Count).CenterFooter.Text
' In conclusion, use the Page class to retrieve information about headers
' and footers for specific pages. Use the PageSetup object to set the headers
' and footers, as it's clearer to set them there.
End Sub
但Debug.Print "Second page (CenterFooter): " & pgs(2).CenterFooter.Text
行输出的值与预期值不同:
Second page (CenterFooter): This is the last page's center footer
而不是右:Second page (CenterFooter): This is the second page's footer
。
我尝试了不同的东西,但CenterFooter
始终保持最后一个输入值。如何更改此行为,以便每个页面都能获得我想要的确切页脚?
答案 0 :(得分:1)
有不同的页脚/标题配置,但它们都不允许为每个页面写入不同的值。您可以为第一页和偶数/不均匀页面编写不同的文本;您也可以添加一些formatting页面的某些变体页面(例如,页码),但就是这样。在Word中,规则是等效的。
关于您提供的MSDN代码,其中一条评论说:
请注意,Excel仅支持第一个不同的页眉/页脚 页面,所以第二页和其他页面上的页眉和页脚是 合并 - 最后一个值集将覆盖页眉/页脚。
因此这段代码实际上按预期工作;虽然一见不太清楚。
答案 1 :(得分:0)
我知道这是从死里复活一个线程,但这实际上在Excel VBA中是可行的。我不得不弄清楚,因为我在这里找不到可接受的解决方案,所以我将其留给下一个可怜的草皮:
解决方案是创建一个子例程来设置页眉和页脚,然后在另一个子集中的循环中调用该例程,一次调用每个工作表并通过变量管理要说的内容。
是这样的:
Sub InsertQuoteHeaderAndFooter(ByVal shtHeader As Worksheet, strText$)
shtHeader.PageSetup.RightFooter = "&""Calibri"" &8 &K434643" & strTxt & " | &P of &N"
End Sub
然后在For循环中调用它,根据需要调制shtHeader和strText。希望这对下一位考古学家有所帮助。