Word: Macro to replace some hyphens with en dashesMay 16, 2014
I run several find/replace routines on most of the documents I edit. One is to replace <space><hyphen><space> with <space><en dash><space>, and another is to find any number range separated by a hyphen not an en dash (e.g. 2013-2014 or p35-47), and replace the hyphen with an en dash (e.g. 2013–2014, p35–47).
So I decided to automate this process by recording a macro for each find/replace routine, then I combined those macros into one. I could assign a keystroke combination to it, but as I only run it once on each document, there’s probably not a lot of value in doing that. The whole process takes just a few seconds, even on a long document.
CAUTION: If you have numbers legitimately separated by hyphens (e.g. document numbers like 1234-567-890) this macro will replace the hyphens in those numbers with en dashes too, which may not be what you want. A workaround if you only have a few numbers of this type is to run this macro, and then manually change those few it replaced incorrectly.
Here’s the macro:
Sub ReplaceHyphenWithEnDash() ' ' ReplaceHyphenWithEnDash Macro ' ' The first part of this macro replaces space hyphen space ' with space en dash space Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = " - " .Replacement.Text = " ^= " .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll ' The second part of this macro finds a number range separated ' by a hyphen and replaces the hyphen with an en dash Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "([0-9])(-)([0-9])" .Replacement.Text = "\1^=\3" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchAllWordForms = False .MatchSoundsLike = False .MatchWildcards = True End With Selection.Find.Execute Replace:=wdReplaceAll End Sub
There may be a simpler way to write this macro, but as I’m not a VBA developer and as this worked for me, I’ll leave it as it is!