Word VBA获取特定节中带格式的页脚页码问题
Hey there, let's work through this problem together. You're trying to grab the formatted page number string (like 1-1 or Roman numerals) from a specific section's footer, but you're stuck on targeting that section's footer instead of the global template. Here's how to fix this:
First, target the specific section's footer
Word lets you access footers per-section, not just the global ones. Each section has three possible footer types: primary (normal pages), even pages, and first page. Use theSectionscollection to pick your target section, then grab the right footer:Dim targetSection As Section Dim targetFooter As Footer ' Replace 2 with your actual section index (starts at 1) Set targetSection = ActiveDocument.Sections(2) ' Use wdHeaderFooterEvenPages for even pages, wdHeaderFooterFirstPage for first page Set targetFooter = targetSection.Footers(wdHeaderFooterPrimary)Next, loop through fields to extract the Page field's value
Once you have the right footer, iterate through its fields to find thewdFieldPagetype. Update the field first to get the latest value, then pull the formatted text from the field's result:Dim fld As Field Dim formattedPageNum As String formattedPageNum = "" For Each fld In targetFooter.Range.Fields If fld.Type = wdFieldPage Then fld.Update ' Make sure we have the most current page number formattedPageNum = fld.Result.Text ' This gets the formatted string directly Exit For ' No need to check other fields once we find the Page field End If Next fld ' Check if we found the field and output the result If formattedPageNum <> "" Then MsgBox "Formatted page number: " & formattedPageNum Else MsgBox "No Page field found in this footer." End IfA quick note on linked footers
If your section's footer is set to "Link to Previous", thetargetFooter.LinkToPreviousproperty will beTrue. In this case, the footer content is inherited from the previous section, so you'll need to either unlink it first or access the linked section's footer to get the Page field data.
The best part? This method will capture whatever formatted page number you have set—whether it's chapter-based (like 1-1), Roman numerals, or plain numbers—since the fld.Result.Text pulls the rendered, formatted output directly from the field.
内容的提问来源于stack exchange,提问作者nafarkash

