Script for changing fonts in a Word document

眉间皱痕 提交于 2020-01-21 19:39:40

问题


I have a Word 2007 file and I want to change all usage of the Courier New font into a Lucida Console font. I need a script that find all words formatted in that font and change it to the new font.

How can I do that?


回答1:


Inside Word, you can record a macro by doing it yourself. Then you open the VBA editor, optionally remove some useless thing (usually too many selections or moves within the file) and you've got your script.

Edited: moved the contents of a comment here, to answer the author's comment.

When recording the macro, within the find and replace dialog, click on 'Replace All'. Then stop recording. The generated macro looks like:

Selection.Find.ClearFormatting 
Selection.Find.Replacement.ClearFormatting 
With Selection.Find 
  .Text = "tarte au pomme" 
  .Replacement.Text = "t aux pruneaux" 
  .Wrap = wdFindContinue 
  .MatchCase = False 
  ' removed some stuff 
End With 
Selection.Find.Execute Replace:=wdReplaceAll 

From that, you can create the VBScript macro. You need to get the value of wdReplaceAll and wdFindContinue in the Object Browser.




回答2:


Perhaps you can use OpenXML SDK 2.0? You should be able to change the style (which is what contains the font information, I believe).




回答3:


This will do it for you:

Sub ChangeFonts() 
Dim doc As Document 
Set doc = ActiveDocument
    For i = 1 To doc.Range.Characters.Count 
        If doc.Range.Characters(i).Font.Name = "Courier New" Then 
            doc.Range.Characters(i).Font.Name = "Lucida Console" 
        End If 
    Next 
End Sub


来源:https://stackoverflow.com/questions/2339972/script-for-changing-fonts-in-a-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!