简体   繁体   English

MS Word宏VBA帮助,已选择图像

[英]MS Word Macro VBA Help, Selected image

I have basic Macro and VBA knowledge yet cannot get my head around where I am going wrong here. 我具有基本的Macro和VBA知识,但是无法弄清楚我在哪里出错了。 (Code inserted at the bottom) I want my macro to move a selected image into the top centre of the page. (代码插入底部)我希望宏将选定的图像移到页面的顶部中心。 The issue I am facing is that it will not work for each image in the document, it works for the first one then no longer performs the task. 我面临的问题是,它不适用于文档中的每个图像,它适用于第一个图像,然后不再执行任务。 I am using Microsoft Word 2016. 我正在使用Microsoft Word 2016。

The main command does what I want it to, I feel my error is within these two lines main命令执行了我想要的操作,我觉得我的错误在这两行之内

Set myDocument = ActiveDocument
With myDocument.Shapes(1)

Whole code; 整个代码;

Sub AlignToCentre()
'
' AlignToCentre

    Dim shp As Shape
Set myDocument = ActiveDocument
With myDocument.Shapes(1)
        .WrapFormat.Type = wdWrapSquare
        .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
        .Left = wdShapeCenter
        .RelativeVerticalPosition = wdRelativeVerticalPositionPage
        .Top = InchesToPoints(1)

    End With
End Sub

If you want this to work with the selected image, and only the selected image, then more like this, where you get the Shape from the current selection. 如果您希望它与选定的图像一起使用,并且仅与选定的图像一起使用,则更像这样,您可以从当前选择中获得形状。

Note how you should first check to make sure a Shape is selected... 请注意如何首先检查以确保选择了“形状” ...

Sub PositionSelectedShape()
    Dim sel As word.Selection
    Dim shp As word.Shape

    Set sel = Selection
    If sel.Type = wdSelectionShape Then
        Set shp = sel.ShapeRange(1)
        With shp
            .WrapFormat.Type = wdWrapSquare
            .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
            .Left = wdShapeCenter
            .RelativeVerticalPosition = wdRelativeVerticalPositionPage
            .Top = InchesToPoints(1)
        End With
    End If
End Sub

Exactly like Kim Raaness has suggested, you need to loop through all shapes of you would like to centre them all. 就像Kim Raaness所建议的那样,您需要遍历想要将所有形状居中的所有形状。

Try something like this: 尝试这样的事情:

Sub AlignToCentre()
'
' AlignToCentre

    Dim shp As Shape
Set myDocument = ActiveDocument
For Each shp in myDocument.Shapes
  With shp
        .WrapFormat.Type = wdWrapSquare
        .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
        .Left = wdShapeCenter
        .RelativeVerticalPosition = wdRelativeVerticalPositionPage
        .Top = InchesToPoints(1)
  End With
Next shp
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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