Align Charts to Worksheet Grid Via Chart Names
In the previous post, I presented a macro that aligned embedded charts to a worksheet cell grid given certain criteria. The macro works OK if you're not concerned about the order in which any chart is placed on the worksheet. Andy Pope offered a more efficient version via comment. However, after more review I found that the macro would rearrange the original placement of one or more of the charts if one or more of the original charts were deleted and replaced. The root of the problem is that embedded charts are really shapes that are stored with an index number in the shapes collection. If a shape is deleted and a new shape created, the new shape is given the last index number in the collection. To place individual charts where you want, you need to somehow specify what index number of the shape you want to where.
The only way I could think of to get around this problem was to name each chart individually and the order the charts by name. Depending on how I wanted the charts to fall on the worksheet, I named each chart "Cht1", "Cht2", "Cht3", etc. I then modified Andy's macro to order the charts by the chart names:
Sub AlignCharts()
Dim Cht As ChartObject
Dim ChartsAcross As Integer
Dim ColumnsAcross As Integer
Dim RowsDown As Integer
Dim Rng1 As Range
Dim Rng2 As Range
Set Rng1 = Range("B2")
ChartsAcross = 3
ColumnsAcross = 4
RowsDown = 10
Set Rng2 = Rng1
TotalCharts = 0
For Each Cht In ActiveSheet.ChartObjects
TotalCharts = TotalCharts + 1
Next Cht
For Cnt = 1 To TotalCharts
Set Cht = ActiveSheet.ChartObjects("Cht" & Cnt)
With Cht
.Top = Rng1.Top
.Left = Rng1.Left
.Height = 94.5
.Width = 144
End With
If Cnt Mod ChartsAcross = 0 Then
Set Rng1 = Rng2.Offset(RowsDown, 0)
Set Rng2 = Rng1
Else
Set Rng1 = Rng1.Offset(0, ColumnsAcross)
End If
Next
End Sub