• VBA code needed for paragraph and bold within text box–Word 2003

    Home » Forums » AskWoody support » Productivity software by function » MS Word and word processing help » VBA code needed for paragraph and bold within text box–Word 2003

    Author
    Topic
    #501606

    I have been asked to add a text box to a global Macro and was able to find a small bit of information on the Internet as to how this can be done, but I can’t find information anywhere as to how to insert a paragraph and bold the writing within the text box. Also, it seems the Macro recorder will not work when trying to capture the steps of inserting a text box or shape. I know this is something simple, but it is difficult when you don’t know how to do it and can’t find the information anywhere. The code I have is below. I appreciate any help you can give me, as this is a doctor that wants the text box added to the top of her report format. She also wants a picture added, so I’m sure I will be asking for help on that after I get this issue resolved. :confused:

    Sub test2()

    Dim Box As Shape
    Set Box = ActiveDocument.Shapes.AddTextbox( _
    Orientation:=msoTextOrientationHorizontal, _
    Left:=75, Top:=75, Width:=300, Height:=75)
    Box.TextFrame.TextRange.text = “This is my text that I would like bolded, with a new line of text that follows.”

    End Sub

    Viewing 6 reply threads
    Author
    Replies
    • #1522629

      Try:

      Code:
      Sub test2()
      Dim Box As Shape
      Set Box = ActiveDocument.Shapes.AddTextbox( _
        Orientation:=msoTextOrientationHorizontal, _
        Left:=75, Top:=75, Width:=300, Height:=75)
      With Box.TextFrame.TextRange
        .Text = "This is my text that I would like bolded." & vbCr
        .Font.Bold = True
        .Collapse wdCollapseEnd
        .Text = "This is my new line of text."
        .Font.Bold = False
      End With
      End Sub

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

      • #1522649

        Thanks so much for your help, Macropod. Works like a charm! ๐Ÿ˜€

        • #1522688

          Ah, I knew that seemed too easy. Is there any way to make the text within the text box to stay in Calibri 11 pt font? The entire report format and Macro code is in Calibri 11 pt font, but the text within the box is coming out as Times New Roman 12 pt for some reason. I cannot find any code within the box that seems to need changing, except for maybe; Orientation:=msoTextOrientationHorizontal, _, but that snippet of code seems to be only for positioning?

    • #1522690

      By default, textboxes are initialized with Word’s Normal Style. Presumably, then, the Normal Style in your document uses 12pt TNR. To get 11pt Calibri, you could insert:
      .Font.Name = “Calibri”
      .Font.Size = 11
      before:
      .Collapse wdCollapseEnd

      Note: Overriding Style attributes this way isn’t ideal. It would be better to use Styles to control the formatting throughout. For example:

      Code:
      Sub test2()
      Dim Box As Shape
      Set Box = ActiveDocument.Shapes.AddTextbox( _
        Orientation:=msoTextOrientationHorizontal, _
        Left:=75, Top:=75, Width:=300, Height:=75)
      With Box.TextFrame.TextRange
        .Text = "This is my text that I would like bolded." & vbCr
        .Style = "StyleName1"
        .Collapse wdCollapseEnd
        .Text = "This is my new line of text."
        .Style = "StyleName2"
      End With
      End Sub

      where StyleName1 & StyleName2 are Styles formatted with the appropriate attributes.

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

      • #1522704

        I am not accustomed to assigning styles, but I think I did it properly. I recorded a Macro when assigning the new styles so that I could get the code. Normal was assigned to NTR 12 pt, and Style1 was assigned to Calibri 11 pt. I then took the code from the newly created styles and placed it in the previous code, running a test Macro, which ran but did not change the font. Here is the code that I used:

        Dim Box As Shape
        Set Box = ActiveDocument.Shapes.AddTextbox( _
        Orientation:=msoTextOrientationHorizontal, _
        Left:=75, Top:=75, Width:=300, Height:=75)
        With Box.TextFrame.TextRange
        .text = “This is my text that I would like bolded.” & vbCr
        Selection.Style = ActiveDocument.Styles(“Normal”)
        .Collapse wdCollapseEnd
        .text = “This is my new line of text.”
        Selection.Style = ActiveDocument.Styles(“Style1”)

        I then tried your other suggestion of inserting

        .Font.Name = “Calibri”
        .Font.Size = 11
        before:
        .Collapse wdCollapseEnd

        which worked great. If I were to use styles, could the code be written into the Macro and shared with other people? I am assuming styles are based off of each individual’s computer settings and that other people using the Macro would need to have the same style and code language on their end as well? I plan on sharing this Macro with seven other people, so would it be best to go with the font change code before .Collapse wdCollapseEnd? I am assuming it is best not to override style attributes because it can make the Macro “wonky?”

    • #1522711

      I already gave you exactly the code you need for assigning Styles, except for the actual names, so I don’t understand why you’d think you need to code it differently. The fact your test macro didn’t change the font only demonstrates the effect of doing otherwise. Apart from that, it’s also clear your Normal Style doesn’t use 11pt Calibri; otherwise, that’s what the textbox would display already.

      As for sharing the code, if the other users are using a document in which the Styles called by the macro exist, or is attached to a template in which they exist, the other users should be able to use the code. Indeed, you should be able to use just a single new Style, which you apply to the whole textbox for a non-bold font, then apply Word’s built-in Strong character Style to bold the first paragraph. For example:

      Code:
      Sub test2()
      Dim Box As Shape
      Set Box = ActiveDocument.Shapes.AddTextbox( _
        Orientation:=msoTextOrientationHorizontal, _
        Left:=75, Top:=75, Width:=300, Height:=75)
      With Box.TextFrame.TextRange
        .Style = "MyCalibri11ptStyle"
        .Text = "This is my text that I would like bolded." & vbCr & "This is my new line of text."
        .Paragraphs.First.Range.Style = "Strong"
      End With
      End Sub

      Cheers,
      Paul Edstein
      [Fmr MS MVP - Word]

      • #1522942

        Thank you for your patience and the time you are taking to explain these things to me. As mentioned previously, I am not familiar with Styles, their names, or how to assign them because that is something I have never done before. I have a basic understanding of the concept, which is that Word saves different styles to its normal.dot template. When I open Word, the font is TNR 12 pt, so it makes sense that is the normal style.

        Your previous code did not work and generated a run-time error, so I thought I needed to assign specific styles to get the style name needed to replace the part of the code I had highlighted in red (I did this by clicking on Format, Styles and Formatting, created the style, ran the Macro recorder to capture the code, and replaced the line in your code that is highlighted in red). The code in your last message also generated a run-time error, but you did say that the code is exactly what was needed, only I needed the actual style names. How would I go about getting the actual names to place in the code? I’m sorry I sound so ignorant here, but, again, it is not something I have had to do in the past.

        • #1522961

          As I have told you twice now, you need to use Style names that actually exist in your document (or its template); it’s hardly surprising, therefore that you get an error when you try to tell Word to use a Style that doesn’t exist.

          So, to get the macro to work, create a paragraph Style that uses 11pt Calibri, then replace ‘MyCalibri11ptStyle’ in the last lot of code I gave you with that Style’s name. That’s all there is to it.

          I have a basic understanding of the concept, which is that Word saves different styles to its normal.dot template. When I open Word, the font is TNR 12 pt, so it makes sense that is the normal style.

          That’s only true if you tell Word to do so; otherwise the Style only gets added to the document you create it in. And, if you’re going to share the code via Word’s Normal template, that’s exactly what you’ll need to do. The only other option would be to have the macro create the Style too. For example:

          Code:
          Sub Demo()
          Application.ScreenUpdating = False
          Dim Box As Shape
          Const StlNm As String = "BoxStyle"
          Call TestStyle(StlNm)
          With ActiveDocument
            Set Box = .Shapes.AddTextbox( _
            Orientation:=msoTextOrientationHorizontal, _
            Left:=75, Top:=75, Width:=300, Height:=75)
            With Box.TextFrame.TextRange
              .Style = StlNm
              .Text = "This is my text that I would like bolded." & vbCr & "This is my new line of text."
              .Paragraphs.First.Range.Style = "Strong"
            End With
          End With
          Set Box = Nothing
          Application.ScreenUpdating = True
          End Sub
          
          Sub TestStyle(StlNm As String)
          Dim Stl As Style, bFnd As Boolean
          With ActiveDocument
            bFnd = False
            For Each Stl In .Styles
              If Stl.NameLocal = StlNm Then
                bFnd = True
                Exit For
              End If
            Next
            If bFnd = False Then
              Set Stl = .Styles.Add(Name:=StlNm, Type:=wdStyleTypeParagraph)
              Call FormatBoxStyle(Stl)
            End If
          End With
          Set Stl = Nothing
          End Sub
          
          Sub FormatBoxStyle(Stl As Style)
          With Stl
            .BaseStyle = ""
            .NextParagraphStyle = "Normal"
            .NoSpaceBetweenParagraphsOfSameStyle = False
            With .Font
              .Name = "Calibri"
              .Size = 11
              .ColorIndex = wdAuto
              .Bold = False
              .Italic = False
              .Underline = wdUnderlineNone
            End With
            With .ParagraphFormat
              .TabStops.ClearAll
              .LeftIndent = 0
              .RightIndent = 0
              .FirstLineIndent = 0
              .Alignment = wdAlignParagraphCenter
              .SpaceAfter = 0
              .SpaceBefore = 0
              .LineSpacingRule = wdLineSpaceSingle
            End With
          End With
          End Sub

          Cheers,
          Paul Edstein
          [Fmr MS MVP - Word]

          • #1522976

            I understand now. My mistake was that I thought the example shown in your code had to be worded exactly the same, even though you did put it within quotes to show me it was an example. I assigned Calibri 11 pt to a paragraph style, which was named Style1. I then placed that name in the code, and it worked (replaced the part in the code from; .Style = “StyleName1” to .Style = “Style1”). Thanks again for taking the time to explain this to me.

    • #1523410

      As I thought, I am stuck on the code for inserting an image and placing two boxes/borders around it (not sure of the correct terminology — inline shape or border?). I have completed the code for the entire document but two issues I am stuck on and am hoping someone can help. I will list the other issue as a separate topic/thread in order to avoid confusion. I am not familiar with writing code for styles, which seems to be my main issue. I have searched for hours on the Internet in hopes of finding code I could use as an example and in my Microsoft Word 2000 book but can’t find anything that helps. I have been able to insert the picture and re-size and position it. Since I am not familiar with writing code for styles, I used the previous code Macropod gave me and altered it, which I know is not correct in this case. The previous code was for a text box, which I altered to create thicker lines. This seemed to work, except it put a dark line around the picture and then bits of a thinner line in places. I am trying to get a 3 pt line directly around the photo so that it touches the edges and then a larger 0.5 pt line around that one. I will list the code below. The below bolded code is from the previous text box that Macropod provided, and I am only listing the code in case the information is needed for the current code I am trying to figure out (or if there is a conflict). The previous text box sits directly to the left of the picture I am trying to frame on the right of the text box.

      Code:
      Sub test()
      '
      Dim Box As Shape
      Set Box = ActiveDocument.Shapes.AddTextbox( _
      Orientation:=msoTextOrientationHorizontal, _
      Left:=74, Top:=25, Width:=300, Height:=75)
      With Box.TextFrame.TextRange
        .Style = "Style1"
        .Text = " " & vbCr
        .Collapse wdCollapseEnd
        .Text = " 0000 Mockingbird Lane, Suite 13" & vbCr
        .Font.Bold = True
        .Collapse wdCollapseEnd
        .Text = " Cucamonga, CA 00000" & vbCr & vbCr
        .Font.Bold = True
        .Collapse wdCollapseEnd
        .Text = " (000) 000-0000 / EmailAddress@gmail.email"
        .Font.Bold = True
        Dim imagePath As String
        imagePath = "J:EMAILAEV logo.jpg"
        ActiveDocument.Shapes.AddPicture FileName:="J:EMAILAEV logo.jpg", _
          LinkToFile:=False, _
          SaveWithDocument:=True, _
          Left:=7, _
          Top:=-150, _
          Anchor:=Selection.Range, _
          Width:=45, _
          Height:=70
      
        Dim Box2 As Shape
        Set Box2 = ActiveDocument.Shapes.AddTextbox( _
          Orientation:=msoTextOrientationHorizontal, _
          Left:=420, Top:=23, Width:=90, Height:=73)
        With Box2.TextFrame.TextRange
          .Style = "Style2"
      
        End With
      
        Dim Eye As String
        Eye = "J:EMAILEye Image.jpg"
        ActiveDocument.Shapes.AddPicture FileName:="J:EMAILEye Image.jpg", _
          LinkToFile:=False, _
          SaveWithDocument:=True, _
          Left:=350, _
          Top:=-150, _
          Anchor:=Selection.Range, _
          Width:=86, _
          Height:=58
      
       End Sub
      • #1523474

        As I thought, I am stuck on the code for inserting an image and placing two boxes/borders around it (not sure of the correct terminology — inline shape or border?). I have completed the code for the entire document but two issues I am stuck on and am hoping someone can help. I will list the other issue as a separate topic/thread in order to avoid confusion. I am not familiar with writing code for styles, which seems to be my main issue. I have searched for hours on the Internet in hopes of finding code I could use as an example and in my Microsoft Word 2000 book but can’t find anything that helps. I have been able to insert the picture and re-size and position it. Since I am not familiar with writing code for styles, I used the previous code Macropod gave me and altered it, which I know is not correct in this case.[/quote]
        I already provided you with code to do exactly that in my last post. Did you read it?

        The previous code was for a text box, which I altered to create thicker lines. This seemed to work, except it put a dark line around the picture and then bits of a thinner line in places. I am trying to get a 3 pt line directly around the photo so that it touches the edges and then a larger 0.5 pt line around that one.

        Try something like:

        Code:
        Set Box = ActiveDocument.Shapes.AddPicture(FileName:="J:EMAILAEV logo.jpg", _
            LinkToFile:=False, SaveWithDocument:=True, Left:=7, Top:=-150, _
            Anchor:=Selection.Range, Width:=45, Height:=70)
        With Box.Line
          .Weight = 4.5
          .DashStyle = msoLineSolid
          .Style = msoLineThinThick
          .Transparency = 0#
          .Visible = msoTrue
          .ForeColor.ObjectThemeColor = wdThemeColorText1
          .ForeColor.TintAndShade = 0#
          .BackColor.RGB = RGB(255, 255, 255)
        End With

        PS: When posting code, please use the code tags. They’re on the ‘Go Advanced’ tab at the bottom of this screen.

        PPS: I’ve merged both threads, as the first part of the topic is just a continuation and the second, which also refers to shape manipulation, is closely related.

        Cheers,
        Paul Edstein
        [Fmr MS MVP - Word]

    • #1523648

      Thank you, Macropod. I will try your suggestion after I have finished my workday. I will also remember to put code tags around future code. ๐Ÿ˜ฎ

      • #1524070

        Thank you for the information, Macropod. I played around with the code and came up with some interesting effects I had not anticipated. I did not accomplish what I had set out to do, but the text box and logo I have now will work just fine. I still have a couple of questions regarding the text box and code.

          [*]Is there a way to anchor the text box so it does not move around on the page when typing?

          [*]Can I share the Macro with others without their needing to store the pictures and create the same style on their end?

        I am guessing there is no way to share the Macro with other people without their having the pictures saved in a folder on their end and the code re-written to reflect the folder where the pictures are stored, as well as their needing to create the same style so that it matches the text box font, but I thought I would ask before assuming that. I installed the Macro in another person’s computer today and tried it out, only to receive multiple Macro errors. Once I re-wrote the code to find the pictures in a folder on that person’s computer and created the style, the Macro worked fine. However, there are seven other transcriptionists that I need to set up with this Macro in case they should type the doctor’s work in the future, and it is going to be a huge pain if I have to do this on each person’s computer and remember to do the same in the future for another person. Again, I think I already know the answer but am hoping to be proven wrong.

        Thank you for taking the time to educate me.

    • #1524263

      The code can be written multiple ways to allow it to work on other computers. Personally, I would place the graphics into the template itself as building blocks so there is no need to import them from external files. However, you could also have the code search a folder relative to the template – for example
      Eye = ActiveDocument.AttachedTemplate.Path & “Eye Image.jpg”

      To anchor the text box to a specific location on the page, have a look at the positioning attributes you have assigned to it. By default, the positioning is relative to the ‘anchoring paragraph’ but you can easily change it to be relative to the page itself or the column margins. To explore the text box positioning attributes right click on the border of the text box and choose More Layout Options > Position. You can code these settings into your macro but again, it would be easier to do it via the GUI and then store it with those settings as a building block in the template.

    • #1524315

      I’m with you and would much prefer to have the code written into the Macro itself for the picture and logo. I went back and re-read my first post, and I apparently did not make it clear as to what I was trying to do. The Macro I am attempting to add the pictures and text box to is a global Macro and already has many functions, so I would prefer not needing to store the picture in a folder and have the Macro “call it out” when needed. As mentioned previously, I have never written code to add pictures or text boxes, so could you or someone please tell me how that can be done so that another person can simply install the Macro into another computer and run it without needing additional information on their end? I work best with examples, so if you could point me to a place where they show inserting text boxes or pictures into written code for dummies, I would appreciate it. A small Macro sample with code already embedded would most likely help a lot because I could play with the code to try and get it to work on my end. Sorry, I don’t even know if I am making sense any longer because I am working 12-hour days and trying to figure this out in my spare time, so the brain cells are dying off quickly!

      One of the problems with the text box and pictures is that the doctor sent me a template through email. The text box moves around in the template, which is what I was using to replicate the Macro on my end. The template was created in Word 2007, whereas I use Word 2003. I know most things are universal between the two versions of Word, but I am finding it more difficult to work with the template because the positioning is not clear to me. I did as you said and right-clicked on the text box border. I did not have an option for More Layout Options > Position, but I did have Format Text Box, which I am assuming is the same thing? I did alter the position by using the format options when writing the code, and everything works fine unless the typist needs to position her cursor directly beneath the box and add something. When adding text directly below the text box, the box moves to cover the first part of the report. With the information you have provided, I think what I need to do is position the text box wherever it looks appropriate on my end, which should allow me to anchor it to the page itself? I was trying to position the text box so that it looked equal with the one on the template sample, only I found out the template looked nothing like it did on my end when running the Macro in Word 2007. Again, this is not a huge issue, but these little things really bug me at times. My main objective is being able to write the code so that I can send the Macro to other transcriptionists and not need to create additional styles and save photos in folders on their end, so I really need some help on how to embed the pictures and have the text box font come out in Calibri 11 pt bold when my Normal style is set at Times New Roman.

      Thank you for your help, Andrew, and taking the time to offer your advice.

      • #1524455

        Once I re-wrote the code to find the pictures in a folder on that person’s computer and created the style, the Macro worked fine. However, there are seven other transcriptionists that I need to set up with this Macro in case they should type the doctor’s work in the future, and it is going to be a huge pain if I have to do this on each person’s computer and remember to do the same in the future for another person. Again, I think I already know the answer but am hoping to be proven wrong.

        Please read post #9 again. There I have already provided you with code to add a Style, without you having to add it manually. Have you ever run that code? Your subsequent posts suggest not, otherwise I can’t understand how it is that you persist with what you’re doing.

        As for you ultimate aim, you really should be working with a template.

        One of the problems with the text box and pictures is that the doctor sent me a template through email. The text box moves around in the template, which is what I was using to replicate the Macro on my end. The template was created in Word 2007, whereas I use Word 2003. I know most things are universal between the two versions of Word, but I am finding it more difficult to work with the template because the positioning is not clear to me.

        What you seem not to appreciate is that Word 2003 & 2007 handle the layout of templates in the .dot format and documents in the .doc format essentially the same way. However, what does affect the page layout within and across all Word versions is whether each user of the document is using the same active printer driver. That’s because Word uses the active printer’s driver to optimise the layout for that printer.
        Change active printers and the page layout may change.
        Change operating systems (e.g. Win to Mac or even Win 7 to Win 8), even with the same printers, and the page layout may change.
        Change printer driver versions on PCs using the same OS and the page layout may change.

        So, if you’re designing a document for use on another PC, you owe it to yourself and those you’re designing for to minimise the differences between your system and theirs. You should at least install and make active a printer driver for the printer they use; preferably the same version of that driver. You don’t need to have the actual printer, just the driver. You should also ensure you work with the same document format they’ll be using. Given that they use Word 2007, you should be designing a template in the .dotx format, since that’s Word 2007’s native format, not the older .dot format used by Word 2003 & earlier. Ideally, you’d do that using Word 2007 or 2010.

        Once you’ve designed a single template for the target machine, all that needs to be done for all existing and future users is to ensure they have access to that template. If their network is suitably configured, they can share the same work group’s templates, so there’s no need to install it on each machine; otherwise, that’s all that would be needed. No one there needs any macros.

        Cheers,
        Paul Edstein
        [Fmr MS MVP - Word]

    Viewing 6 reply threads
    Reply To: Reply #1522688 in VBA code needed for paragraph and bold within text box–Word 2003

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information:




    Cancel