Roy Osherove

View Original

Style Macros for technical authors working in Word

One of the things you do as an author of a book working in MS Word, is do a lot of formatting on the text that you write. When working with the manning word templates, for example, you are expected to use a list of built in text styles that manning created, with names such as ".body" and "code" for formatting different elements in your text.

 

It's quite tedious to use the mouse to set styles on text selections, and as a keyboard junky it bothered me that you can't have specific shortcuts to set the style of the selection.

A solution to this can be made by creating custom macros in word, each setting the selection to a different style, and then attaching a special keyboard shortcut to each of these macros.

this process in itself is quite tedious and time consuming, but I've done it. now you don't have to. I've even automated the creation of the special keybaord shortcuts.

Steps to make:

  1. In word, press ALT-F11 or open the macros editor
  2. Paste in the code for the macros in VBA as shown below.
  3. Customize the styles names that each "formatXX" method sets to match the styles you'd like.
  4. Customize the letters for the shortcuts as you wish in the "InstallAllMacros" method (it's Ctrl-Alt-[letter])
  5. Put the cursor inside the method named "InstallAllMacros" and press F5 to run it. when it has finished running you will have shortcuts as written in the method for the specific styles. The shortcuts are all in the form of Ctrl+Alt+[letter] which is shown in the method you just ran.
  6. You can now get back to work.

VBA Code for settings styles automatically:

Sub InstallAllMacros()
    Call InstallMacro("FormatBody", wdKeyB)
    Call InstallMacro("FormatCodeChar", wdKeyH)
    Call InstallMacro("FormatCode", wdKeyC)
    Call InstallMacro("FormatHeader1", wdKey1)
    Call InstallMacro("FormatHeader2", wdKey2)
    Call InstallMacro("FormatHeader3", wdKey3)
    Call InstallMacro("FormatFigure", wdKeyF)
End Sub

Sub FormatCodeChar()
    Call FormatSel(".Code Char")
End Sub
Sub FormatFigure()
    Call FormatSel(".Figure")
End Sub

Sub FormatHeader1()
    Call FormatSel(".Head 1")
End Sub

Sub FormatHeader2()
    Call FormatSel(".Head 2")
End Sub

Sub FormatHeader3()
    Call FormatSel(".Head 3")
End Sub

Sub FormatCode()
    Call FormatSel(".Code")
    Selection.ParagraphFormat.Alignment = wdAlignParagraphLeftEnd
End Sub
Sub FormatBody()
    Call FormatSel(".Body")
End Sub

Sub InstallMacro(CommandName As String, Key1 As WdKey)
    CustomizationContext = NormalTemplate
    KeyBindings.Add wdKeyCategoryCommand, CommandName, BuildKeyCode(Key1, wdKeyAlt, wdKeyControl)
End Sub

Sub FormatSel(StyleName As String)
    Selection.Style = ActiveDocument.Styles(StyleName)
End Sub

 

Have fun. Hope this saves you as much time as it did for me.