How do I remove extra spaces in PPT using VBA?

2019-08-31 14:43发布

问题:

Can anyone help me with the below code? I am trying to use VBA to remove any extra spaces in a PowerPoint presentation.

Sub removeSpaces()
Dim sld As Slide
Dim shp As Shape
For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes
    Do While InStr(shp, "  ") > 0
        shp.Value = Replace(shp, "  ", " ")
        shp.Value = Trim(shp.Value)
    Next shp
Next sld
End Sub

When I currently run it, it shows an error of "Method or data member not found" and highlights the "shp.Value" part.

回答1:

a Shape object doesn't have a .Value property. The Instr function may also not evaluate against a Shape object.

https://msdn.microsoft.com/en-us/library/office/ff747227(v=office.14).aspx

Generally, you need to refer to the shape's TextFrame, like:

Dim shpText as String

For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes
        If shp.HasTextFrame Then
            shpText = shp.TextFrame.TextRange.Text 'Get the shape's text
            Do While InStr(shpText, "  ") > 0
                shpText = Trim(Replace(shpText, "  ", " "))
            Loop
            shp.TextFrame.TextRange.Text = shpText 'Put the new text in the shape
        Else
            shpText = vbNullString
        End If
    Next shp    
Next sld
End Sub