Calling search and replace in MS Words

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Calling search and replace in MS Words

11 Sep 2018, 06:18

Greetings,

Anyone can point me to how I can call a search and replace function in MS Word? The script I have does that:

Str2 := "C:\Templates\"
Str3 := " - Word"
Str4 = %Str2%%Str1%.docX
Str6 := " "
Str5 = %Str1%%Str3%

run winword.exe %Str4%
WinWait, %Str5%,
IfWinNotActive, %Str5%, , WinActivate, %Str5%,
WinWaitActive, %Str5%,

It simply opens a word document. Then I need to do a search and replace. I tried to simply use click and send but the confirmations windows are too much of a pain and I could not make the coordinates work right.

Thank you
User avatar
Scr1pter
Posts: 1272
Joined: 06 Aug 2017, 08:21
Location: Germany

Re: Calling search and replace in MS Words

11 Sep 2018, 09:25

Hi,

Our professionals will probably suggest using COM.
I have no Word COM experience, so I can't help with COM.

Okay, anyway, with your current script you're able to open an MS Word document - is that correct?
What happens if you make a simple

Code: Select all

Send ^h
?

What confirmation windows are you speaking about?

P.S: I'm not really sure if you need such an amount of variables, but maybe that's just a taste of style.

Regards
Please use [code][/code] when posting code!
Keyboard: Logitech G PRO - Mouse: Logitech G502 LS - OS: Windows 10 Pro 64 Bit - AHK version: 1.1.33.09
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Re: Calling search and replace in MS Words

11 Sep 2018, 09:47

It does open word with the right file perfectly.
I was able to write a script to open the find and replace (ctlr-H), put the search string and replace string, click on the replace buttom, but the pop up window after that, I am not able to get or use the right coordinates to click on the close button.
User avatar
Scr1pter
Posts: 1272
Joined: 06 Aug 2017, 08:21
Location: Germany

Re: Calling search and replace in MS Words

11 Sep 2018, 10:55

Why not just sending Esc?

Code: Select all

Send {Esc}
Instead of trying to close it with the mouse, use keys.

My suggestion is:
Use keys whenever it is possible.
(Especially to avoid any kind of coordinates issues).

Edit:
If Esc doesn't work, try to close the window by:

Code: Select all

Send !{F4} ; Alt+F4
This won't close Word when sending it just 1x

Regards
Please use [code][/code] when posting code!
Keyboard: Logitech G PRO - Mouse: Logitech G502 LS - OS: Windows 10 Pro 64 Bit - AHK version: 1.1.33.09
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

11 Sep 2018, 11:24

kestak wrote:Anyone can point me to how I can call a search and replace function in MS Word?

It simply opens a word document. Then I need to do a search and replace.

Code: Select all

F2::
	wdApp := ComObjCreate("Word.Application")
	wdApp.Visible := true
	wdDoc := wdApp.Documents.Open(A_Desktop "\Test\One.docx")
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdDoc.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
return
FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Re: Calling search and replace in MS Words

11 Sep 2018, 12:38

The last piece of code is almost it. It opens word, but no document opens in the word. I am sure of the name, path and the folder is R/W for sure (full admin right to the script).

Are you sure the script is good and does not miss something?

Thank you
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

11 Sep 2018, 13:04

kestak wrote:The last piece of code is almost it. It opens word, but no document opens in the word. I am sure of the name, path and the folder is R/W for sure (full admin right to the script).

Are you sure the script is good and does not miss something?

Thank you
It works perfectly for me.

I did do the filename and path a little funny to link to my test folder on the desktop of my computer. You might try the more straight forward example below:

Code: Select all

F2::
	wdApp := ComObjCreate("Word.Application")
	wdApp.Visible := true
	FileName := "C:\Test\One.docx" ; change this to your path and filename
	wdDoc := wdApp.Documents.Open(FileName)
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdDoc.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
return
FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Re: Calling search and replace in MS Words

11 Sep 2018, 14:22

Thank you!!!!

The more straightforward version works perfectly!!!!
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Re: Calling search and replace in MS Words

11 Sep 2018, 14:35

I have another question. That solution is way better than what I have. The algorithm is simple:
1 - Open the document
2 - Replace a few string
3 - Select all the text and copy (I was doing click on text, ctrl-A, ctrl-B, close the document without saving
4 - Ctrl-c into another application

My question is simple, with your way to do the thing, how can I do step 3?
I am sorry if my question sounds stupid. I am not a programmer.

Thank you for your help!!!!!
awel20
Posts: 211
Joined: 19 Mar 2018, 14:09

Re: Calling search and replace in MS Words

11 Sep 2018, 18:09

Code: Select all

; Copy the main text range
wdDoc.StoryRanges(1).Copy ; wdMainTextStory = 1

; Close wdDoc without saving
wdDoc.Close(0) ; wdDoNotSaveChanges = 0

; Quit word
wdApp.Quit

; Free all global objects (not necessary when using local vars).
wdApp := wdApp := ""
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

11 Sep 2018, 19:04

Code: Select all

F2::
	wdApp := ComObjCreate("Word.Application")
	wdDoc := wdApp.Documents.Open("c:\Test\One.docx")
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdDoc.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
	wdApp.Selection.WholeStory
	wdApp.Selection.Copy
	;
	; Do what ever you need to paste to your other application
	;
	wdApp.Quit(0)	; quit without saving changes, -1 to automatically save
return
No reason to display the Word application if you are just opening to get info and then closing.

You could do the pasting after the wdApp.Quit(0) but will run into problems if the clipboard "contains a large amount" as Word clears a large clipboard by default. You could work around this if really needed.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

11 Sep 2018, 19:17

Code: Select all

F2::
	wdApp := ComObjCreate("Word.Application")
	wdDoc := wdApp.Documents.Open("c:\Test\One.docx")
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdDoc.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
	wdApp.Selection.WholeStory
	wdApp.Selection.Copy
	Clip := ClipboardAll
	wdApp.Quit(0)	; quit without saving changes, -1 to automatically save
	Clipboard := Clip
	Send ^v
return
Example that can handle large clipboard. Just get where you want the data pasted and hit F2.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
kestak
Posts: 40
Joined: 15 Aug 2018, 06:35

Re: Calling search and replace in MS Words

11 Sep 2018, 19:49

Thank you very much!
The file is not big at all. Maximum 1000 words (5k max).
I will try that code tomorrow.

Thank you again!
Gibbons
Posts: 93
Joined: 20 Sep 2016, 20:39

Re: Calling search and replace in MS Words

12 Sep 2018, 14:00

In case you have several to do at once:

Code: Select all

MSWordMultiReplace("apple", "banana", "one", "two")

MSWordMultiReplace(params*) ; params* can be any number of text pairs the first of the pair being the text to be replaced, the second the replacement text
{                           ; thus ("apple", "banana", "one", "two") will replace all "apple"s with "banana" and all "one"s with "two".
	oWord := ComObjActive("Word.Application")
	oWord.Selection.Find.ClearFormatting
	oWord.Selection.Find.Replacement.ClearFormatting
	for k,v in params
	{
		c++
		if (c = 1)
		{
			st := v
			continue
		}
		rt := v, c := 0
		oWord.Selection.Find.Execute(st, 0, 0, 0, 0, 0, 1, 1, 0, rt, 2)
	}
	return
}
Fleon
Posts: 11
Joined: 27 Aug 2021, 15:19

Re: Calling search and replace in MS Words

31 Aug 2021, 10:35

Hey, all of you are much better than I am with COM. Hoping you can help. I am trying to do a find and replace within the active word document. Let's say I want to replace all of A with BBB. This is what I've pieced together, but it doesn't work. Doesn't seem to do anything at all. I know it's launching, b/c I get my Msgbox popup. Can you guys figure out what's wrong? I've tried the following two things:

1)

Code: Select all

Find = "A"
Replace = "BBB"
WordApp := ComObjActive("Word.Application")
WordApp.Selection.Find.Execute(Find,0,0,0,0,0,1,1,0,Replace,2,0,0,0,0)

Msgbox did it do it?
return
[Mod edit: [code][/code] tags added.]


2)

Code: Select all

WordApp := ComObjActive("Word.Application")
WordApp.Selection.Find.Execute("A",0,0,0,0,0,1,1,0,"BBB",2,0,0,0,0)
Msgbox did it do it? F5
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

31 Aug 2021, 15:08

Fleon wrote:
31 Aug 2021, 10:35
Hey, all of you are much better than I am with COM. Hoping you can help. I am trying to do a find and replace within the active word document. Let's say I want to replace all of A with BBB. This is what I've pieced together, but it doesn't work. Doesn't seem to do anything at all. I know it's launching, b/c I get my Msgbox popup. Can you guys figure out what's wrong? I've tried the following two things:

1)

Code: Select all

Find = "A"
Replace = "BBB"
WordApp := ComObjActive("Word.Application")
WordApp.Selection.Find.Execute(Find,0,0,0,0,0,1,1,0,Replace,2,0,0,0,0)

Msgbox did it do it?
return
[Mod edit: [code][/code] tags added.]


2)

Code: Select all

WordApp := ComObjActive("Word.Application")
WordApp.Selection.Find.Execute("A",0,0,0,0,0,1,1,0,"BBB",2,0,0,0,0)
Msgbox did it do it? F5

Here is an example:

Code: Select all

F3::
	wdApp := ComObjActive("Word.Application")
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdDoc.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
return
Your problem might be you are just searching the selected text and not the entire content of the document.

You might only want to search the selected but if not then you may not be getting the expected results.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Fleon
Posts: 11
Joined: 27 Aug 2021, 15:19

Re: Calling search and replace in MS Words

31 Aug 2021, 15:38

Thanks, but doesn't seem to be the problem. I manually selected a bunch of text and ran it and still nothing. I mean, other than my msgbox popup, it seems to be doing nothing at all.
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Calling search and replace in MS Words

31 Aug 2021, 17:15

Fleon wrote:
31 Aug 2021, 15:38
Thanks, but doesn't seem to be the problem. I manually selected a bunch of text and ran it and still nothing. I mean, other than my msgbox popup, it seems to be doing nothing at all.
I noticed when I actually run my code that I did not define wdDoc. I snippetted the posted code out of an existing project.

Tested, working code:

Code: Select all

F3::
	wdApp := ComObjActive("Word.Application")
	sFind := "My Name"
	sReplace := "Fanatic Guru"
	wdApp.ActiveDocument.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2)
return
The problem with your code example is the difference between using = and :=.

This works for me:

Code: Select all

Find := "A"
Replace := "BBB"
WordApp := ComObjActive("Word.Application")
WordApp.Selection.Find.Execute(Find,0,0,0,0,0,1,1,0,Replace,2,0,0,0,0)

Msgbox did it do it?
Also, as a side not Selection does not limit the Find to just the selection range because of how the Find method works. It is actually trickier to Find and Replace only within a selected range than I first realized. If you truly only want to Find/Replace within a selection then it is going to require more work.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Fleon
Posts: 11
Joined: 27 Aug 2021, 15:19

Re: Calling search and replace in MS Words

01 Sep 2021, 10:15

Hey, FG - thanks so much for the help so far. This is the error I'm getting. Any ideas?

This is when the Word document is the active window and the mouse cursor is on it.


error.png
error.png (36.79 KiB) Viewed 1929 times
Fleon
Posts: 11
Joined: 27 Aug 2021, 15:19

Re: Calling search and replace in MS Words

01 Sep 2021, 14:21

Hey FG,

Thanks! Your code actually did work. In fact, so did many of my prior attempts. I googled the error I was getting and looks like a reboot cleared out whatever Word was doing wrong.

I have a different question for you, if you have some more interest in helping.

wdApp.ActiveDocument.Content.Find.Execute(sFind,0,0,0,0,0,1,1,0,sReplace,2) WILL replace all the variables that are in the text. HOWEVER, it will not replace variables that are in a text box. The normal ^h Find/Replace does work to do this correctly. I found that this seems to be a problem for other people:

https://stackoverflow.com/questions/14256417/word-automation-find-and-replace-not-including-text-boxes

I'm playing around a bit, but this may be more COM than I really am comfortable with. Do you have some suggestions on adapting this to AHK?

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Descolada, Rohwedder, ulysim and 388 guests