Thursday, January 24, 2008

Excel VBA: Moving a Shape to Specific Position

To move a shape to a specific position of an excel workbook, you can specify the location of the shape's top, left corner by using the following commands:

ActiveSheet
.shapes(X).top = 100
ActiveSheet.shapes(X).left = 200

Each shape is referred to by a number so replace the X by that number. the first shape up is numbered 1, the second is numbered 2 and so on. The code for shape 1 would look like:

ActiveSheet.shapes(1).top = 100
ActiveSheet.shapes(1).left = 200


Each shape is also given a name such as "Rectangle 1" so an alternative to this code is:

ActiveSheet.shapes("Rectangle 1").top = 100
ActiveSheet.shapes(
"Rectangle 1").left = 200

Now, as far as exactly where the shapes will be located, you will likely have to play around with it to get it right, the location does not appear to correspond with pixels or cell locations, so just try different numbers and see where it ends up!

I will post code soon that will allow a user to identify a shape's name by clicking it. Leave a comment and I will likely post it sooner. In the meantime, you can record a macro to get the shapes name or keep track of the order in which you added the shapes so you can refer to them by number (or by "Rectangle 1" for the first rectangle you add, "Rectangle 2" for the second, etc.)

2 comments:

Unknown said...

In a loop, such as:

For Each x In ActiveSheet.Shapes

Next x

in what order are the shapes selected?

JB said...

The shapes are selected in the order you added them. So if you drew a square and then drew a circle, the square would be the first one selected, and the circle next.