Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

vba - How do I position a TextBox in Word that I've just added to a page

I have a document that has a number of rectangle shapes. I want to replace each of those with a TextBox in exactly the same place. My starting point is working with an existing known shape I want to replace with a textbox (later I'll add further automation to process the selected shape or all shapes).

This is my code so far:

Sub Macro3()
'
' Macro3 Macro
'
'
Dim shp As Shape
Dim Box As Shape

For Each shp In ActiveDocument.Shapes.Range(Array("Group 1928"))
    shp.Select
    Set Box = ActiveDocument.Shapes.AddTextbox( _
    Orientation:=msoTextOrientationHorizontal, _
    Left:=shp.Left, Top:=shp.Top, Width:=shp.Width, Height:=shp.Height)
    Box.RelativeHorizontalPosition = shp.RelativeHorizontalPosition
    Box.RelativeVerticalPosition = shp.RelativeVerticalPosition
    Box.TextFrame.TextRange.Text = "Some text"
Next shp

End Sub

I've tried setting a number of other properties but the textbox always appears and stays at the top centre of the document page.

Thank you for any guidance you can offer.

Regards Tim

question from:https://stackoverflow.com/questions/65890999/how-do-i-position-a-textbox-in-word-that-ive-just-added-to-a-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example:

Sub Demo()
Application.ScreenUpdating = False
Dim i As Long, rt As Long, rl As Long, wf As Long, Shp As Shape
With ActiveDocument
  For i = .Shapes.Count To 1 Step -1
    With .Shapes(1)
      If .Type = msoAutoShape Then
        wf = .WrapFormat.Type
        rt = .TopRelative
        rl = .LeftRelative
        Set Shp = ActiveDocument.Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, _
          Left:=.Left, Top:=.Top, Width:=.Width, Height:=.Height, Anchor:=.Anchor)
        With Shp
          .WrapFormat.Type = wf
          .TopRelative = rt
          .LeftRelative = rl
          .TextFrame.TextRange.Text = "Hello World"
        End With
        .Delete
      End If
    End With
  Next
End With
Application.ScreenUpdating = True
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...