Assign a macro to a shape in VBA

n3mesis125

New Member
Joined
Dec 19, 2007
Messages
19
HI all, I'm trying to figure out if it is possible to add a shape to a specific cell ie: rectangle and then assign a macro to the newly created shape? The reason I want to do this is because I am importing several rows of data and while the data imports, I want a rectangle shape to appear for each row and it will be a 'Modify' button. So I want to assign a macro to the shape so when a user clicks on the shape it will pop up a userform. But I want to do all of this with VBA since all of the data is being imported via VBA.
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
To answer the second half of your question, this is working for me.

In the Workbook Module, add this. You may also want to trigger the initialize sub when you add shapes or change shape names or sheet names.
Code:
Private Sub Workbook_Open()
initializeShapeClickEvents
End Sub

In another Module, add these.
Code:
Public Sub initializeShapeClickEvents()
'INITIALIZE THE OnAction FOR EACH SHAPE TO TRAP CLICKS WITH THE SHAPE NAMES
Dim theShape As Shape, theSheet As Worksheet

For Each theSheet In Sheets()
For Each theShape In theSheet.Shapes
'PASS THE SHAPE NAME AND THE WORKSHEET
theShape.OnAction = "'shapeClicked """ & theShape.name & """, """ & theSheet.name & """'"
Next theShape
Next theSheet
End Sub

Public Function shapeClicked(ByVal theShapeName As String, ByVal theSheet As String)
'.... do things
End Function
 
Upvote 0
As for the first part of your question, you can get the cell position like so...
Cells(1,1).Left and .Top, .Width, .Height

And use the same to position the shape.
Sheets("Sheet Name").Shapes("Shape Name").Left = Cells(1,1).Left
 
Upvote 0

Forum statistics

Threads
1,214,598
Messages
6,120,441
Members
448,966
Latest member
DannyC96

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top