We help IT Professionals succeed at work.

Powerpoint macro: TextFrame.TextRange.character(place, length).delete creates a space in the place of the deleted part

Laszlo Benedek
on
604 Views
Last Modified: 2018-01-17
The code below should find and replace certain words. It works fine for full words, but when I only want to replace part of a word a space is inserted before the new part.

Eg powerpoint has a textbox

test[1]

the result should be

test[2]

but instead it is

test [2]

Sub test()
Call replace("[1]", "[2]")

End Sub




'goes trhough each slide and textbox
'replaces old text with new text without affecting the formatting
Sub replace(OldTxt, NewTxt)
    Dim sld As Slide
    Dim grpItem As Shape
    Dim shp As Shape
    Dim i As Integer
    Dim j As Integer
    Dim varTemp As Variant
    Dim lenStr As Integer
    Dim posStr As Integer
    Dim s As String

    lenStr = Len(OldTxt)
    For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes

        If shp.HasTextFrame Then
            If shp.TextFrame.HasText Then
                With shp.TextFrame.TextRange

                    Do While InStr(1, .Text, OldTxt, vbTextCompare) > 0
                        posStr = InStr(1, .Text, OldTxt, vbTextCompare)
                        'this is where the new character is added
                        .Characters(posStr, lenStr).InsertAfter NewTxt
                        .Characters(posStr, lenStr).Delete
                    Loop
                End With
            End If
        End If


    Next shp
Next
End Sub

Open in new window

Comment
Watch Question

Author

Commented:
Note: this problem doesn't occur when a full word is replaced: ie if there's one space before the replaced part to start with, there is not going to be an extra one.
NorieAnalyst Assistant
CERTIFIED EXPERT

Commented:
If you want to find and replace couldn't you use the VBA Replace function?
CERTIFIED EXPERT
Top Expert 2016
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks it works

Author

Commented:
Norie
I tried that. The problem is that it makes the whole text box have unifom formatting based on the first character.

Here's the related question explaining it:
https://www.experts-exchange.com/questions/29020149/How-to-find-and-replace-with-macro-in-powerpoint-without-affecting-the-formatting.html#a42118295
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.