Search code examples
vbapowerpoint

Refactoring via Loop a VBA script involving With keyword To reduce Code Length


In a loop, I have an N by 1 table in PowerPoint slides that as I create them, I format them. I am showing below an example with N=2. How can I refactor this using a loop to reduce the length of the code, please?

With pptTable.Table.Cell(1, 1).Shape
    .TextFrame.TextRange.Font.Name = "Calibri"
    .TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignRight
    .TextFrame.TextRange.Font.Size = 54
    .TextFrame2.VerticalAnchor = msoAnchorMiddle
End With

With pptTable.Table.Cell(2, 1).Shape
    .TextFrame.TextRange.Font.Name = "Calibri"
    .TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignRight
    .TextFrame.TextRange.Font.Size = 54
    .TextFrame2.VerticalAnchor = msoAnchorMiddle
End With

Solution

  • You need to learn how to split activities up into smaller chunks so that they can be encapsulated in a sub or a function.

    Sub Test()
    
        ReformatShape ppttable, 1, 1
        ReformatShape ppttable, 2, 1
        ReformatShape ppttable, 3, 1, ipsize:=48
        ReformatShape ppttable, 4, 1, ipVerticalAnchor:=msoAnchorBottomBaseLine
        ' etc
    End Sub
    
    
    Public Sub ReformatShape _
    ( _
        ByVal ipTable As PowerPoint.Table, _
        ByVal ipX As Long, _
        ByVal ipY As Long, _
        Optional ByVal ipName As String = "Calibri", _
        Optional ByVal ipAlignment As PpParagraphAlignment = ppAlignRight, _
        Optional ByVal ipsize As Long = 54, _
        Optional ByVal ipVerticalAnchor As MsoVerticalAnchor = msoAnchorMiddle _
    )
    
        With iptable.Table.Cell(ipX,ipY).Shape
            .TextFrame.TextRange.Font.Name = ipName
            .TextFrame.TextRange.ParagraphFormat.Alignment = ipAlignment
            .TextFrame.TextRange.Font.Size = ipsize
            .TextFrame2.VerticalAnchor = ipVerticalAnchor
        End With
    
    End Sub