BeateF
BeateF

Reputation: 11

how to find ALL occurrences of a string in PowerPoint with the VBA replace function

I am trying to replace all carriage returns with the ¶ symbol to make the carriage returns visible in PPT (only word has a button for this, PPT does not). Since the "replace" function only finds the first occurrence, I need to loop through each string to find the next occurrences.

I am using the sample code from the MS "replace" function, but the code only finds SOME of the carriage returns but not ALL of them. What am I missing? Thanks!

VBA code:

If .HasTextFrame Then
    If .TextFrame.HasText Then
        'MsgBox (.TextFrame.TextRange.Text)
        Set oTxtRng = oSh.TextFrame.TextRange

        'Set oTmpRng = oTxtRng
        Set oTmpRng = oTxtRng.Replace(FindWhat:=Chr$(13), _
        Replacewhat:=("¶"))

        Do While Not oTmpRng Is Nothing
            Set oTxtRng = oTxtRng.Characters(oTmpRng.Start + oTmpRng.Length + 1, _
            oTxtRng.Length)
            charCount = charCount + 1

            'MsgBox (oTxtRng.Text)

            Set oTmpRng = oTxtRng.Replace(FindWhat:=Chr$(13), Replacewhat:=("¶"))
        Loop

    End If
End If

Upvotes: 1

Views: 1125

Answers (3)

user6853416
user6853416

Reputation: 11

I experienced the same issue with the Microsoft Sample code. It seems to miss certain occurrences (although consistently). Anyway, to fix it, instead of redefining oTxtRng, I instead changed it to use the After:= parameter. That seems to work reliably:

If .HasTextFrame Then
  If .TextFrame.HasText Then
    'MsgBox (.TextFrame.TextRange.Text)
    Set oTxtRng = oSh.TextFrame.TextRange

    'Set oTmpRng = oTxtRng
    Set oTmpRng = oTxtRng.Replace(FindWhat:=Chr$(13), _
    Replacewhat:=("¶"))

    Do While Not oTmpRng Is Nothing
        charCount = charCount + 1

        'MsgBox (oTxtRng.Text)

        Set oTmpRng = oTxtRng.Replace(FindWhat:=Chr$(13), Replacewhat:=("¶"), After:=oTmpRng.Start + oTmpRng.Length)
    Loop

  End If
End If

Upvotes: 1

Steve Rindsberg
Steve Rindsberg

Reputation: 14809

PPT uses different line ending characters, depending on version and what type of text box it is even within one version; paragraph endings are different from linebreaks also. This page on my PPTFAQ site should help:

Paragraph endings and line breaks http://www.pptfaq.com/FAQ00992_Paragraph_endings_and_line_breaks.htm

Upvotes: 1

Programnik
Programnik

Reputation: 1565

Use the Replace function, not the text range Replace method, eg

dim sText = Replace(oTxtRng.Text, Chr$(13), "¶")

oTxtRng.Text = sText

Replace function replaces all occurrences in one go.

Upvotes: 0

Related Questions