{"id":55613,"date":"2008-05-08T01:36:00","date_gmt":"2008-05-08T01:36:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/05\/08\/hey-scripting-guy-how-can-i-copy-a-portion-of-a-microsoft-word-document-to-a-new-microsoft-word-document\/"},"modified":"2008-05-08T01:36:00","modified_gmt":"2008-05-08T01:36:00","slug":"hey-scripting-guy-how-can-i-copy-a-portion-of-a-microsoft-word-document-to-a-new-microsoft-word-document","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-copy-a-portion-of-a-microsoft-word-document-to-a-new-microsoft-word-document\/","title":{"rendered":"Hey, Scripting Guy! How Can I Copy a Portion of a Microsoft Word Document to a New Microsoft Word Document?"},"content":{"rendered":"<p><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\" \/> <\/p>\n<p>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?<br \/>&#8212; CB<\/p>\n<p><img decoding=\"async\" border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\" \/><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\" \/><a href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><img decoding=\"async\" class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\" \/><\/a> <\/p>\n<p>Hey, CB. You know, it\u2019s kind of a melancholic day here at Scripting Guys world headquarters. That\u2019s because the Juanita Rebels were defeated 10-8 in the opening round of the Kingco district tournament, a loss that ended the Rebels\u2019 season and might have ended the Scripting Son\u2019s baseball career. (Although a couple of teams have asked him to play for them this summer he hasn\u2019t decided if he\u2019ll play summer ball or he\u2019ll simply prepare to head off for college in August. In addition, although the University of Idaho offers baseball as a \u201cclub\u201d sport, he\u2019s not sure if wants to play ball in college or not.)<\/p>\n<p>Needless to say, the Scripting Son was a bit wistful about seeing his baseball days potentially come to an end. But don\u2019t worry: the Scripting Dad, in his own inimitable way, managed to cheer his son up. Of course, ever since then the Scripting <i>Dad<\/i> has been a bit wistful about seeing the Scripting Son\u2019s 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\u2019s he supposed to do <i>now<\/i>?<\/p>\n<table id=\"ECD\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p class=\"lastInCell\"><b>Note<\/b>. What\u2019s that? Focus on his work and his career? Ha; that\u2019s a good one!<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>At any rate, the Scripting Guy who writes this column has spent most of the day thinking back on all the good times he\u2019s had watching the Scripting Son play ball. It\u2019s safe to say that baseball has been very good to the Scripting Family; for example, it\u2019s given them a chance to visit some of the world\u2019s 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.<\/p>\n<p>Sigh. <\/p>\n<p>Remember the two no-hitters the Scripting Son has thrown? Remember the perfect game he <i>almost<\/i> threw as a 16-year-old? With two outs in the bottom of the 7<sup>th<\/sup> 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. (\u201cI thought it was going to go foul,\u201d 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 \u2013 well, you get the idea.<\/p>\n<p>Sigh.<\/p>\n<p>As it is, the Scripting House is filled to the brim with baseball trophies earned by the Scripting Son and the Scripting Dad. What\u2019s that? How many of those trophies belong to the Scripting <i>Dad<\/i>? Well, actually \u2013 look, doesn\u2019t anyone have a <i>scripting<\/i> question, for crying out loud? Oh, we see that CB does; guess we better answer that for him:<\/p>\n<pre class=\"codeSample\">Const wdStory = 6\nConst wdExtend = 1\n\nSet objWord = CreateObject(\"Word.Application\")\nobjWord.Visible = True\n\nSet objDoc = objWord.Documents.Open(\"C:\\Scripts\\Test.doc\")\nSet objSelection = objWord.Selection\n\nobjSelection.Find.Forward = True\nobjSelection.Find.MatchWholeWord = True\nobjSelection.Find.Text = \"baseball\"\n\nDo While True\n    objSelection.Find.Execute\n    If objSelection.Find.Found Then\n        objSelection.EndOf wdStory, wdExtend\n        strText = objSelection.Copy\n        x = 1\n        Exit Do\n    Else\n        Exit Do\n    End If\nLoop\n\nIf x = 1 Then\n    Set objDoc2 = objWord.Documents.Add()\n    Set objSelection2 = objWord.Selection\n    objSelection2.Paste\nEnd If\n<\/pre>\n<p>Can we figure out how this script works? Listen, if you set your mind to it you can do anything, right?<\/p>\n<table id=\"ECE\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p><b>Note<\/b>. 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, \u201cThere\u2019s no way they\u2019re to going to rob me <i>this<\/i> time,\u201d and promptly belted the ball over the centerfield fence.<\/p>\n<p>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 <i>scripting<\/i> questions?!?<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Speaking of scripts and scripting, our script starts off by defining a pair of constants \u2013 wdStory and wdExtend \u2013 that we\u2019ll use to help us select the appropriate text in the document. After defining the constants we create an instance of the <b>Word.Application<\/b> object and then set the <b>Visible<\/b> property to True; that gives us a running instance of Microsoft Word that we can see on screen. We use the <b>Open<\/b> method to open the file C:\\Scripts\\Test.doc, then use this line of code to create an instance of Word\u2019s <b>Selection<\/b> object, positioned (by default) at the beginning of the document:<\/p>\n<pre class=\"codeSample\">Set objSelection = objWord.Selection\n<\/pre>\n<p>Once we have the Selection object in hand we define three properties of the <b>Find<\/b> object (a child object of the Selection object):<\/p>\n<pre class=\"codeSample\">objSelection.Find.Forward = True\nobjSelection.Find.MatchWholeWord = True\nobjSelection.Find.Text = \"baseball\"\n<\/pre>\n<p>Setting the <b>Forward<\/b> property to True tells the script that we want to search the document from top to bottom. Setting <b>MatchWholeWord<\/b> to True tells the script that we want to match whole words only. (In other words, if we were searching for <i>cat<\/i> the script won\u2019t match <i>category<\/i>, <i>catalog<\/i>, or even <i>scatterbrained<\/i>.) Finally, we set the <b>Text<\/b> property to the text value we want to search for: baseball.<\/p>\n<p>Sigh.<\/p>\n<p>At this point we\u2019re 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 <b>Execute<\/b> method, which tells the script to search for the first instance of the target text:<\/p>\n<pre class=\"codeSample\">objSelection.Find.Execute\n<\/pre>\n<p>After calling the Execute method we check to see if the Find object\u2019s <b>Found<\/b> property is True. If it\u2019s not, that simply means we didn\u2019t find the word <i>baseball<\/i> anywhere in the document; consequently, we call the <b>Exit Do<\/b> statement and drop out of the loop.<\/p>\n<p>But what if we <i>did<\/i> find the target text? In that case, we run this block of code:<\/p>\n<pre class=\"codeSample\">objSelection.EndOf wdStory, wdExtend\nstrText = objSelection.Copy\nx = 1\nExit Do\n<\/pre>\n<p>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\u2019re searching for the word <i>baseball<\/i>; if we find that term the first such instance of the word <i>baseball<\/i> will be selected. That\u2019s nice, but it\u2019s not quite what we need: we need to select not only the word <i>baseball<\/i> but all the rest of the text that follows the target word. <\/p>\n<p>A problem? Nah; all we have to do is call the <b>EndOf<\/b> method, followed by two parameters:<\/p>\n<table border=\"0\" cellSpacing=\"0\" cellPadding=\"0\">\n<tbody>\n<tr>\n<td class=\"listBullet\" vAlign=\"top\">\u2022<\/td>\n<td class=\"listItem\">\n<p>The constant <b>wdStory<\/b>, 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.<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td class=\"listBullet\" vAlign=\"top\">\u2022<\/td>\n<td class=\"listItem\">\n<p>The constant <b>wdExtend<\/b>, which tells the script that we want to extend the selection rather than move the selection.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The net effect? Everything in the document, from the first instance of the word <i>baseball<\/i> on, will be selected.<\/p>\n<table id=\"E2H\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p class=\"lastInCell\"><b>Note<\/b>. See? Not a problem at all. A <i>real<\/i> 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\u2019 Mets rallied to score 10 runs and win the game.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Once that\u2019s done we use the <b>Copy<\/b> 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.<\/p>\n<p>So <i>now<\/i> what are we going to do? Good question. There\u2019s obviously yard work to do, and we need to repaint the front of the house. And, of course, we should probably \u2013 oh, wait: you mean with the script, don\u2019t you? Well, once we exit the loop we check to see if x is equal to 1:<\/p>\n<pre class=\"codeSample\">If x = 1 Then\n<\/pre>\n<p>If x is not equal to 1 that just means that we didn\u2019t find the word <i>baseball<\/i> anywhere in the document; consequently the script simply comes to an end. If x <i>is<\/i> equal to 1, however, we then execute these three lines of code:<\/p>\n<pre class=\"codeSample\">Set objDoc2 = objWord.Documents.Add()\nSet objSelection2 = objWord.Selection\nobjSelection2.Paste\n<\/pre>\n<p>As you can see, there\u2019s not much going on in this block of code. In line 1 we call the <b>Add<\/b> 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 <b>Paste<\/b> method to paste the copied text into the new document. What will that do for us? Give it a try and see for yourself.<\/p>\n<p>That should do it, CB. If it doesn\u2019t just let us know; after all, it looks like we have all sorts of time for answering scripting-related questions.<\/p>\n<p>Sigh.<\/p>\n<table id=\"EIBAC\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<thead><\/thead>\n<tbody>\n<tr class=\"record\" vAlign=\"top\">\n<td>\n<p class=\"lastInCell\"><b>Note<\/b>. And no, those are definitely <i>not<\/i> tears welling up in the Scripting Dad\u2019s eyes; apparently the Scripting Editor is peeling onions in her office again. But don\u2019t worry; we\u2019ll go have a talk with her.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n","protected":false},"excerpt":{"rendered":"<p>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?&#8212; CB Hey, CB. You know, it\u2019s kind of a melancholic day here at Scripting Guys world headquarters. That\u2019s because the Juanita [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[84,49,3,5],"class_list":["post-55613","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-microsoft-word","tag-office","tag-scripting-guy","tag-vbscript"],"acf":[],"blog_post_summary":"<p>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?&#8212; CB Hey, CB. You know, it\u2019s kind of a melancholic day here at Scripting Guys world headquarters. That\u2019s because the Juanita [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55613","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=55613"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/55613\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=55613"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=55613"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=55613"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}