如何在excel vba中选择形状?

时间:2011-11-23 17:28:16

标签: excel vba selection shape

我插入了一个智能艺术品,并将其转换为形状。并通过点击选择一个形状。

现在我想获得选定形状的Shape对象。我试过了,但它引发了异常。

dim shap as Excel.Shape = ExcelApp.Selection 

我可以通过迭代ActiveSheet.Shapes或像这样

来获取形状对象
dim shap as Excel.Shape = ActiveSheet.Shapes.Item(1) 

但我怎么知道这个形状是否被选中,真的需要帮助谢谢。

2 个答案:

答案 0 :(得分:3)

尝试Selection.ShapeRange获取对形状对象的引用。

答案 1 :(得分:1)

如果未选择任何形状或多个形状,则会获得单个选定的Shape或Nothing。显然,您可以删除MsgBox调用。

Function GetSelectedShape() As Shape
    If TypeName(Selection) <> "Rectangle" Then
        MsgBox "Selection is not a single shape"
        Exit Function
    End If
    Dim oShapes As ShapeRange
    Set oShapes = Selection.ShapeRange

    If oShapes.Count <> 1 Then
        MsgBox "Selection is not a single shape"
        Exit Function
    End If

    Set GetSelectedShape = oShapes(1)

End Function