Etudes for Microsoft Word Programmers

Home ] Up ] Etude 1.1. Text Fit ] Etude 1.2. Symbol Case ] Etude 1.3. Finding and Painting Hyperlinks ] Etude 1.4. Styles ] Etude 1.5. Inserting Formatted Text ] Etude 1.6. Text in the Column. ] Etude 1.7. Formatting Headline. ]


Etude 1.4. Styles

Style (1 syl.) is from the Latin stylus (an iron pencil for writing on waxen tablets, etc.). The characteristic of a person's writing is called his style. Metaphorically it is applied to composition and speech. Good writing is stylish, and, metaphorically, smartness of dress and deportment is so called.

"Style is the dress of thought, and a well-dressed thought, like a well-dressed man, appears to great advantage."- Chesterfield: Letter ccxl. p. 361.

http://www.websters-online-dictionary.org/definition/style

The styles are intended for grouping numerous text formatting attributes. The "applying style" operation is usually performed with the help of the tool "Format Painter", its icon represents a paint . But instead of changing several attributes for the selected text and then reproducing the formatting again and again for other selections, it is much easier to save all the necessary attributes as a style and then just apply the created style as many times as it is needed. It saves effort.

You may collect the sets of favorite styles and easily transfer them from one document to another, from a document to a template, and vice versa. In addition, the text formatted by the given style is easy to be found and/or replaced; and you may replace not only the text itself, but also the formatting, just using some other style.

In the section "Find and Replace Using Styles" (see below) I fulfill my promise, given in the previous Etude 1.3 (Task 3 "Find and Replace"). I speak about the fixing of the "find and replacement" bug in the code produced by Microsoft Word automatic macros generator.

Resources

Template "AhTextStyles.dot", 35 Kb, ZIP [download].

 

Task. Style Object and Styles Collection.

It is natural to find out what a Microsoft Word Style is before stating or solving the problem with styles. The special page is dedicated to Styles in the Appendix.

Along with the properties of the Style Object and the Styles Collection, the properties of the aggregated objects, such as Font, Border, Frame, Shading, ParagraphFormat and some others are also put into consideration. Separate page is dedicated to Color Management (enumerations Color and ColorIndex).

Brief contents of the Appendix reference files are given in the following table. It is worth getting acquainted with it (and, certainly, with corresponding objects as well) while working with this etude.

Color Color. The properties Color and ColorIndex are usually used for Object Color Management.
Border "Border" Object.
"Borders and Shading" dialog.
Enumeration WdLineStyle – line styles.
Frame "Frame" Object.
"Frame" dialog.
Enumeration WdFrameSizeRule
Enumeration WdFramePosition
Enumeration WdRelativeHorizontalPosition
Enumeration WdRelativeVerticalPosition
Shading "Shading" Object.
"Borders and Shading" dialog.
Enumeration WdTextureIndex.
Font "Font" Object.
Enumeration WdAnimation.
Enumeration WdUnderline – underlining styles.
Enumeration wdEmphasisMark.
ParagraphFormat "ParagraphFormat" Object.
Enumeration WdParagraphAlignment – paragraph alignments.
Enumeration WdBaselineAlignment – base line alignments.
Enumeration WdLineSpacing.
Enumeration WdOutlineLevel.
Style "Style" Object.
Enumeration WdStyleType – style types.
"Styles" Collection.
Enumeration WdBuiltinStyle – built-in styles.

The examples, given in the Appendix demonstrate that working with styles is rather easy. If you switch on macros recording, create a new style and then look at the generated code it will be evident that the definition of style includes several dozens of parameters. The example of such code is given further.

"Find and Replace" Using Styles

As it was said above, the text formatted by a given style is easy to be found and/or replaced. And the replacement may consist in using some other style. As simple as that. To replace a style use the button "Format" of the "Find and Replace" dialog.

On the picture below: the "Find and Replace" dialog, in which the "AH_BYLINE_1" style with the Bold Font attribute is set for finding and "AH_BYLINE_2" style is set for replacement. Note, that both "Find what" and "REplace with" fields are empty - we are going to search formatting attributes.

If you switch on the macros generator before setting the Find Object attributes, the following code will be generated.

'
' AhReplaceStyleTest
'
Sub AhReplaceStyleTest()
'
' AhReplaceStyle Macro
' Macro recorded 2/1/2006 by Evgeny Akhundzhanov
'
'
' Find Object formatting
'
    Selection.Find.ClearFormatting
    Selection.Find.Style = ActiveDocument.Styles("AH_BYLINE_1")
    Selection.Find.ParagraphFormat.Borders.Shadow = False
'
' Due to the bug in MS Word Macro Generator
' changes in font attributes don't reflect in VBA code.
' You need to add the required attributes manually.
'
    Selection.Find.Font.Bold = True
   
'
' Replacement Object formatting
'
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Style = ActiveDocument.Styles("AH_BYLINE_2")
    Selection.Find.Replacement.ParagraphFormat.Borders.Shadow = False
    ' Selection.Find.Replacement.Font.Italic = True
    With Selection.Find
        .Text = ""               ' we are searching for formatting attributes
        .Replacement.Text = ""   ' not for text
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

 
 
 

 

The code for the font attributes for Find and Replacement objects is not generated automatically because of the error in the macros generator. The corresponding code should be added manually. Otherwise the macro will not work properly.

In the code sample above the following line has been added manually.

Selection.Find.Font.Bold = True

Replacement object font attributes change is made in a similar way:

Selection.Find.Replacement.Font.Italic = True

Functional Specification

Task

The task is to create the template "AhTextStyles.dot", in which the macros for working with styles are accommodated. The toolbar "AhTextStyles" should provide quick access to the operations of creation and removal of the user’s set of styles, and also to applying of the user’s styles "1" and "2" to the selected text.

Toolbar "AhTextStyles"

The toolbar "AhTextStyles" looks like this:

Brief description of the toolbar buttons is given in the following table:

Button

Description

Help

Brief prompt on the toolbar buttons

Create

Creation of the styles AhHeadlineStyle1 and AhHeadlineStyle2.

Delete

Removal of the styles AhHeadlineStyle1 and AhHeadlineStyle2.

Style1

Applying of the AhHeadlineStyle1 style to the selected text.

Style2

Applying of the AhHeadlineStyle2 style to the selected text.

Fonts Demo

Creation of a new document with the samples of all fonts, installed in the system.

Help

Brief prompt on the toolbar buttons looks like this:

Creating Styles

When you press the button "Create", the styles "AhHeadlineStyle1" and "AhHeadlineStyle2" are created. In case of existence of the style with this name the message appears and the style is not redefined.

Deleting Styles

When you press the button "Delete", the styles "AhHeadlineStyle1" and "AhHeadlineStyle2" are deleted. In case of absence of the styles with such names nothing happens.

Applying Style1

Applying of the Style 1 is reflected on the following picture:

 

Applying Style2

The parameters of the Frame object are set in the definition of the Style 2.

Applying of the Style 2 is reflected on the following picture:

 

At the attempt of editing the text, formatted by the Style 2, the frame is displayed.

 

Fonts Demo

A part of the document which demonstrates the samples of fonts installed in the system is given in the table below. The document was generated automatically with the help of the macros AhTextFontsDemo. In its turn, the macros AhTextFontsDemo is based on the macros of the FontSampleGenerator module of the "Macros9.dot" template. The "Macros9.dot" template was created in Microsoft Technical Support. The macros were adopted by the author at the time of studying of someone else’s experience. The author is in the general habit of adopting everything that is interesting in the process of working or studying. Note that the created document can be easily printed.

Implementation - Template "AhTextStyles.dot"

Simple operations for working with the styles are implemented in the template "AhTextStyles.dot". The toolbar "AhTextStyles" provides a simple interface to the operations of creation, removal and applying of created styles to the selected text.

The names of procedures and functions that perform basic operations with styles are listed in the following table:

Operation

Macros

Style Creation

AhCreateHeadlineStyles

Style Deletion

AhDeleteHeadlineStyle, AhDeleteHeadlineStyles

Checking of the style’s existence

AhStyleExists

Applying Style

AhStyleSelection, AhStyle1, AhStyle2

The VBA source code is given below.

'
' File AhTextStyles.dot|AhTextStyles
'
' Etudes for Microsoft Word Programmers.
' Etude 1.4. Styles.
'
' First published on http://www.transcriber.ru
'
' © 2000-2007. Evgeny Akhundzhanov. All rights reserved.
'
 

Constants

'
' Constants
'
Private Const cStrHeadlineStyle1 As String = "AhHeadlineStyle1"
Private Const cStrHeadlineStyle2 As String = "AhHeadlineStyle2"

Messages

'
' Messages
'
Private Const cStrStylesHelp As String = _
    "Etudes for Microsoft Word Programmers." & vbCrLf & _
    "Etude 1.4. Styles." & vbCrLf & _
    "http://www.transcriber.ru" & vbCrLf & vbCrLf & _
    "Template AhTextStyles.dot - Working with styles." & vbCrLf & vbCrLf & _
        "Create - creates styles %1 and %2" & vbCrLf & _
        "Delete - deletes styles %1 and %2" & vbCrLf & vbCrLf & _
        "Style 1 - applies Style %1" & " to the selection" & vbCrLf & _
        "Style 2 - applies Style %2" & " to the selection" & vbCrLf & _
        "" & vbCrLf
Private Const cStrStyleExists As String = "Style <%1> exists."
Private Const cStrStyleDoesntExist As String = "Style <%1> doesn't exist."
Private Const cStrSelectionIsEmpty As String = "Selection is empty."

 

Procedure AhStylesHelp

'
' AhStylesHelp
'
Sub AhStylesHelp()
Dim strStylesHelp As String
    strStylesHelp = cStrStylesHelp
    strStylesHelp = Replace(strStylesHelp, "%1", cStrHeadlineStyle1)
    strStylesHelp = Replace(strStylesHelp, "%2", cStrHeadlineStyle2)
   
    MsgBox strStylesHelp
End Sub

Procedure AhStyleExists

'
' AhStyleExists
'
Public Function AhStyleExists(ByVal strStyleName As String) As Boolean
On Error GoTo ErrorLabel
With ActiveDocument.Styles(strStyleName)
    AhStyleExists = True
    Exit Function
End With
ErrorLabel:
    AhStyleExists = False
End Function

Procedure AhDeleteStyle

'
' AhDeleteStyle
'
Sub AhDeleteStyle(ByVal strStyleName As String)
If Documents.Count = 0 Then Exit Sub
    If AhStyleExists(strStyleName) Then
        ActiveDocument.Styles(strStyleName).Delete
    End If
End Sub

Procedure AhDeleteHeadlineStyles

'
' AhDeleteHeadlineStyles
'
Sub AhDeleteHeadlineStyles()
    AhDeleteStyle cStrHeadlineStyle1
    AhDeleteStyle cStrHeadlineStyle2
End Sub

Procedure AhCreateHeadlineStyles

'
' AhCreateHeadlineStyles
'
Sub AhCreateHeadlineStyles()

If Documents.Count = 0 Then Exit Sub

Dim strStyleName As String
Dim strStyleExists As String
 
If AhStyleExists(cStrHeadlineStyle1) Then
    strStyleExists = Replace(cStrStyleExists, "%1", cStrHeadlineStyle1)
    MsgBox strStyleExists
Else
    strStyleName = cStrHeadlineStyle1
    ActiveDocument.Styles.Add Name:=strStyleName, Type:=wdStyleTypeParagraph
    With ActiveDocument.Styles(strStyleName)
    .AutomaticallyUpdate = False
    With .Font
        .Name = "Times New Roman"
        .Size = 16
        .Bold = True
        .Italic = False
        .Underline = wdUnderlineNone
        .UnderlineColor = wdColorAutomatic
        .StrikeThrough = False
        .DoubleStrikeThrough = False
        .Outline = False
        .Emboss = False
        .Shadow = True
        .Hidden = False
        .SmallCaps = False
        .AllCaps = False
        .Color = wdColorBlue
        .Engrave = False
        .Superscript = False
        .Subscript = False
        .Scaling = 100
        .Kerning = 0
        .Animation = wdAnimationNone
    End With
    With .ParagraphFormat
        .LeftIndent = InchesToPoints(0)
        .RightIndent = InchesToPoints(0)
        .SpaceBefore = 0
        .SpaceBeforeAuto = False
        .SpaceAfter = 0
        .SpaceAfterAuto = False
        .LineSpacingRule = wdLineSpaceSingle
        .Alignment = wdAlignParagraphLeft
        .WidowControl = True
        .KeepWithNext = False
        .KeepTogether = False
        .PageBreakBefore = False
        .NoLineNumber = False
        .Hyphenation = True
        .FirstLineIndent = InchesToPoints(0)
        .OutlineLevel = wdOutlineLevelBodyText
        .CharacterUnitLeftIndent = 0
        .CharacterUnitRightIndent = 0
        .CharacterUnitFirstLineIndent = 0
        .LineUnitBefore = 0
        .LineUnitAfter = 0
    End With
    .NoSpaceBetweenParagraphsOfSameStyle = False
    .ParagraphFormat.TabStops.ClearAll
    With .ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorAutomatic
            .BackgroundPatternColor = wdColorAutomatic
        End With
        .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
        .Borders(wdBorderRight).LineStyle = wdLineStyleNone
        .Borders(wdBorderTop).LineStyle = wdLineStyleNone
        .Borders(wdBorderBottom).LineStyle = wdLineStyleNone
        With .Borders
            .DistanceFromTop = 1
            .DistanceFromLeft = 4
            .DistanceFromBottom = 1
            .DistanceFromRight = 4
            .Shadow = False
        End With
    End With
    .LanguageID = wdEnglishUS
    .NoProofing = False
    .Frame.Delete
    End With
End If
   
If AhStyleExists(cStrHeadlineStyle2) Then
    strStyleExists = Replace(cStrStyleExists, "%1", cStrHeadlineStyle2)
    MsgBox strStyleExists
Else
    strStyleName = cStrHeadlineStyle2
    ActiveDocument.Styles.Add Name:=strStyleName, Type:=wdStyleTypeParagraph
    With ActiveDocument.Styles(strStyleName)
    .AutomaticallyUpdate = False
    With .Font
        .Name = "Arial"
        .Size = 14
        .Bold = True
        .Italic = True
        .Underline = wdUnderlineNone
        .UnderlineColor = wdColorAutomatic
        .StrikeThrough = False
        .DoubleStrikeThrough = False
        .Outline = False
        .Emboss = False
        .Shadow = False
        .Hidden = False
        .SmallCaps = False
        .AllCaps = False
        .Color = wdColorRed
        .Engrave = True
        .Superscript = False
        .Subscript = False
        .Scaling = 100
        .Kerning = 0
        .Animation = wdAnimationNone
    End With
    With .ParagraphFormat
        .LeftIndent = InchesToPoints(0)
        .RightIndent = InchesToPoints(0)
        .SpaceBefore = 0
        .SpaceBeforeAuto = False
        .SpaceAfter = 0
        .SpaceAfterAuto = False
        .LineSpacingRule = wdLineSpaceSingle
        .Alignment = wdAlignParagraphLeft
        .WidowControl = True
        .KeepWithNext = False
        .KeepTogether = False
        .PageBreakBefore = False
        .NoLineNumber = False
        .Hyphenation = True
        .FirstLineIndent = InchesToPoints(0)
        .OutlineLevel = wdOutlineLevelBodyText
        .CharacterUnitLeftIndent = 0
        .CharacterUnitRightIndent = 0
        .CharacterUnitFirstLineIndent = 0
        .LineUnitBefore = 0
        .LineUnitAfter = 0
    End With
    .NoSpaceBetweenParagraphsOfSameStyle = False
    .ParagraphFormat.TabStops.ClearAll
    With .ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorAutomatic
            .BackgroundPatternColor = wdColorAutomatic
        End With
        .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
        .Borders(wdBorderRight).LineStyle = wdLineStyleNone
        .Borders(wdBorderTop).LineStyle = wdLineStyleNone
        .Borders(wdBorderBottom).LineStyle = wdLineStyleNone
        With .Borders
            .DistanceFromTop = 1
            .DistanceFromLeft = 4
            .DistanceFromBottom = 1
            .DistanceFromRight = 4
            .Shadow = False
        End With
    End With
    .LanguageID = wdEnglishUS
    .NoProofing = False
    ' .Frame.Delete
    .Frame.LockAnchor = True    ' we leave the Frame here !    End With
End If
End Sub

Procedure AhStyleSelection

'
' AhStyleSelection
'
Private Sub AhStyleSelection(ByVal strStyleName As String)
If Documents.Count = 0 Then Exit Sub
    If AhStyleExists(strStyleName) Then
        If Selection.Start = Selection.End Then
            MsgBox cStrSelectionIsEmpty
        Else
            Selection.Style = strStyleName
        End If
    Else
        Dim strStyleMsg As String
        strStyleDoesntExist = Replace(cStrStyleDoesntExist, "%1", strStyleName)
        MsgBox strStyleDoesntExist
    End If
End Sub

Procedure AhStyle1

'
' AhStyle1
'
Sub AhStyle1()
    AhStyleSelection cStrHeadlineStyle1
End Sub

Procedure AhStyle2

'
' AhStyle2
'
Sub AhStyle2()
    AhStyleSelection cStrHeadlineStyle2
End Sub

Procedure AhFontsDemo

The procedure AhFontsDemo calls the procedure FontSampleGenerator from the module AhTextFontsDemo. The procedure FontSampleGenerator is taken from the template "Macros9.dot", created in Microsoft Technical Support.
The corresponding VBA code is not given here, but is available inside the "AhTextStyles.dot" template.

'
' AhFontsDemo
'
Sub AhFontsDemo()
Dim iAnswer As Long
    iAnswer = MsgBox("AhFontsDemo", vbYesNo)
    If iAnswer = vbYes Then
        AhTextFontsDemo.FontSampleGenerator
    End If
End Sub

Conclusions

The properties and methods of the Style Object and the Styles Collection are investigated in this etude, as well as the properties of some other objects, related to text formatting. The macros for creation, removal and using of styles are created, as well as the macros for checking of the style’s existence.

The "AhTextStyles.dot" template is created on the basis of specification. It contains macros for working with styles. The toolbar "AhTextStyles" provides a simple interface to the operations of creation and removal of the user’s set of styles, and also to applying of the user’s styles to the selected text.

Tasks

Task 1

Change the macros and the toolbar of the "AhTextStyles.dot" template so that they become convenient personally for you.

 

Task 2. Frequently Used Styles

The amount of the most frequently used built-in styles is not big, as a rule. Users tend to use just several built-in styles. Create a new template to optimize work with the built-in styles. Create the macros that apply to the selected text five (or seven) built-in styles, most frequently used by you personally. Add buttons to the toolbar, one for each of your styles. The result should look something like this:

You may use the built-in "Normal", "Normal (Web)" and "Body Text" styles for "normal styles", for instance. The built-in "Heading 1","Heading 2" and "Heading 3" are appropriate for the heading styles. Choose built-in styles for "Agate" buttons yourself.

If the number of the built-in styles is not enough for you, create the code (and the buttons) to apply your own styles, as well as the built-in ones, to the selected text. I hope that after thorough study of this etude you will easily do it. Won’t you?

For a big amount of styles it will be sensible to create a drop-down list in the toolbar. The creation of controls in the toolbars is described in Etude 10 "Custom Toolbars".

 

Task 3 Styles Demo.

By analogy with the fonts demo macro (the AhFontsDemo procedure, press "Fonts Demo" button to call it), create a macro that demonstrates all styled used in the active document.

The result should look something like this: .


Etudes for Microsoft Word Programmers. Etude 1.4.


Unless otherwise noted, all materials on this site are
© 2000-2009 Evgeny Akhundzhanov, All Rights Reserved Worldwide
Microsoft is in no way affiliated with, nor offers endorsement of, this site.
www.transcriber.ru | E-mail the Author