Search code examples
vbapowerpointinputbox

Replace using InputBox in Powerpoint


I would like to replace the word "instrument" in all slides using input from the User. The code below worked when I set Replacement = "ppp" but when I changed it to Replacement = InputBox, the instrument is not replaced by the user input.

Any suggestions?

Sub Replaceinstrument()
    Dim sld As Slide
    Dim shp As Shape
    Dim Replacement As String
    

    For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes

    
    Replacement = InputBox("to change")
    
    If Replacement = "" Then Exit Sub
    
               
    If shp.HasTextFrame Then
        If shp.TextFrame.HasText Then
             With shp.TextFrame.TextRange
              .Replace "instrument", Replacement
                    
             End With
                             
            End If
        End If
        
    Next shp
    
Next

End Sub

Solution

  • Because you have InputBox inside the loop, it is running for every shape in your presentation. Here it is in working order:

    Sub Replaceinstrument()
        Dim sld As Slide
        Dim shp As Shape
        Dim Replacement As String
    
        Replacement = InputBox("to change")
        If Replacement = "" Then Exit Sub
        
        For Each sld In ActivePresentation.Slides
            For Each shp In sld.Shapes
                If shp.HasTextFrame Then
                    If shp.TextFrame.HasText Then
                        shp.TextFrame.TextRange.Replace "instrument", Replacement
                    End If
                End If
            Next shp
        Next
    End Sub