簡體   English   中英

使用 VBA 在 Word 中編輯特定的頁腳列

[英]Editing a specific footer column in Word with VBA

我正在嘗試在 Word 中編輯三列頁腳的右側列。 我可以很好地編輯整個頁腳,但我想保持前兩列完好無損。

Public WithEvents App As Word.Application

Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
     'ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text = "my value"
End Sub

我見過各種編輯頁眉和頁腳的解決方案,但沒有一個只編輯分離頁腳的特定部分。 我開始懷疑頁腳是否只是被定義為一個無法通過左/右分隔部分區分的大字段。

有誰知道這是否可能?

下面的代碼應該可以幫助你。 只需取消注釋您要編輯的頁腳部分的相關代碼塊

Sub EditFooterText(ByVal Doc As Document, NewText As String)
   Dim footerRange As Range
   Dim leftTab As Long, rightTab As Long, footerLength As Long
   Set footerRange = Doc.Sections(1).Footers(wdHeaderFooterPrimary).Range
   With footerRange
      'find the tabs
      leftTab = InStr(.Text, vbTab)
      rightTab = Len(.Text) - InStrRev(.Text, vbTab)
      
      'to edit the left text
'      .Collapse wdCollapseStart
'      .MoveEnd wdCharacter, leftTab - 1
      
      'to edit the centre text
'      .Collapse wdCollapseStart
'      .Move wdCharacter, leftTab
'      .MoveEnd wdCharacter, rightTab
      
      'to edit the right text
      .Collapse wdCollapseEnd
      .MoveStart wdCharacter, (0 - (rightTab - 1))
      
      .Text = NewText
   End With
End Sub

如果您從BeforeSave事件調用它,您可以使用以下內容:

Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
     EditFooterText Doc, "my value"
End Sub

如果頁腳由對齊選項卡分隔,看起來與打開顯示/隱藏的普通選項卡相同,但具有不同的字符代碼,那么您可以使用以下例程:

Sub EditFooterTextWithAlignmentTabs(ByVal Doc As Document, NewText As String)
   Dim footerRange As Range
   Dim leftTab As Long, rightTab As Long, footerLength As Long
   Set footerRange = Doc.Sections(1).Footers(wdHeaderFooterPrimary).Range
   With footerRange
      'find the tabs
      leftTab = InStr(.Text, Chr(48))
      rightTab = Len(.Text) - InStrRev(.Text, Chr(48))
      
      Debug.Print leftTab
      Debug.Print rightTab
      
      'to edit the left text
'      .Collapse wdCollapseStart
'      .MoveEnd wdCharacter, leftTab - 1
      
      'to edit the centre text
'      .Collapse wdCollapseStart
'      .Move wdCharacter, leftTab
'      .MoveEnd wdCharacter, rightTab
      
      'to edit the right text
      .Collapse wdCollapseEnd
      .MoveStart wdCharacter, (0 - (rightTab - 1))
      
      .Text = NewText
   End With
End Sub

您可以通過在立即窗口中鍵入?AscW(Selection.Text)來獲取所選字符的 unicode 值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM