Search code examples
vbastring-formattingpowerpoint

Remove Line Break in Powerpoint VBA


I saw this post but I couldn't modify my VBA script for PPT presentation. Almost each slide has text in textbox. However, at the end of some textboxes there are multiple line breaks at the end (Enter hits), about 1-3 in some places. I would like to have a macro to delete those uneccessary line breaks. Tell me what I'm doing wrong here (2 scripts):

Sub RemoveSpaces(osh As Shape)

Dim oSl As Slide
    Dim osh As Shape


    With ActivePresentation

For Each oSl In .Slides
    For Each osh In oSl.Shapes
        With osh
            If .HasTextFrame Then
                If .TextFrame.HasText Then
                    If Right$(osh.TextFrame.TextRange.Characters(osh.TextFrame.TextRange.Length, 2)) = vbCrLf Then
                    osh.TextFrame.TextRange.Text = Left$(osh.TextFrame.TextRange.Text, Len(osh.TextFrame.TextRange.Text) - 2)
                    End If
                End If
            End If
        End With
    Next
Next

    End With
End Sub

and

Sub RemoveSpaces()

Dim oSl As Slide
    Dim osh As Shape


    With ActivePresentation

For Each oSl In .Slides
    For Each osh In oSl.Shapes
        With osh
            If .HasTextFrame Then
                If .TextFrame.HasText Then
                    If osh.TextFrame.TextRange.Characters(osh.TextFrame.TextRange.Length - 2, 2).Text = vbCrLf Then
                    osh.TextFrame.TextRange.Characters(osh.TextFrame.TextRange.Length - 2, 2).Delete
                    End If
                End If
            End If
        End With
    Next
Next

    End With
End Sub

Solution

  • When I press enter in PowerPoint, it apparently adds a Vertical Tab which is ASCII code of 11. Try the following:

    Sub RemoveSpaces()
    
    Dim oSl As Slide
        Dim osh As Shape
    
    
        With ActivePresentation
    
    For Each oSl In .Slides
        For Each osh In oSl.Shapes
            With osh
                If .HasTextFrame Then
                    If .TextFrame.HasText Then
                        Do While osh.TextFrame.TextRange.Characters(osh.TextFrame.TextRange.Length - 1, 1).Text = Chr(11)
                            osh.TextFrame.TextRange.Characters(osh.TextFrame.TextRange.Length - 1, 1).Delete
                        Loop
                    End If
                End If
            End With
        Next
    Next
    
        End With
    End Sub