Microsoft Word Style Object VBA (Visual Basic for Applications) example

Microsoft Word Style Object VBA (Visual Basic for Applications) example

Style

Represents a user-defined style. The Style object includes formatting attributes (such as font, font name, font color, paragraph alignment and paragraph spacing) as properties of the Style object. The Styles collection includes all the styles in the specified document Index (a positive integer), can be used to reference single style, Microsoft Word exposes WdBuiltinStyle constant which can be used to assign a predefined style. Style name are case sensitive hence should be remembered while referencing in the code. The following example modifies the font name of the user-defined style named “Color” in the active document.

Style Examples

public Sub ModifyFontStylemethod()
	  'Not recommended Active
	  ActiveDocument.Styles("InfoExtract").Font.Name = "Arial"
	  
	  'Recommended Strong Reference
	  Documents("MyDoc").Styles("InfoExtract").Font.Name = "Arial"
End Sub

Built in Style

public Sub BoldStylemethod()
   Documents("MyDoc").Styles(wdStyleHeading1).Font.Bold=True
End Sub

Styles collection

public Sub BaseStylemethod()
	'Get Vase Style
	Debug.Print Documents("MyDoc").Styles(1).BaseStyle
	
	'Get Local name of style
	Debug.Print Documents("MyDoc").Styles(1).NameLocal
End Sub

Range Object:

public Sub RangeStylemethod()
   oRange.Style = wdStyleNormal
End Sub

Selection Object:

public Sub SelectionStylemethod()
   Selection.Paragraphs(1).Style = wdStyleHeading1
End Sub

Add

public Sub AddStylemethod()
   Dim oStyle As Style
   Set oStyle = Documents("InfoExtractDoc").Styles.Add(Name:="InfoPara", Type:=wdStyleTypeCharacter)
   oStyle.Font.Bold=True
   Selection.Range.Style="InfoPara"
End Sub

Deleting

public Sub DeleteStylemethod()
   Documents("InfoExtractDoc").Styles("InfoPara").Delete
End Sub

Video: How to create/modify/apply styles in Microsoft Word:

Next>>Working with Special Symbols/Multi bytes Symbols in Word VBA

Leave a Reply

Your email address will not be published.