Find and replace in word document from word

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Find and replace in word document from word

Post by YasserKhalil »

Hello everyone
I am using a code that was working well as for this topic
This is part of the code

Code: Select all

    With ThisWorkbook.Worksheets("INF")
        objDoc.Content.Find.Execute findText:="XXXXX", ReplaceWith:=.Range("B3").Value, MatchWholeWord:=False, Replace:=2
        objDoc.Content.Find.Execute findText:="YYYYY", ReplaceWith:=.Range("B5").Value, MatchWholeWord:=False, Replace:=2
    End With
It finds and replaces specific words and no problem at that point.
The problem is that the string in Arabic doesn't come correctly unless the direction of the writing is set to Arabic (by changng Shift + Alt ). How can this be automatically done via the code?

User avatar
HansV
Administrator
Posts: 78236
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Find and replace in word document from word

Post by HansV »

You'll probably have to use Word.Selection object, loop instead of replacing everything in one go, and use the Selection.RtlRun method (Word) method.
Since I don't have Arabic installed, I cannot help you with the details.
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Find and replace in word document from word

Post by YasserKhalil »

Thanks a lot. I have found some codes but the variables for word VBA doesn't work in excel. Such as wdStory
objDoc.Selection.EndKey Unit:=wdStory

User avatar
HansV
Administrator
Posts: 78236
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Find and replace in word document from word

Post by HansV »

You can fix this as follows:
- Start Word.
- Activate the Visual Basic Editor (Alt+F11).
- Activate the Immediate window (Ctrl+G).
- Type the following, then press Enter:

? wdStory

- You'll see that the value of wdStory is 6.
- Change wdStory to 6 in your code.
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Find and replace in word document from word

Post by YasserKhalil »

Thanks a lot, my tutor. That's a great tip.

User avatar
HansV
Administrator
Posts: 78236
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Find and replace in word document from word

Post by HansV »

Another way to find out is by starting the Object Browser in Word's Visual Basic Editor by pressing F2.
Type wdStory (or another Word constant) in the search box and press Enter.
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4911
Joined: 31 Aug 2016, 09:02

Re: Find and replace in word document from word

Post by YasserKhalil »

Thank you very much for your great support.