Here's one way. I made it a little more flexible so that you can select one or more shapes that you want aligned, and the routine will align all selected shapes within the range they cover. The shapes may be positioned within a single cell or may overlap several shapes. The code finds the underlying range based on the top-left cell and bottom-right cell under the shape.
I made a UserForm F_AlignSelectedShapes with two checkboxes, chkHorizontal and chkVertical, both checked by default. The UserForm has two buttons, btnOK and btnCancel. The Default property of btnOK is True, so pressing Enter is the same as clicking btnOK. The Cancel property of btnCancel is True, so pressing Esc is the same as clicking btnCancel.
The code in the UserForm module is simple:
VBA Code:
Option Explicit
Private Sub btnOK_Click()
' loop through all selected shapes
Dim shp As Shape
For Each shp In Selection.ShapeRange
Dim TopLeftCell As Range, BottomRightCell As Range
Set TopLeftCell = shp.TopLeftCell
Set BottomRightCell = shp.BottomRightCell
Dim UnderlyingGrid As Range
Set UnderlyingGrid = Range(TopLeftCell, BottomRightCell)
If Me.chkHorizontal.Value Then
shp.Left = UnderlyingGrid.Left + (UnderlyingGrid.Width - shp.Width) / 2
End If
If Me.chkVertical.Value Then
shp.Top = UnderlyingGrid.Top + (UnderlyingGrid.Height - shp.Height) / 2
End If
Next
Unload Me
End Sub
Private Sub btnCancel_Click()
Unload Me
End Sub
I also have code in a regular code module that checks whether one or more shapes are selected, and if so, it displays the UserForm.
Code:
Option Explicit
Sub AlignSelectedShapesInGrid()
On Error Resume Next
Dim shprng As ShapeRange
Set shprng = Selection.ShapeRange
On Error GoTo 0
If Not shprng Is Nothing Then
F_AlignSelectedShapes.Show
End If
End Sub
In the left image you see two selected shapes in their original misaligned positions and the UserForm. In the right image you see the images in their center-aligned positions.
View attachment 63549