Waqas
Waqas

Reputation: 4489

How to get selected shape in excel vba?

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.

dim shap as Excel.Shape = ExcelApp.Selection 

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

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

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

Upvotes: 2

Views: 38257

Answers (2)

Jbjstam
Jbjstam

Reputation: 884

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

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

Upvotes: 1

Rachel Hettinger
Rachel Hettinger

Reputation: 8442

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

Upvotes: 3

Related Questions