italicize "the Ns and Ps"

setup

i've come across a journal that's quite specific about formatting. one of the specifications was to italicize all instances of N/n and P/p when they're representing sample size and p value, respectively. i had to work fast since this and other revisions were to be completed under a tight deadline. so, perhaps going batch is a viable path ...

solution

the plan

  1. using selection.find, keywords being N/n/P/p followed by '=', '<', '<=', '>', or '>=', e.g. 'N=', 'p < ',
  2. italicize the 'N/n/P/p' portion of the hit,
  3. repeat until all instances are formatted.

programming language & module(s)

  • VBA

file preps

  • make the doc to apply formatting to has to be the active document, i.e. where the cursor's currently in.

variables to customize

none

the script

italicizeTheNs
Sub italicizeTheNs()
Dim doc As Document
Dim trkRevStatus As Boolean
Dim selStart, selEnd, safeCount As Long
Dim lan As String
Dim kwColl As Collection
Application.ScreenUpdating = False
System.Cursor = wdCursorWait
Set doc = ActiveDocument
trkRevStatus = doc.TrackRevisions
doc.TrackRevisions = False
selStart = Selection.Start
selEnd = Selection.End
clearFind
Set kwColl = New Collection
kwColl.Add "[NnPp][=<≤>≥]"
kwColl.Add "[NnPp] [=<≤>≥]"
kwColl.Add "[Nn] \(%\)"
kwColl.Add "[Nn], %"
kwColl.Add "[Pp]-value"
kwColl.Add "[Pp] value"
For Each kw In kwColl
With Selection
.HomeKey wdStory
With .Find
.MatchWildcards = True
.Wrap = wdFindStop
.Text = kw
End With
safeCount = 0
Do While .Find.Execute And safeCount < 1000
safeCount = safeCount + 1
doc.Range(.Start, .Start + 1).Font.Italic = True
Loop
Next
clearFind
doc.Range(selStart, selEnd).Select
doc.TrackRevisions = trkRevStatus
System.Cursor = wdCursorNormal
Application.ScreenUpdating = True
End Sub
Sub clearFind()
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End Sub

output

none. note that the macro does not save the doc. instead, the decision is retained for the user.

note to self

  • remember that only the first character of the .find hits are italicized.
  • add kw in the kwColl to accommodate for more scenarios that need the formatting.
  • may need to tweek safeCount < 1000 in extreme cases where're a scary lot of "the Ns".
Some rights reserved
Except where otherwise noted, content on this page is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.