我想在启用宏的powerpoint演示文稿上的命令按钮上构建一个条件。如果形状存在,那么我希望它被删除,否则按钮应该产生一个关于没有这种形状这一事实的陈述。目前我遇到了麻烦...!如何获得Power点以识别形状为空?这是我的代码:
If ActivePresentation.Slides(3).Shapes("Picture") Is Nothing Then
MsgBox "no Picture"
Else
ActivePresentation.Slides(3).Shapes("Picture").Delete
MsgBox "Picture Cleared"
End If
此代码仅产生错误,因为形状不存在,因此第一个if语句失败。也许我们需要检查它是否在选择窗格中?
答案 0 :(得分:3)
其他一些建议可行,但总的来说,除非绝对必要,否则依靠选择是不好的做法。相反,你可以调用一个稍微不同的函数:
Function ShapeExists(ByVal oSl as Slide, ByVal ShapeName as String) as Boolean
Dim oSh as Shape
For Each oSh in oSl.Shapes
If oSh.Name = ShapeName Then
ShapeExists = True
Exit Function
End If
Next ' Shape
' No shape here, so though it's not strictly necessary:
ShapeExists = False
End Function
如果找到,你也可以修改它以返回对形状的引用,否则返回任何内容。
如果您不想使用早期的退出函数,可以通过简单的方法来编写它。
答案 1 :(得分:2)
正如@davidmneedham在评论中的链接(@ TimWilliams answer)中给出的那样,你可以使用类似如下的结构:
Option Explicit
Sub test()
Dim shp As Shape
Dim myshapeName As String
myshapeName = "Picture"
Dim sl As Slide
Set sl = ActivePresentation.Slides(1)
If shapePresent(sl, myshapeName) Then
sl.Shapes(myshapeName).Delete
Else
MsgBox myshapeName & " not present"
End If
End Sub
Private Function shapePresent(ByVal sl As Slide, ByVal myshapeName As String) As Boolean
On Error GoTo errhand
sl.Shapes(myshapeName).Select
shapePresent = True
Exit Function
errhand:
shapePresent = False
Err.Clear
End Function
使用与答案相同的格式:
Private Function shapePresent(ByVal sl As Slide, ByVal myshapeName As String) As Boolean
Dim myShape As Shape
On Error Resume Next
Set myShape = sl.Shapes(myshapeName)
On Error GoTo 0
shapePresent = Not myShape Is Nothing
End Function