Hey, Scripting Guy! How can I find some text in a Microsoft Word document, copy the rest of the document from that point on, then paste the copied text into a brand-new Word file?
Hey, CB. You know, it’s kind of a melancholic day here at Scripting Guys world headquarters. That’s because the Juanita Rebels were defeated 10-8 in the opening round of the Kingco district tournament, a loss that ended the Rebels’ season and might have ended the Scripting Son’s baseball career. (Although a couple of teams have asked him to play for them this summer he hasn’t decided if he’ll play summer ball or he’ll simply prepare to head off for college in August. In addition, although the University of Idaho offers baseball as a “club” sport, he’s not sure if wants to play ball in college or not.)
Needless to say, the Scripting Son was a bit wistful about seeing his baseball days potentially come to an end. But don’t worry: the Scripting Dad, in his own inimitable way, managed to cheer his son up. Of course, ever since then the Scripting Dad has been a bit wistful about seeing the Scripting Son’s baseball days potentially come to an end; after all, for the past 12 years pretty much the only thing the Scripting Guy who writes this column has done is watch his son play baseball. What’s he supposed to do now?
Note. What’s that? Focus on his work and his career? Ha; that’s a good one!
At any rate, the Scripting Guy who writes this column has spent most of the day thinking back on all the good times he’s had watching the Scripting Son play ball. It’s safe to say that baseball has been very good to the Scripting Family; for example, it’s given them a chance to visit some of the world’s great cities. Tokyo, Japan? Been there and done that; a few years ago the Scripting Son played on an all-star team that toured Tokyo. Vancouver, Canada? Of course; the Scripting Son played there as a 12-year-old. Sequim, WA? Walla Walla, WA? Check and double-check.
Remember the two no-hitters the Scripting Son has thrown? Remember the perfect game he almost threw as a 16-year-old? With two outs in the bottom of the 7th the batter dribbled a ground ball down the third base line. The third baseman, instead of fielding the ball, simply stood and watched it roll past him, giving the opposing team their only base runner of the game. (“I thought it was going to go foul,” the third baseman explained later.) Remember the game in Woodinville, when the Scripting Son came in as a relief pitcher and struck out 11 in 5 innings? He also had 5 hits in that game, which was good, although not as good as the 4 doubles and 2 singles he had in a junior high game. (Was he grounded for getting those 2 singles rather than 2 more doubles? You bet he was.) And remember – well, you get the idea.
As it is, the Scripting House is filled to the brim with baseball trophies earned by the Scripting Son and the Scripting Dad. What’s that? How many of those trophies belong to the Scripting Dad? Well, actually – look, doesn’t anyone have a scripting question, for crying out loud? Oh, we see that CB does; guess we better answer that for him:
Const wdStory = 6 Const wdExtend = 1 Set objWord = CreateObject("Word.Application") objWord.Visible = True Set objDoc = objWord.Documents.Open("C:\Scripts\Test.doc") Set objSelection = objWord.Selection objSelection.Find.Forward = True objSelection.Find.MatchWholeWord = True objSelection.Find.Text = "baseball" Do While True objSelection.Find.Execute If objSelection.Find.Found Then objSelection.EndOf wdStory, wdExtend strText = objSelection.Copy x = 1 Exit Do Else Exit Do End If Loop If x = 1 Then Set objDoc2 = objWord.Documents.Add() Set objSelection2 = objWord.Selection objSelection2.Paste End If
Can we figure out how this script works? Listen, if you set your mind to it you can do anything, right?
Note. Which reminds us of the game in which the Scripting Son, in his first two at-bats, got robbed of base hits. Before his third at-bat he muttered, “There’s no way they’re to going to rob me this time,” and promptly belted the ball over the centerfield fence.
So was that single home run, by itself, more home runs than the Scripting Dad ever hit? Hey, what did we say about asking only scripting questions?!?
Speaking of scripts and scripting, our script starts off by defining a pair of constants – wdStory and wdExtend – that we’ll use to help us select the appropriate text in the document. After defining the constants we create an instance of the Word.Application object and then set the Visible property to True; that gives us a running instance of Microsoft Word that we can see on screen. We use the Open method to open the file C:\Scripts\Test.doc, then use this line of code to create an instance of Word’s Selection object, positioned (by default) at the beginning of the document:
Set objSelection = objWord.Selection
Once we have the Selection object in hand we define three properties of the Find object (a child object of the Selection object):
objSelection.Find.Forward = True objSelection.Find.MatchWholeWord = True objSelection.Find.Text = "baseball"
Setting the Forward property to True tells the script that we want to search the document from top to bottom. Setting MatchWholeWord to True tells the script that we want to match whole words only. (In other words, if we were searching for cat the script won’t match category, catalog, or even scatterbrained.) Finally, we set the Text property to the text value we want to search for: baseball.
At this point we’re ready to start searching for the target text. To do that we first set up a Do While loop designed to run as long as True is equal to True. Inside that loop we then call the Execute method, which tells the script to search for the first instance of the target text:
After calling the Execute method we check to see if the Find object’s Found property is True. If it’s not, that simply means we didn’t find the word baseball anywhere in the document; consequently, we call the Exit Do statement and drop out of the loop.
But what if we did find the target text? In that case, we run this block of code:
objSelection.EndOf wdStory, wdExtend strText = objSelection.Copy x = 1 Exit Do
Suppose you search for text in a Microsoft Word document and your script manages to find that text. In that case, the search term automatically becomes selected. In other words, suppose we’re searching for the word baseball; if we find that term the first such instance of the word baseball will be selected. That’s nice, but it’s not quite what we need: we need to select not only the word baseball but all the rest of the text that follows the target word.
A problem? Nah; all we have to do is call the EndOf method, followed by two parameters:
The constant wdStory, which tells the script that we want to select the rest of the story (i.e., the rest of the document), as opposed to, say, the rest of the sentence or paragraph.
The constant wdExtend, which tells the script that we want to extend the selection rather than move the selection.
The net effect? Everything in the document, from the first instance of the word baseball on, will be selected.
Note. See? Not a problem at all. A real problem occurred when the Scripting Son was 10 and his team entered the bottom of the sixth inning (the last inning in Little League) trailing by 9 runs. Remarkably enough, those amazin’ Mets rallied to score 10 runs and win the game.
Once that’s done we use the Copy method to copy the selected text to the Clipboard. We set the value of a variable named x to 1 (more on that in just a second), then call the Exit Do statement to exit our Do Until loop.
So now what are we going to do? Good question. There’s obviously yard work to do, and we need to repaint the front of the house. And, of course, we should probably – oh, wait: you mean with the script, don’t you? Well, once we exit the loop we check to see if x is equal to 1:
If x = 1 Then
If x is not equal to 1 that just means that we didn’t find the word baseball anywhere in the document; consequently the script simply comes to an end. If x is equal to 1, however, we then execute these three lines of code:
Set objDoc2 = objWord.Documents.Add() Set objSelection2 = objWord.Selection objSelection2.Paste
As you can see, there’s not much going on in this block of code. In line 1 we call the Add method to create a new, blank Word document. In line 2, we create a new instance of the Word Selection object, this one tied to our new, blank document. Last, but surely not least, we call the Paste method to paste the copied text into the new document. What will that do for us? Give it a try and see for yourself.
That should do it, CB. If it doesn’t just let us know; after all, it looks like we have all sorts of time for answering scripting-related questions.
Note. And no, those are definitely not tears welling up in the Scripting Dad’s eyes; apparently the Scripting Editor is peeling onions in her office again. But don’t worry; we’ll go have a talk with her.