简体   繁体   中英

How to position a command button in MS Word via VBA

I currently have a VBA script that works as it should apart from the position of the command button in the MS word documant. Currently the button is positioned as the very first thing on the document pushing the existing text to the right.

The VBA code I have use for the button is:

Dim doc As Word.Document
Dim shp As Word.InlineShape
Set doc = ActiveDocument

Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
shp.OLEFormat.Object.Caption = "Create PDF and print"

How do I position the button? On the same line but centered would do fine. Centered but at the very end of the document (following the letter as it is typed), even better.

Thank you.

You must add the button to a specific paragraph of the document. For example:

doc.Content.InsertParagraphAfter
Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1", _
    Range:=doc.Paragraphs.Last.Range)

Thus you can format the button paragraph as you want. For example:

doc.Paragraphs.Last.Alignment = wdAlignParagraphCenter
Sub Add_InlineShapes_To_EachLine()

    Dim shp As Word.InlineShape
    Dim NbOfLines, cpt As Integer
    'Count the number of non blank lines in current document
    NbOfLines = ActiveDocument.BuiltInDocumentProperties(wdPropertyLines)
    cpt = 1
    Set p = ActiveDocument.Paragraphs.First
    
    For Lin = 1 To NbOfLines
    
        Set shp = p.Range.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
           
        With shp.OLEFormat.Object
            .Caption = cpt
            .FontSize = 8
            .Width = 20
            .Height = 20
        End With
        
        Set p = p.Next
        cpt = cpt + 1
        
    Next Lin
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM