2
votes

So this is what I want to do, if it's possible. I've got a lot of rich textboxes in a Word template. And I want to create a macro that basically checks if any characters in the text entered into the placeholder is formatted with superscript, subscript, bold or underline etc.

So, What I've got so far is this

Dim i As Long
Dim txtboxString as String
For i = 1 To ActiveDocument.ContentControls.Count

    If ActiveDocument.ContentControls(i).Title = "Repporttitle" Or ActiveDocument.ContentControls(i).Title = "Subtitle" Then
        If ActiveDocument.ContentControls(i).LockContentControl = True Then
            ActiveDocument.ContentControls(i).LockContentControl = False
        End If
        txtboxString = ActiveDocument.ContentControls(i).Range.Text

    End If
Next i

So, now, txtboxString contains the text that was typed into the placeholder. But I want to check each letter for it's formatting. The method above only gives me the text as a simple text string. I've seen that I can check each letter of the string this way:

Dim counter as integer
Dim contentText as string '(this is passed on via the above txtboxString)
Dim letter as string

For counter = 1 To Len(contentText)
    letter = Mid(contentText, counter, 1)
Next

But, this won't give me the formatting of each letter. How can I do that?

1

1 Answers

1
votes

Use Characters and Font instead of Text. Like this:

Sub GetCharacterFormatting()
Dim i As Long
Dim txtboxString As Characters ''# <- this was changed from "String" to "Characters"
Dim Bold As String
Dim Italic As String
Dim Subscript As String
Dim CharacterFont As Font
Dim ap As Document: Set ap = ActiveDocument
For i = 1 To ap.ContentControls.Count
    If ap.ContentControls(i).Title = "Repporttitle" Or ap.ContentControls(i).Title = "Subtitle" Then
        If ap.ContentControls(i).LockContentControl = True Then
            ap.ContentControls(i).LockContentControl = False
        End If
        txtboxString = ap.ContentControls(i).Range.Characters ''# <- this was changed from "Text" to "Characters"
        Dim counter As Integer
        For counter = 1 To txtboxString.Count
            Index = counter
            CharacterText = txtboxString(i).Text
            CharacterFont = txtboxString(i).Font
            ''# You can just grab all the formatting for the character or use If/Then statements
            Bold = "Bold: " & CharacterFont.Bold & ", "
            Italic = "Italic: " & CharacterFont.Italic & ", "
            Subscript = "Subscript: " & CharacterFont.Subscript & " "
            ''#
        Next
        Debug.Print Index & " (" & CharacterText & ") : " & Bold; Italic; Subscript
    End If
Next i
End Sub