Microsoft Word Sentences VBA (Visual Basic for Applications)

Microsoft Word Sentences VBA (Visual Basic for Applications)

Sentences

Group of lines or texts creates Sentences or collection of Range objects that represent all the sentences in a selection, range, or document. Use index (a positive integer number), to return a Range object that represents a single sentence. The following example formats the first sentence in the active document.

Count

Public Sub GetSentencesCount()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Display count
    MsgBox "You selection has " & oRange.Sentences.Count & " Sentences"
End Sub

Output

Print each sentence

Public Sub GetSentences()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Display each sentence
    Dim oSentence
    For Each oSentence In oRange.Sentences
        Debug.Print oSentence.Text
    Next oSentence
    
    'Memory cleanup
    Set oSentence = Nothing
    Set oRange = Nothing
End Sub

Output

In word document.
VBA is always helpful language for the office users having little knowledge of programming.
The journey of VBA is very old, since it supports little security hence, Microsoft can enhance the same to make it more versatile in nature.

Formatting

Public Sub FormatSentences()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Display each sentence
    Dim oSentence
    For Each oSentence In oRange.Sentences
        'Check if sentence text is bold then format
        If oSentence.Font.Bold = True Then
            oSentence.Font.Color = vbGreen
            oSentence.Font.Size = 18
        End If
    Next oSentence
    
    'Memory cleanup
    Set oSentence = Nothing
    Set oRange = Nothing
End Sub

Output

InsertAfter/InsertBefore

Public Sub InsertAfterBeforeSentence()
    'Retain selection
    Dim oRange As Range
    Set oRange = Selection.Range
    
    'Display each sentence
    Dim oSentence
    For Each oSentence In oRange.Sentences
        'Check if sentence text is bold then format
        If oSentence.Font.Bold = True Then
            oSentence.InsertAfter " Inserted After "
            oSentence.InsertBefore " Inserted Before "
        End If
    Next oSentence
    
    'Memory cleanup
    Set oSentence = Nothing
    Set oRange = Nothing
End Sub

Output

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Leave a Reply

Your email address will not be published.