使用VBA(宏)PowerPoint将其他形状内的形状对齐并命名形状

时间:2019-07-08 14:00:52

标签: vba alignment powerpoint

我想在幻灯片中的尖角矩形内对齐(在这种情况下为中心)一个形状(圆角矩形),即两个形状的中心点应使用VBA相等,而无需使用“选择”。通过名称引用它们(例如,无论这两个形状是一堆什么,宏都应将它们对齐),但不确定如何开始。

请问外行的解释。任何想法都会真的有帮助,并促使我开始。

enter image description here

2 个答案:

答案 0 :(得分:0)

您将必须设置一个循环来检查幻灯片中的每个形状,查找其类型是否为AutoShape,然后确定其AutoShapeType为msoShapeRoundedRectangle或msoShapeRectangle。找到每个名称后,您将每个名称存储在变量中。如果两者都找到,则将分别获得每个的左,上,宽和高测量值,并设置这些值以使中心对齐。

Sub CenterShapes()
  Dim oSlide As Slide
  Dim oShape As Shape
  Dim bFoundRRect As Boolean, bFoundRect As Boolean
  Dim RRectName$, RectName$
  For Each oSlide In ActivePresentation.Slides
    For Each oShape In oSlide.Shapes
      If oShape.Type = msoAutoShape Then
        If oShape.AutoShapeType = msoShapeRoundedRectangle Then
          bFoundRRect = True
          RRectName$ = oShape.Name
        End If
        If oShape.AutoShapeType = msoShapeRectangle Then
          bFoundRect = True
          RectName$ = oShape.Name
        End If
      End If
    Next oShape
    If bFoundRRect = True And bFoundRect = True Then
      RRectVCenter = oSlide.Shapes(RRectName$).Top + (oSlide.Shapes(RRectName$).Height / 2)
      RRectHCenter = oSlide.Shapes(RRectName$).Left + (oSlide.Shapes(RRectName$).Width / 2)
      RectVCenter = oSlide.Shapes(RectName$).Top + (oSlide.Shapes(RectName$).Height / 2)
      RectHCenter = oSlide.Shapes(RectName$).Left + (oSlide.Shapes(RectName$).Width / 2)
      VDif = RRectVCenter - RectVCenter
      HDif = RRectHCenter - RectHCenter
      oSlide.Shapes(RectName$).Top = oSlide.Shapes(RectName$).Top + VDif
      oSlide.Shapes(RectName$).Left = oSlide.Shapes(RectName$).Left + HDif
    End If
  Next oSlide
End Sub

答案 1 :(得分:0)

此示例假定您知道或使用代码确定要对齐的形状的名称。然后,这是设置ShapeRange并在PowerPoint中使用内置对齐功能的快速方法。

Option Explicit

Sub AlignMe()
    Dim theseShapeNames As Variant
    theseShapeNames = Array("Rectangle 3", "Rectangle 4", "Rectangle 5")

    Dim thisSlide As Slide
    Dim theseShapes As ShapeRange
    Set thisSlide = ActivePresentation.Slides(1)
    Set theseShapes = thisSlide.Shapes.Range(theseShapeNames)
    theseShapes.Align msoAlignCenters, msoFalse
End Sub