Microsoft Word Range Object VBA (Visual Basic for Applications)

Microsoft Word Range Object VBA (Visual Basic for Applications)

Range

Refers an area in a document to perform actions, like insert text or apply formatting. For example, you may want to write a macro that locates a word or phrase within a portion of a document. The portion of the document can be represented by a Range. After the Range object is identified, methods and properties of the Range object can be applied to modify the contents of the range.

Note: Range object is not as Selection object in Word. There is only one selection per document but Ranges can be multiple.

Create/Add Range

Sub SetNewRange() 
	Dim rngDoc As Range 
	Set rngDoc = ActiveDocument.Range(Start:=0, End:=10) 
End Sub

Bold property

Sub SetRangeToBold() 
	Dim rngDoc As Range 
	Set rngDoc = ActiveDocument.Range(Start:=0, End:=10) 
	rngDoc.Bold = True 
End Sub

InsertBefore

Sub InsertTextBeforeRange() 
	Dim rngDoc As Range 
	Set rngDoc = ActiveDocument.Range(Start:=0, End:=0) 
	rngDoc.InsertBefore "Hello " 
End Sub

Output

Paragraph with Range

Sub GetNewRange() 
	Dim doc As Document 
	Dim rngDoc As Range 
	Set doc = ActiveDocument 
	Set rngDoc = doc.Range(Start:=doc.Paragraphs(2).Range.Start, _ 
	End:=doc.Paragraphs(3).Range.End) 
End Sub

List objects which exposes Range

  • Selection
  • Document
  • Paragraph
  • Bookmark
  • Cell

Alignment

Sub FormattingRange() 
	ActiveDocument.Paragraphs(2).Range.Select 
	Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter 
End Sub

SetRange

Sometimes you add or delete contents from your document which are referenced under a Range object. Since Range object is predefined and holding reference before change would not know what has been added or deleted from given range. To fit Range back to amended range Word offers SetRange method by which you can expand or shrink your range object. The SetRange method then redefines the range so that it refers to the current selection plus the next 10 characters.

Code example

Sub ResizeRange() 
	Dim rngParagraph As Range
	'Get current range
	Set rngParagraph = Selection.Range 
	'Extend range by 10 chars
	rngParagraph.SetRange Start:=rngParagraph.Start, End:=rngParagraph.End + 10 
End Sub

Next>>Working with Tables in Word VBA

Leave a Reply

Your email address will not be published. Required fields are marked *