vbacolorsms-word

Changing (alternating) the colors of sentences (not highlights)


I'm looking for a VBA Word macro that assigns a different color to every sentence of a text. This could consist of three or four different colors that alternate. I want it to color the words themselves, the font; in other words, I do NOT want text to be highlighted.

I researched the topic already. The only macros I find are those that highlight.(I already asked this question before. And someone on stackoverflow had given me the perfect answer! But unfortunately the macro is no longer stored in my VBA (not sure what happened) and the thread of my former question was deleted.


Solution

  • You should be able to modify this to get something that does it the way you want.

    Sub ChangeSentenceColors()
        Dim sentence As Range
        Dim randColor As Long
    
        For Each sentence In ActiveDocument.Sentences
            randColor = RGB(Int((255 - 0 + 1) * Rnd + 0), _
                            Int((255 - 0 + 1) * Rnd + 0), _
                            Int((255 - 0 + 1) * Rnd + 0))
            sentence.Font.Color = randColor
        Next
    End Sub
    

    Here is the previous answer that was deleted (not my answer).

    Sub ColorSentences()
    Dim doc As Document
    Dim sentence As Range
    Dim colors As Variant
    Dim colorIndex As Integer
    ' Define the colors (change these if needed)  
    colors = Array(wdColorRed, wdColorBlue, wdColorGreen, wdColorDarkYellow, wdColorViolet)  
      
    Set doc = ActiveDocument  
    colorIndex = 0  
      
    ' Loop through each sentence in the document  
    For Each sentence In doc.Sentences  
        sentence.Font.Color = colors(colorIndex Mod 5)  
        colorIndex = colorIndex + 1  
    Next sentence  
      
    MsgBox "Sentences have been colored!", vbInformation  
    End Sub