VBA Excel - Unlink headers & footers in Word

2019-09-17 08:23发布

I have discovered after many hours of investigating that the code:

objWord.ActiveDocument.Fields.Unlink

Only unlinks the fields in the body of a Word document that is linked via "Paste Special > Paste Link" to Excel but leaves the headers and footers linked.

What would be the code to unlink header and footer fields as well?

I have found some code online that could be along the right path and something to work with.....

Dim oField  As Field 
 Dim  oSection  As Section 
 Dim  oHeader  As HeaderFooter 
 Dim  oFooter  As HeaderFooter 

 For Each  oSection  In  ActiveDocument.Sections 

     For Each  oHeader  In  oSection.Headers 
         If  oHeader.Exists  Then 
             For Each  oField  In  oHeader.Range.Fields 
                 oField.Unlink 
             Next  oField 
         End If 
     Next  oHeader 

     For Each  oFooter  In  oSection.Footers 
         If  oFooter.Exists  Then 
              For Each  oField  In  oFooter.Range.Fields 
                  oField.Unlink 
             Next  oField 
         End If 
     Next  oFooter 

 Next  oSection 

I understand the above won't work just copied and pasted into the userform module as it is code intended for Word. I do not have the knowledge to modify it so that it works from Excel.

1条回答
戒情不戒烟
2楼-- · 2019-09-17 08:44

To resolve this, I placed the code I poseted in the question into the VBA of the Word document in a sub called UnlinkHeader, rather than Excel, and simply called it from Excel.

Call objWord.Run("UnlinkHeader")
查看更多
登录 后发表回答