使用 VBA 使同一文本框中的不同单词具有不同的字体大小

Make different words in same text box have different font size using VBA

标题几乎说明了一切,但为了更清楚一点,假设我想通过 VBA 创建一个文本框,上面写着 "This text should be of font size 24, this text should be of font size 20."

现在,我正在使用自己的函数创建文本框,如下所示。干杯,感谢您的帮助!

Sub textBox(textBoxText As String)
    Dim myTextBox As Shape
    With ActiveWindow.Selection.SlideRange
        Set myTextBox = .Shapes.AddTextbox _
            (Orientation:=msoTextOrientationHorizontal, Left:=153, Top:=50, _
            Width:=400, Height:=100)
        myTextBox.TextFrame.TextRange.Text = textBoxText
        myTextBox.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignCenter
        myTextBox.TextFrame.TextRange.Font.Bold = msoTrue
        myTextBox.TextFrame.TextRange.Font.Name = "Arial (Headings)"

    End With
End Sub

不需要 RichTextBox。答案在于 TextBox 的 TextFrame 中的 TextRange 对象的属性(多啰嗦!)。基本上,您可以 parse/traverse 此范围对象内的文本,如果您根据段落(或句子、单词、字符等)进行选择,则可以应用不同的文本效果。

Sub CreateTextbox()
    Dim MyTextBox As Shape
    Dim textBoxText As String
    Dim textToChange As TextRange
    textBoxText = "this is some wild text"
    With ActiveWindow.Selection.SlideRange
        Set MyTextBox = .Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, _
                        Left:=153, Top:=50, Width:=400, Height:=100)
        MyTextBox.TextFrame.TextRange.Text = textBoxText
        MyTextBox.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignCenter
        MyTextBox.TextFrame.TextRange.Font.Bold = msoTrue
        MyTextBox.TextFrame.TextRange.Font.Name = "Arial (Headings)"

        # here's where the magic happens
        Set textToChange = MyTextBox.TextFrame.TextRange
        textToChange.Words(3).Select
        textToChange.Words(3).Font.Size = 42

    End With
End Sub

获取文本范围参考,然后分配所需的字体大小。

With myTextBox.TextFrame2.TextRange
    With .InsertAfter("This text should be of font size 24,")
        .Font.Size = 24
    End With
    With .InsertAfter("this text should be of font size 20")
        .Font.Size = 20
    End With
End With