在标题中按名称访问形状

时间:2015-08-28 17:46:51

标签: vba word-vba

我的第一篇帖子很抱歉任何错误。

我正在尝试替换文档标题中的图像。这将完成几千次。

这行代码:

Set shp = ActiveDocument.Sections(1).Headers.Shapes(strPic)

原因:

  

编译错误:找不到方法或数据成员

Set shp = ActiveDocument.Shapes("strPic")

原因:

  

运行时错误'-2147024809(80070057):找不到具有指定名称的项目。

我已经用多种方式编写了,并且不能让它分配shp我觉得这是一个非常简单的问题,我是如何访问标题的,或者这整个sub可能是错误的。获取形状名称前的strPic行。

Sub imagerepl()

With Selection
         ' \\ If we selected a InlineShape then convert to Shape
        If .Type = wdSelectionInlineShape Then
            .InlineShapes(1).ConvertToShape
        End If
    End With

strPic = Selection.ShapeRange.Name
Set shp = ActiveDocument.Sections(1).Headers.Shapes(strPic)

'Capture properties of exisitng picture such as location and size
With shp
    t = .Top
    l = .Left
    h = .Height
    w = .Width
End With

ActiveDocument.StoryRanges(wdPrimaryHeaderStory).ShapeRange(strPic).Delete


Set shp = ActiveDocument.Shapes.AddPicture("C:\Users\tk\Pictures\DFHlogo.png",        msoFalse, msoTrue, l, t, w, h)
shp.Name = strPic
shp.ScaleHeight Factor:=1, RelativeToOriginalSize:=msoTrue
shp.ScaleWidth Factor:=1, RelativeToOriginalSize:=msoTrue


End Sub

1 个答案:

答案 0 :(得分:1)

您可以通过Range.InlineShapes集合访问标题图片。例如,以下例程将删除集合中的第一个图像,然后将新图像添加到标题中。

Dim sh As InlineShape

With ThisDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range

    ' Get the first (possibly only, for you) image in the header...
    Set sh = .InlineShapes(1)

    ' Delete it...
    sh.Delete

    ' Add a new image to the header...
    Set sh = .InlineShapes.AddPicture("c:\path\to\my.jpg")

    ' Set its properties...
    sh.Width = 100
    sh.Height = 100
    ...

End With