Page 1 of 1

Loop through MS Word Object (StoryRanges) Using For Loop

Posted: 18 Jun 2016, 10:15
by Heezea
Hey guys, could anybody please help me with figuring out how to loop through the StoryRanges object in MS Word?

The testing code is located below. It fails at "For myStoryRange, In StoryRange" with the error message '_NewEnum' is not a method.

Code: Select all

^Space::
	oWord := ComObjActive("Word.Application")
	StoryRange := {}
	StoryRange := oWord.ActiveDocument.StoryRanges
	For myStoryRange, In StoryRange
	{
		myStoryRange.Text := "Hello"
	}
return
Also tried this, but no luck, same error.

Code: Select all

^Space::
	oWord := ComObjActive("Word.Application")
	StoryRange := {}
	StoryRange := ComObjArray(ComObjType(oWord.ActiveDocument.StoryRanges.Item(1)), 8)
	StoryRange := oWord.ActiveDocument.StoryRanges
	For myStoryRange, In StoryRange
	{
		myStoryRange.Text := "Hello"
	}
return
Thanks

Re: Loop through MS Word Object (StoryRanges) Using For Loop

Posted: 18 Jun 2016, 10:50
by Capn Odin
Untested. Try this.

Code: Select all

^Space::
	oWord := ComObjActive("Word.Application")
	StoryRange := oWord.ActiveDocument.StoryRanges
	MsgBox, % StoryRange.Count
	loop % StoryRange.Count
	{
		StoryRange.Item(A_Index - 1).Text := "Hello"
	}
return

Re: Loop through MS Word Object (StoryRanges) Using For Loop

Posted: 19 Jun 2016, 11:26
by Heezea
This doesn't work either; well it works on the very first section or when A_Index is 1 or when it's the first loop. On the second iteration it gives error message of "The requested member of the collection does not exist."

This is weird because the .Count returns however many sections there are and the loop tries to continue if I press keep script running on the error message box.

The word document I'm testing on has 5 sections - I inserted 5 "section breaks" from the Page Layout Tab in word along with some text for each.

Within the loop, I also tried:

Code: Select all

myStoryRange := ""
myStoryRange := {}
myStoryRange := oWord.ActiveDocument.StoryRanges(A_Index)
No luck there either. Just get the error message "The requested member of the collection does not exist."
Also tried:

Code: Select all

myStoryRange := myStoryRange.NextStoryRange
which just results in myStoryRange being blank after the first iteration.

Re: Loop through MS Word Object (StoryRanges) Using For Loop

Posted: 19 Jun 2016, 12:11
by kon
This post has an example of looping through storyranges: https://autohotkey.com/boards/viewtopic ... 275#p51275
If a storyrange doesn't exist it will throw an error, so you have to use try/catch/continue for those cases.