Home > Back-end >  Change fontSize of an existing TextBox Shape
Change fontSize of an existing TextBox Shape

Time:11-09

I have a textBox in my Word Document, whose text is automatically populated through MailMerge - (the <<FinalName>> one in the below pic).

enter image description here

The shape name of the TextBox is namebox (I got this from Home > Editing > Selection Pane)

I was wondering if it's possible to change the font-size of this particular textBox - The textBox by default has a fontSize of 11, and I should decrease it to 10, depending on a variable's character-length (if its longer than 32 chars or not), so It could fit longer text more easily.

I have tried building some code myself, but I am getting a compilation error of 'variable not defined' on the namebox word.

Here is where I inserted the textbox: enter image description here

Dim caName As String
Dim nameLen As Integer
caName = .DataSource.DataFields("Final Display Name").Value
nameLen = Len(caName)

If nameLen < 32 Then
    namebox.Font.Size = 10 'error - namebox variable is not defined
Else
    namebox.Font.Size = 11 'practically nothing changes here
End If

As you can see, the value for caName is taken from a DataSource - this DataSource is also linked to MailMerge, so values will be the same.

I have seen various examples, but most of them create a new textbox instead of using an existing one. How do I change the font-size for an existing textBox shape? Kindly guide... Thanks! :)

CodePudding user response:

That "textbox" is actually a Shape with a TextFrame. You can get the shape object by name and change its font size (of the TextRange for its TextFrame) this way:

Sub Test
    Dim ShapeName As String
    ShapeName = "namebox" ' change this to the name of your shape

    ActiveDocument.Shapes(ShapeName).TextFrame.TextRange.Font.Size = 30

    ' to get the text that is in it...
    MsgBox ActiveDocument.Shapes(ShapeName).TextFrame.TextRange.Text
End Sub

TextFrame object (Word)

If you are unsure about the name to use, print a list of the shape names in the immediate window using this:

Sub ShowListOfShapes()
    Dim shp as Shape
    For Each shp In ActiveDocument.Shapes
        Debug.Print shp.Name
    Next
End Sub
  • Related