首页 文章

VBA PowerPoint:根据形状的相对位置来查看形状

提问于
浏览
-1

我是VBA编程的新手,但由于我有一些C经验,我认为我可以用VBA完成这项任务 .

我有一个100张幻灯片演示文稿,其中包含表格,图片和绘图 . 每张幻灯片上绘制的形状不同,但它们的共同属性是它们与设置位置和大小的图片重叠 .

我想对每张幻灯片进行基本操作,例如某些形状的分组,删除和定位 . 目标是更改幻灯片的格式 .

我做了我的研究,但由于我想保持某些形状不变,并且文件不是由我创建的,所以我不知道这些形状的名称或索引,我找不到解决这个问题的方法 . 我认为最好通过它们在幻灯片上的相对位置来引用形状,即它们是在特定选择内还是在幻灯片上某一点的范围内(例如左上角) .

有可能做出这种参考或条件吗?

提前感谢您的回答 .

2 回答

  • 0

    一般来说,你有 Shape 的集合,你可以按索引访问元素,例如如果您不知道索引,但您知道其他功能可以唯一标识感兴趣的 Shape ,则必须遍历该集合,并查询直到找到 Shape .

    请参阅示例代码,您必须对其进行调整 .

    Sub PickShapeByPos()
        Dim sl As Slide
        Dim shidx As Integer, sh as Shape
    
        Dim topref As Integer, leftref As Integer
        ' Your code to set the reference point
    
        For Each sl In ActivePresentation.Slides
            For shidx = sl.Shapes.Count To 1 Step -1
                Set sh = sl.Shapes(shidx)
                If ((sh.Top - topref < 10) And (sh.Left - leftref < 10)) Then
                    ' Found it!
                    ...
                End If
            Next
        Next
    End Sub
    

    (PS:我目前没有Office系统,所以这段代码可能需要很少的调整) .

  • 0

    从sancho.s的回答开始,我想出了下面的建议 . 它是一个函数,返回符合您传递给函数的任何幻灯片的Top和Left条件的形状 . 它还允许您设置起始索引,因此您可以重复调用它,而不是一遍又一遍地拾取符合规格的第一个形状 .

    Sub TestShapeByLocation()
        Dim oSl As Slide
        Dim oSh As Shape
        Dim x As Long
    
        Set oSl = ActivePresentation.Slides(1)
    
        x = 1
        ' get the first shape that meets our specs
        Set oSh = ShapeByLocation(oSl, x, 100, 100)
        Do While Not oSh Is Nothing
            ' do whatever to the shape
            oSh.Left = oSh.Left + 100
            ' and get the next shape that meets our specs
            x = x + 1
            Set oSh = ShapeByLocation(oSl, x, 100, 100)
        Loop
    
    End Sub
    
    Function ShapeByLocation(oSl As Slide, lIndex As Long, _
            sngTop As Single, sngLeft As Single) As Shape
    
        Dim x As Long
        With oSl
            For x = lIndex To .Shapes.Count
                If .Shapes(x).Left <= sngLeft Then
                    If .Shapes(x).Top <= sngTop Then
                        Set ShapeByLocation = .Shapes(x)
                        Exit Function
                    End If
                End If
            Next
        End With
    End Function
    

相关问题