vba 如何在excel vba中获得选定的形状?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8246511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:12:43  来源:igfitidea点击:

How to get selected shape in excel vba?

excelvbaselectionshape

提问by Waqas

I have inserted a smart art, and converted it to shapes. And Selected a shape by clicking on it.

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

Now I want to get Shape object of slected shape. I have tried this but it throws exception.

现在我想获得所选形状的 Shape 对象。我试过这个,但它抛出异常。

dim shap as Excel.Shape = ExcelApp.Selection 

I can get the shape object by iterating on ActiveSheet.Shapes or like this

我可以通过迭代 ActiveSheet.Shapes 或像这样来获取形状对象

dim shap as Excel.Shape = ActiveSheet.Shapes.Item(1) 

But how would I know this shape is selected or not, Really need Help Thanks.

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

回答by Rachel Hettinger

Try Selection.ShapeRangeto get a reference to the shape object.

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

回答by Jbjstam

This gets a single selected Shape or Nothing if none or several shapes are selected. Obviously, you can drop the MsgBox calls.

如果没有或多个形状被选择,这将得到一个选定的形状或空。显然,您可以删除 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