WiseOwl Training - Established 1992 Wise Owl Training

Established May 1992
30 years in business
Wise Owl Training
30 years in business
See 520 reviews for our classroom and online training
How to create autoshapes, lines and connectors in VBA macros
Part seven of an eight-part series of blogs

You can use Visual Basic within Excel, PowerPoint or Word to draw shapes, format them and even assign macros to run - this long blog gives lots of ideas of how to proceed!

  1. Working with shapes in VBA
  2. Working with shapes - getting started
  3. Naming, referring to and positioning shapes
  4. Formatting shapes and adding text
  5. Adding lines and connectors to join shapes together
  6. Working with multiple shapes
  7. Assigning macros to shapes (this blog)
  8. Exercises on shapes

This is one small part of our free online Excel VBA tutorial.  To find out how to learn in a more structured way, have a look at our training courses in VBA.

Posted by Andy Brown on 25 January 2014

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Assigning macros to shapes

Perhaps the most remarkable thing that you can do with shapes is get them to run macros:

Assigning macro to shape

We'll arrange it so that when you click on the shape, you'll see a message box appear!


Here's the message that clicking on the owl will show:

Owl hoot message

The message our macro will show.


To make this work you need to create a macro first, then assign it to a shape.

Creating the macro

Here's a modest macro which displays the hoot message on screen (and reads it out for good measure, although it sounds a bit strange!):

Sub Hoot()

'make the owl hoot!

MsgBox "Tu-whit, tu-whoo"

'just in case you missed it, say it out loud

Application.Speech.Speak "Tu-whit, tu-whoo"

End Sub

The macro you create must be contained in the same workbook as the shape.

 Assigning a macro to a shape

To do this, set the shape's OnAction property:

Sub CreateShapes()

'text box and owl logo, plus connector

Dim Logo As Shape

'set reference to a worksheet

Set w = ActiveSheet

'now add the owl logo (initially a rectangle)

Set Logo = w.Shapes.AddShape(1, 10, 10, 50, 50)

Logo.Fill.UserPicture "C:\ajb files\wise-owl-logo.jpg"

'assign a macro to it

Logo.OnAction = "Hoot"

End Sub

That's all that you need to do!  Clicking on the shape will now run the Hoot macro.


As a postscript to this blog, I've included some links to some online exercises, so that you can test your VBA ability!

This blog has 0 threads Add post