Page 1 of 1

Replace paragraph text in Word

Posted: Sat Feb 03, 2024 7:18 pm
by punak
Hello
I use these codes to replace text in Word and it works great.
But
These codes do not change the text inside the paragraphs. What changes should be made in the codes for this?

Code: Select all

;/////////////////////////////////////////////////////////////////////////////////
;***COMate***  COM automation through iDispatch.
;*===========
;*
;*Search and replace in a Word document - by srod.
;/////////////////////////////////////////////////////////////////////////////////

IncludePath "..\"
XIncludeFile "COMatePLUS.pbi"

Define WordApplication.COMateObject 

#wdReplaceAll  = 2
  
inputDoc$ = "c:\testIN.doc"
outputDoc$ = "c:\testOUT.doc"

search$ = "is"
replace$ = "IS"


WordApplication = COMate_CreateObject("Word.Application") 
    
If WordApplication 
  If WordApplication\Invoke("Documents\Open('" + inputDoc$ + "')") = #S_OK 
    WordApplication\Invoke("Selection\GoTo(1)")
    WordApplication\SetProperty("Selection\Find\MatchWholeWord = #True")
    WordApplication\SetProperty("Selection\Find\Forward = #True")
    WordApplication\SetProperty("Selection\Find\Text = '" + search$ + "'")
    WordApplication\Invoke("Selection\Find\Execute(#Opt, #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, '" + replace$ + "', " + Str(#wdReplaceAll) + ")")
    WordApplication\Invoke("ActiveDocument\SaveAs('" + outputDoc$ + "')")
    WordApplication\Invoke("Quit(0)") 
  Else 
    MessageRequester("COMate -search and replace text in word document!", "Couldn't load the document!")
  EndIf 
  WordApplication\Release() 
Else 
  MessageRequester("COMate -search and replace text in word document!", "Couldn't create the application object!")
EndIf
;

Re: Replace paragraph text in Word

Posted: Sun Feb 04, 2024 1:31 am
by punak
Does anyone know the reason why this code does not work for paragraphs? I searched a lot, but I could not find a suitable code example. I really need this code, please help me. Thanks

Re: Replace paragraph text in Word

Posted: Mon Feb 05, 2024 8:40 pm
by punak
Has any member of the forum thought about my question? Is my question difficult to answer?

Re: Replace paragraph text in Word

Posted: Mon Feb 05, 2024 8:51 pm
by jacdelad
A bit impatient? You won't get an answer faster by damaging one.

Working with COMate isn't easy, there aren't many people here who can help you.

Re: Replace paragraph text in Word

Posted: Mon Feb 05, 2024 10:55 pm
by normeus
@punak,
I do not think you could write an output file to your c: drive from MSWord change the output to a subdirectory in c:\.
What do you mean it does not change text in paragraphs? Could you please show an example of a paragraph?

Code: Select all

IS this a good paragraph?
Comate plus IS good.
Sometimes I think it IS not a good example for all good people of earth. Other times it IS a good example , but this being a simple paragraph, I cannot think of another sentence with IS.
Also IS this a paragraph, yes it IS.
It changed to upper case with this silly test.

Norm.

Re: Replace paragraph text in Word

Posted: Tue Feb 06, 2024 5:55 am
by punak
I apologize :oops: , I mean by paragraph, the text box object in Word that is created from this menu.
Insert --> Text --> TextBox
The above codes do not have the ability to find and replace the text of these text boxes.and I desperately need some code to find and replace the text in these text boxes.

Thank.

Re: Replace paragraph text in Word

Posted: Tue Feb 06, 2024 12:30 pm
by spikey
punak wrote: Tue Feb 06, 2024 5:55 am I desperately need some code to find and replace the text in these text boxes.
Text boxes exist in a separate collection from the main text body, the Shapes collection. See https://learn.microsoft.com/en-us/offic ... ord.shapes and https://learn.microsoft.com/en-us/offic ... word.shape

Shapes are addressable via name:
Shapes("TextBox 1")

Or there is a count property and an iterator:
Shapes.Count
Shapes.Item(1)

You can change the text via the .TextFrame.TextRange.Text property, see https://learn.microsoft.com/en-us/offic ... .textframe

There's a VBA example showing how to use search and replace in text boxes at https://office-watch.com/2023/word-replace-text-boxes/
but this could be tricky to get to work unless you are experienced and confident with both the Word COM api and COMate. I suggest reading this item, if you haven't already: https://learn.microsoft.com/en-us/offic ... nd-methods

You could convert this by using the CreateEnumeration command, see COMateObject Class → General Methods → CreateEnumeration in the COMate help file and 'Demo_CollectionEnumeration.pb' in the COMate examples folder.

I don't have a PC with Microsoft Office installed any more so I'm sorry I can't test this but, hopefully, this is a place to start:

Code: Select all

EnableExplicit

; See https://learn.microsoft.com/en-us/office/vba/api/office.msoshapetype
#msoTextBox = 17 

; See https://learn.microsoft.com/en-us/office/vba/api/word.wdreplace
#wdReplaceAll = 2
#wdReplaceNone = 0
#wdReplaceOne = 1

IncludeFile "COMatePlus.pbi"

Define.COMateObject appWord, docThis, objShape, objTextRange
Define.COMateEnumObject colShapes
Define.I ShapeType
Define.S strCommand, strFind, strReplace

strFind = "ReplaceThis"
strReplace ="WithThis"

; Obtain an application object.
appWord = COMate_CreateObject("Word.Application")

If appWord = 0
  Debug "Failed to create application object."
  Debug COMate_GetLastErrorDescription()
  End
EndIf

appWord\SetProperty("Application\Visible=#True")
Debug "Visible:" + COMate_GetLastErrorDescription()

; Open the document.
strCommand = "Documents\Open('c:\testIN.doc')"
docThis = appWord\GetObjectProperty(strCommand)
If docThis = 0
  Debug "Failed to open the document."
  Debug COMate_GetLastErrorDescription()
  End
EndIf

; Get the shapes collection.
colShapes = docThis\CreateEnumeration("Shapes")
If colShapes = 0
  Debug "Failed to get the shapes collection."
  Debug COMate_GetLastErrorDescription()
  End
EndIf

; Start iteration.
objShape = colShapes\GetNextObject()
While objShape
  ShapeType = objShape\GetIntegerProperty("Type")
  Debug "Type: " +COMate_GetLastErrorDescription()
  
  If ShapeType = #msoTextBox
    
    ; Find and replace.
    ; See https://learn.microsoft.com/en-us/office/vba/api/word.find.execute
    objTextRange = objShape\GetObjectProperty("TextFrame\TextRange")
    Debug "TextFrame\TextRange: " + COMate_GetLastErrorDescription()
    strCommand = "Find\Execute('" + strFind + "', #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, #Opt, " + 
                 "'" + strReplace + "', " + StrU(#wdReplaceAll) + ", #Opt, #Opt, #Opt, #Opt)"
    objTextRange\Invoke(strCommand)
    Debug "Find\Execute : " + COMate_GetLastErrorDescription()
    
  EndIf
  
  ; Next iteration.
  objTextRange\Release()
  objShape\Release()
  objShape = colShapes\GetNextObject()
Wend

; Tidy up
colShapes\Release()
docThis\Release()
appWord\Release()

Re: Replace paragraph text in Word

Posted: Tue Feb 06, 2024 7:52 pm
by punak
Thank you all for the replies, especially spikey.
These codes worked. It works a bit slow only for my word document which has 27 text boxes.
Is there a way to speed up the codes?
Thank you again.

Re: Replace paragraph text in Word

Posted: Tue Feb 06, 2024 8:23 pm
by spikey
punak wrote: Tue Feb 06, 2024 7:52 pm These codes worked.
:D I'm a little surprised! As I said I couldn't test it and was expecting a problem somewhere.
punak wrote: Tue Feb 06, 2024 7:52 pm Is there a way to speed up the codes?
You could try putting this after opening the document:

Code: Select all

appWord\SetProperty("Application\ScreenUpdating=#False")
and this after the loop but before tidying up:

Code: Select all

appWord\SetProperty("Application\ScreenUpdating=#True")
It will make the updates occur invisibly and should improve the speed a little as a consequence.
punak wrote: Tue Feb 06, 2024 7:52 pm Thank you again.
You're welcome!

Re: Replace paragraph text in Word

Posted: Tue Feb 06, 2024 9:09 pm
by punak

Code: Select all

appWord\SetProperty("Application\Visible=#False")
Thanks, I don't use this feature (Visible) at all and it is always in false mode.
I make all the changes in the background and save a new word file.
In any case, these codes work correctly, but finding and replacing 27 text boxes runs at a noticeably slow speed.

Re: Replace paragraph text in Word

Posted: Wed Feb 07, 2024 7:51 pm
by spikey
That's about as good as it's going to get, I can't think of any other optimisations. There's a lot of getting and releasing references in this case, this all has overhead.