如何通过VBA在MS Word中定位命令按钮



我目前有一个VBA脚本,它的工作原理与MS单词documant中命令按钮的位置不同。目前,该按钮位于文档上的第一个位置,将现有文本向右推。

我为按钮使用的VBA代码是:

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"

如何定位按钮?在同一条线上但居中即可。居中但在文档的最后(在键入的字母后面),甚至更好。

谢谢。

您必须将按钮添加到文档的特定段落中。例如:

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

因此,您可以根据需要设置按钮段落的格式。例如:

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

最新更新