Search code examples
vbapowerpoint

How to distribute table rows (from second to last) in PowerPoint with VBA


I am trying to distribute evenly rows across a presentation, so that from the second to the last of each slide they fit into the drawing area (that is, they reach the bottom of the content placeholder of the layout "Title and Content" Set masterShape = ActivePresentation.SlideMaster.CustomLayouts(2).Shapes.Placeholders(2)), while the first row should always be of the same height. However, I can only achieve this last point (the heading is indeed of the same height), while in each slide the total height is smaller than that of the reference placeholder. Below the code I have written.

Sub AdjustTableHeight()
Dim oShp As Shape
Dim oSld As slide
Dim p As Integer

Dim masterShape As Shape


Set masterShape = ActivePresentation.SlideMaster.CustomLayouts(2).Shapes.Placeholders(2)


        For Each oSld In ActivePresentation.Slides
            For Each oShp In oSld.Shapes


             If oShp.HasTable = msoTrue Then

                With ActivePresentation.Slides(2)
                    firstRowHeight = oShp.Table.Rows(1).Height
                End With
             
             
                oShp.Left = masterShape.Left
                oShp.Top = masterShape.Top
                oShp.Width = masterShape.Width

             
                With oShp.Table.Rows(1)
                    .Height = firstRowHeight
                End With
             
                For p = 2 To oShp.Table.Rows.Count 

                      oShp.Table.Rows(p).Height = (masterShape.Height - firstRowHeight) / oShp.Table.Rows.Count - 1 ' I also tried dividing by p, but the rows become very high and not equal to each other
    
                Next p

             End If

            Next oShp
        Next oSld


End Sub


Solution

  • Add parentheses around oShp.Table.Rows.Count - 1 to ensure subtraction happens before the division. Here's your macro in a more succinct form:

    Sub AdjustTableHeight()
        Dim oShp As Shape, masterShape As Shape
        Dim oSld As Slide
        Dim p As Integer
        
        Set masterShape = ActivePresentation.SlideMaster.CustomLayouts(2).Shapes.Placeholders(2)
        For Each oSld In ActivePresentation.Slides
            For Each oShp In oSld.Shapes
                If oShp.HasTable = msoTrue Then
                    With oShp
                        firstRowHeight = .Table.Rows(1).Height
                        .Left = masterShape.Left
                        .Top = masterShape.Top
                        .Width = masterShape.Width
                        .Table.Rows(1).Height = firstRowHeight
                        For p = 2 To .Table.Rows.Count
                            .Table.Rows(p).Height = (masterShape.Height - firstRowHeight) / (.Table.Rows.Count - 1)
                        Next p
                    End With
                End If
            Next oShp
        Next oSld
    End Sub