Determining The ActiveShape On Your Spreadsheet With VBA

Determining The ActiveShape On Your Spreadsheet With VBA

What This Does

There are times when you would like to know information about the currently selected shape on your spreadsheet.  This could be needed because you are trying to change something from a user-selected shape or you want to read-in some bit of information from the shape (most commonly the shape name or text).  There are two different scenarios of code this post will provide.

  1. Determining the name of a shape that is selected by the user
  2. Determining the text of a shape that was clicked-on to run a VBA macro

In both scenarios the code will set a shape variable to the active shape so you can then do as you please from there.

Shape Selected By User

Sub ActiveShape()
'PURPOSE: Determine the currently selected shape

Dim ActiveShape As shape
Dim UserSelection As Variant

'Pull-in what is selected on screen
  Set UserSelection = ActiveWindow.Selection

'Determine if selection is a shape
  On Error GoTo NoShapeSelected
    Set ActiveShape = ActiveSheet.Shapes(UserSelection.Name)
  On Error Resume Next

'Do Something with your Shape variable
  MsgBox "You have selected the shape: " & ActiveShape.Name

Exit Sub

'Error Handler
  MsgBox "You do not have a shape selected!"

End Sub

Shape Clicked On To Run A VBA Macro

Sub Shape_Clicked()
'PURPOSE: Determine what shape was clicked to initiate macro

Dim ActiveShape As shape

'Get Name of Shape that initiated this macro
  ButtonName = Application.Caller

'Set variable to active shape
  Set ActiveShape = ActiveSheet.Shapes(ButtonName)

'Do Something with your Shape variable
  MsgBox "You just clicked the " & ActiveShape.Name & " shape!"

End Sub

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)