views:

70

answers:

3

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  A: 

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).

Moron
+2  A: 

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.

Timores
good but the macro should do that for every courier word found and with the macro recorder I must go on every word and than run that macro!!! May be an iterative procedure...
xdevel2000
Set `.Text = ""` and `.Replacement.Text = ""`. Then this will outperform all other alternatives!
Andreas Rejbrand
+1  A: 

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
Otaku
+1 nice. vba is alive and well
Byron Whitlock
Why do it manually when you can simply Replace All?
Andreas Rejbrand
Because the recursion is faster than `Selection.Find` and works in `Story` other than the main body (headers, footers, etc.).
Otaku
@Otaku: OK, you might be right.
Andreas Rejbrand