COM - Word - read and write

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
bat_boro
Posts: 4
Joined: 20 Apr 2016, 08:44

COM - Word - read and write

Post by bat_boro » 08 Aug 2016, 04:24

Hello,

I'm really having difficulties working with the COM model for Word. While I understand working with COM and ahk in Excel, I just can't wrap my head around Word. Checking the online documentation for the COM model on Microsoft's site didn't help either.

Could someone please lend me a hand by looking at my code below.
What I want to do is write a macro that would read the Excel file line by line, searching for a specific string and when it finds it, I want to replace it with another string.

Here is my sample code:

Code: Select all

FileSelectFile, Path
	oWord := ComObjCreate("Word.Application")
	oWord.Visible := True
	oWord.Documents.Open(Path)
	worddoc := oWord.ActiveDocument.Content.Text
	Loop, Parse, worddoc, `r`n
	{
		Msgbox, %A_Loopfield%
		
		newvar .= A_Loopfield
	}
	Msgbox, %newvar%
And here is my sample word file's contents:
This is a test document
Here are some values – 5, 10, 20, 40
Have fun doing com word ahk
So I understand that I can loop through the file line by line. What I want in this loop is a simple - I want to find every string "10" and replace it with let's say "20"
I can do that with StringReplace in AHK, but how would I write that to the file at the correct position? How would I say to word that I want this "10" to become "20"?

Thanks in advance!
Attachments

[The extension docx has been deactivated and can no longer be displayed.]

word optimizer.ahk
(1.99 KiB) Downloaded 117 times

User avatar
TLM
Posts: 1608
Joined: 01 Oct 2013, 07:52
Contact:

Re: COM - Word - read and write

Post by TLM » 08 Aug 2016, 17:04

You could pull the entire document into a variable or just use Find and Replace build into Word with something like this:

Code: Select all

oWord := ComObjCreate("Word.Application")
oWord.Visible := True
oWord.Documents.Open(Path)

FindAndReplace( oWord, "SEARCH FOR THIS", "CHANGE IT TO THIS" )

FindAndReplace( obj, search, replace )
{
	obj.Selection.Find.ClearFormatting
	obj.Selection.Find.Replacement.ClearFormatting
	obj.Selection.Find.Execute( search, 0, 0, 0, 0, 0, 1, 1, 0, replace, 2)
}

Avastgard
Posts: 133
Joined: 30 Sep 2016, 21:54

Re: COM - Word - read and write

Post by Avastgard » 29 Sep 2021, 09:29

TLM wrote:
08 Aug 2016, 17:04
You could pull the entire document into a variable or just use Find and Replace build into Word with something like this:

Code: Select all

oWord := ComObjCreate("Word.Application")
oWord.Visible := True
oWord.Documents.Open(Path)

FindAndReplace( oWord, "SEARCH FOR THIS", "CHANGE IT TO THIS" )

FindAndReplace( obj, search, replace )
{
	obj.Selection.Find.ClearFormatting
	obj.Selection.Find.Replacement.ClearFormatting
	obj.Selection.Find.Execute( search, 0, 0, 0, 0, 0, 1, 1, 0, replace, 2)
}
@TLM, or everyone who is around, how can I make this work if I want to find several different words and replace them with the content of separate word files?

My use case is I want to write the names of the topics of a document and then run a script to replace the names of the topics with the formatted content of a separate word document. For example:

1. I type in the document:

Introduction
Development
Conclusion

2. I run the script and it replaces the words written above with the contents of Introduction.docx, Development.docx and Conclusion.docx, respectively.

I already have a script that gets the second part of the job done (pasting the formatted content of a word document into another one), and it looks somewhat like this:

Code: Select all

FilePath := "C:\Users\username\AutoHotkey\Clauses\Formatted Text.docx"
    ComObjGet(FilePath).Range.FormattedText.Copy
    Send, ^v
How can I make this script search for a specified word and replace it with the content of Formatted Text.docx? It needs to contain several words to look for and replace with several other word files.
Last edited by Avastgard on 30 Sep 2021, 05:56, edited 1 time in total.

User avatar
flyingDman
Posts: 2791
Joined: 29 Sep 2013, 19:01

Re: COM - Word - read and write

Post by flyingDman » 29 Sep 2021, 11:26

I would not use copy-paste, rather the method TLM proposes. I.e. "You could pull the entire document into a variable". Assuming you have .docx files containing the relevant texts (Introduction.docx, Development.docx, Conclusion.docx) and a test.docx containing the words Introduction, Development, and Conclusion (all in the script's folder):

Code: Select all

oWord := ComObjCreate("Word.Application")
for each, doc in ["Introduction", "Development", "Conclusion"]
	{
	oWord.Documents.open(a_scriptdir "\" doc ".docx")
	%doc% := oWord.ActiveDocument.content.text
	oWord.activedocument.close(0)
	}
;~ msgbox % Introduction "`n" Development "`n" Conclusion	

oWord.Documents.Open(a_scriptdir "\test.docx")	
oWord.visible := True
oWord.activate
sleep, 3000											; allows you to see the replacements. delete when satisfied
for each, doc in ["Introduction", "Development", "Conclusion"]
	oWord.Selection.Find.Execute(doc, 0, 0, 0, 0, 0, 1, 1, 0, %doc%, 2)    ; replace the word with the text in the variable 
;~ oWord.activedocument.close(1)								; to save the new file	
;~ oWord.quit()												; to close Word
14.3 & 1.3.7

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

Re: COM - Word - read and write

Post by FanaticGuru » 29 Sep 2021, 16:04

Avastgard wrote:
29 Sep 2021, 09:29
My use case is I want to write the names of the topics of a document and then run a script to replace the names of the topics with the formatted content of a separate word document. For example:

1. I type in the document:

Introduction
Development
Conclusion

2. I run the script and it replaces the words written above with the contents of Introduction.docx, Development.docx and Conclusion.docx, respecitvely.

An example of finding the word "Introduction" and replacing it with the file "Introduction.docx".

Code: Select all

wdApp := ComObjActive("Word.Application")
wdApp.Selection.Find.Execute("Introduction",,,,,,,1)
wdApp.Selection.InsertFile(A_Desktop "/Test/Introduction.docx")

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

burque505
Posts: 1731
Joined: 22 Jan 2017, 19:37

Re: COM - Word - read and write

Post by burque505 » 29 Sep 2021, 16:07

Nice, FG, that will help me also.
Thanks!
Regards,
burque505

Avastgard
Posts: 133
Joined: 30 Sep 2016, 21:54

Re: COM - Word - read and write

Post by Avastgard » 29 Jun 2022, 08:38

FanaticGuru wrote:
29 Sep 2021, 16:04
Avastgard wrote:
29 Sep 2021, 09:29
My use case is I want to write the names of the topics of a document and then run a script to replace the names of the topics with the formatted content of a separate word document. For example:

1. I type in the document:

Introduction
Development
Conclusion

2. I run the script and it replaces the words written above with the contents of Introduction.docx, Development.docx and Conclusion.docx, respecitvely.

An example of finding the word "Introduction" and replacing it with the file "Introduction.docx".

Code: Select all

wdApp := ComObjActive("Word.Application")
wdApp.Selection.Find.Execute("Introduction",,,,,,,1)
wdApp.Selection.InsertFile(A_Desktop "/Test/Introduction.docx")

FG
@FanaticGuru sorry I haven't reported back for such a long time, but I only had time to test this very recently.

I put this script together:

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

wdApp := ComObjActive("Word.Application")
wdApp.Selection.Find.Execute("introduction",,,,,,,1)
wdApp.Selection.InsertFile("C:\...\introduction.docx")

wdApp := ComObjActive("Word.Application")
wdApp.Selection.Find.Execute("development",,,,,,,1)
wdApp.Selection.InsertFile("C:\...\development.docx")

wdApp := ComObjActive("Word.Application")
wdApp.Selection.Find.Execute("conclusion",,,,,,,1)
wdApp.Selection.InsertFile("C:\...\conclusion.docx")
It mostly works as intended, but the way it is now, even if only type introduction and run the script, it will insert the content of all the three documents (introduction.docx, development.docx and conclusion.docx).

I would like it to only replace what it actually finds in the document I'm composing. I assumed this was the script was supposed to do, as it needs to find the corresponding term, but apparently not. Do I need to insert If conditions to make this work or is the problem something else?

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

Re: COM - Word - read and write

Post by FanaticGuru » 29 Jun 2022, 15:00

Avastgard wrote:
29 Jun 2022, 08:38
I would like it to only replace what it actually finds in the document I'm composing. I assumed this was the script was supposed to do, as it needs to find the corresponding term, but apparently not. Do I need to insert If conditions to make this work or is the problem something else?

Just needs an If to check if it finds the words you are searching for.

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

wdApp := ComObjActive("Word.Application")
if wdApp.Selection.Find.Execute("introduction",,,,,,,1)
	wdApp.Selection.InsertFile(A_Desktop "\Test\introduction.docx")
if wdApp.Selection.Find.Execute("development",,,,,,,1)
	wdApp.Selection.InsertFile(A_Desktop "\Test\development.docx")
if wdApp.Selection.Find.Execute("conclusion",,,,,,,1)
	wdApp.Selection.InsertFile(A_Desktop "\Test\conclusion.docx")

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

Avastgard
Posts: 133
Joined: 30 Sep 2016, 21:54

Re: COM - Word - read and write

Post by Avastgard » 01 Jul 2022, 08:17

Thanks, it works as intended now!

Post Reply

Return to “Ask for Help (v1)”