{"id":64823,"date":"2007-05-21T23:08:00","date_gmt":"2007-05-21T23:08:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2007\/05\/21\/how-can-i-add-the-contents-of-a-group-of-text-files-to-an-access-database\/"},"modified":"2007-05-21T23:08:00","modified_gmt":"2007-05-21T23:08:00","slug":"how-can-i-add-the-contents-of-a-group-of-text-files-to-an-access-database","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-add-the-contents-of-a-group-of-text-files-to-an-access-database\/","title":{"rendered":"How Can I Add the Contents of a Group of Text Files to an Access Database?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"> \n<P>Hey, Scripting Guy! I have a folder that has hundreds of text files in it. I\u2019d like to take each of those files and add the contents (as a memo field) to an Access database. How can I do that?<BR><BR>&#8212; KB<\/P><IMG height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" height=\"288\" alt=\"Script Center\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" align=\"right\" border=\"0\"><\/A> \n<P>Hey, KB. You know, a few years ago the Scripting Guy who writes this column gave a talk at a conference in Orlando. (And yes, he\u2019ll be back in Orlando June 4-8 for <A href=\"http:\/\/www.microsoft.com\/events\/teched2007\/default.mspx\" target=\"_blank\"><B>TechEd 2007<\/B><\/A> \u2026 assuming, of course, that the city\u2019s restraining order really <I>has<\/I> expired.) Because it\u2019s no fun to go to Orlando by yourself, he did some negotiating, and ended up taking along his then 10-year-old son and one of his son\u2019s friends. (Yes, he <I>did<\/I> take the two boys out of school for a week. But, in his view, at least, education is highly-overrated: after all, the Scripting Guy who writes this column has a master\u2019s degree, and look where that got <I>him<\/I>.)<\/P>\n<P>As it turned out, the trio happened to arrive in Florida during the closest thing Orlando has to an off-season. One evening they were at Disney World and, about an hour or so before the park was due to close, rode <A href=\"http:\/\/disneyworld.disney.go.com\/wdw\/parks\/attractionDetail?id=SplashMountainAttractionPage\" target=\"_blank\"><B>Splash Mountain<\/B><\/A>. When the ride was over they realized that there was no one waiting in line; naturally, they walked around, got back on the ride, and rode again. When they got off, they noticed the same thing: pretty much everyone had already gone home for the day. And so they continued riding Splash Mountain, over and over again, until the folks at Disney finally told them it was time to go.<\/P>\n<P>The moral of the story? There are some things that you just never get tired of; you\u2019re willing to do them over and over and over again. For some people, that means riding rides at an amusement park; for most of us, though (including those who breathlessly followed the <I>Hey, Scripting Guy!<\/I> columns of <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/may07\/hey0517.mspx\"><B>May 17<\/B><\/A> and <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/may07\/hey0518.mspx\"><B>May 18<\/B><\/A>) that means writing scripts that work with text files. In particular, that means writing scripts that work with all the text files in a folder:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst adLockOptimistic = 3<\/p>\n<p>Set objConnection = CreateObject(&#8220;ADODB.Connection&#8221;)\nSet objRecordSet = CreateObject(&#8220;ADODB.Recordset&#8221;)<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)<\/p>\n<p>objConnection.Open _\n    &#8220;Provider = Microsoft.Jet.OLEDB.4.0; &#8221; &amp; _\n        &#8220;Data Source = C:\\Scripts\\Test.mdb&#8221; <\/p>\n<p>objRecordSet.Open &#8220;SELECT * FROM TextFiles&#8221; , _\n    objConnection, adOpenStatic, adLockOptimistic<\/p>\n<p>strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)<\/p>\n<p>Set colFileList = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Archive&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)<\/p>\n<p>For Each objFile In colFileList\n    Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading)\n    strContents = objTextFile.ReadAll\n    objTextFile.Close<\/p>\n<p>    objRecordSet.AddNew\n    objRecordSet(&#8220;FileName&#8221;) = objFile.Name\n    objRecordSet(&#8220;FileContents&#8221;) = strContents\n    objRecordSet.Update\nNext<\/p>\n<p>objRecordSet.Close\nobjConnection.Close\n<\/PRE>\n<P>We\u2019ll give everyone a moment to catch their breath and then we\u2019ll see if we can figure out how this script works. We start out by defining a pair of constants, ForReading and adLockOptimistic. ForReading is the constant we\u2019ll use to specify the file mode (for reading) when we open all the text files; adLockOptimistic is the constant we\u2019ll use to indicate how we want to lock our recordset when working with the database. (Optimistic locking simply means that we\u2019ll only lock the recordset when calling the Update method.) After defining the two constants we then create a pair of database objects: <B>ADODB.Connection<\/B> and <B>ADODB.Recordset<\/B>. From there we go ahead and create an instance of the <B>Scripting.FileSystemObject<\/B>, the object used to read text files. We won\u2019t need this object right away, but this seemed as good a time as any to create it. (Fortunately it won\u2019t go stale if we don\u2019t use it immediately.)<\/P>\n<TABLE class=\"dataTable\" id=\"EQE\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P class=\"lastInCell\"><B>Note<\/B>. Before you ask, no, we\u2019re not going to explain much about databases and database objects in today\u2019s column. If you could use a refresher course on working with databases you might take a look at our Scripting Guys webcast <A href=\"http:\/\/go.microsoft.com\/fwlink\/?LinkId=22089\" target=\"_blank\"><B>Database Scripting for System Administrators<\/B><\/A>.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>Unlike the FileSystemObject, we\u2019re going to immediately put our two database objects to use. First, we use the Connection object to connect us to the database C:\\Scripts\\Test.mdb:<\/P><PRE class=\"codeSample\">objConnection.Open _\n    &#8220;Provider = Microsoft.Jet.OLEDB.4.0; &#8221; &amp; _\n        &#8220;Data Source = C:\\Scripts\\Test.mdb&#8221;\n<\/PRE>\n<P>Once we\u2019ve made that connection we use the Recordset object to retrieve a collection of all the records found in the <I>TextFiles<\/I> table:<\/P><PRE class=\"codeSample\">objRecordSet.Open &#8220;SELECT * FROM TextFiles&#8221; , _\n    objConnection, adOpenStatic, adLockOptimistic\n<\/PRE>\n<P>As you\u2019ve probably already figured out, TextFiles is the name of the table where we plan to add the new records. For today\u2019s script we\u2019re assuming that the TextFiles table already exists. However, you could modify this script so that it first creates the new table and then adds records to this brand-new table. For more information on programmatically creating database tables, see the <A href=\"http:\/\/go.microsoft.com\/fwlink\/?LinkId=22089\" target=\"_blank\"><B>webcast<\/B><\/A> we mentioned a few minutes ago.<\/P>\n<P>Now that we have a database connection our next task is to grab hold of all the text files. To do that we first use this block of code to connect to the WMI service on the local computer:<\/P><PRE class=\"codeSample\">strComputer = &#8220;.&#8221;<\/p>\n<p>Set objWMIService = GetObject(&#8220;winmgmts:\\\\&#8221; &amp; strComputer &amp; &#8220;\\root\\cimv2&#8221;)\n<\/PRE>\n<P>And yes, due to limitations with the FileSystemObject, this script is designed to work only on the local computer. That doesn\u2019t mean that you can\u2019t ever, under any circumstances, read text files stored on a remote machine; it just means you\u2019ll have to make some modifications to the script before you can do so. What <I>kind<\/I> of modifications? Why, the ones we discuss in <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/qanda\/oct05\/hey1021.mspx\"><B>this other column<\/B><\/A>, of course.<\/P>\n<P>You know, now that you mention it, there <I>are<\/I> a lot of links and see-alsos in today\u2019s column, aren\u2019t there? That couldn\u2019t possibly mean that the Scripting Guy who writes this column is getting lazy?<\/P>\n<P>Nah.<\/P>\n<P>OK; what\u2019s next? Well, next we use this bit of code to retrieve a collection of all the files found in the folder C:\\Archive:<\/P><PRE class=\"codeSample\">Set colFileList = objWMIService.ExecQuery _\n    (&#8220;ASSOCIATORS OF {Win32_Directory.Name=&#8217;C:\\Archive&#8217;} Where &#8221; _\n        &amp; &#8220;ResultClass = CIM_DataFile&#8221;)\n<\/PRE>\n<P>At this point, and at long last, we\u2019re finally ready to roll: we\u2019re ready to start reading text files and to start adding the contents of those files to our database.<\/P>\n<P>Speaking of which, we should note that we\u2019re using a very simple database table, one that includes just two fields:<\/P>\n<TABLE class=\"\" cellSpacing=\"0\" cellPadding=\"0\" border=\"0\">\n<TBODY>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>FileName<\/B>, a text field where we\u2019ll store the path of the file we opened.<\/P><\/TD><\/TR>\n<TR>\n<TD class=\"listBullet\" vAlign=\"top\">\u2022<\/TD>\n<TD class=\"listItem\">\n<P><B>FileContents<\/B>, a memo field where we\u2019ll store the contents of the file we opened.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<P>Just something we thought you should know.<\/P>\n<P>OK, <I>now<\/I> it\u2019s time to start adding records to the database. Thanks to our WMI query we have a collection of all the files in the folder C:\\Archive, a collection we stashed away in a variable named colFileList. With that in mind we next set up a For Each loop to loop through each and every one of these files:<\/P><PRE class=\"codeSample\">For Each objFile In colFileList\n<\/PRE>\n<P>The first thing we do inside this loop is use the <B>OpenTextFile<\/B> method to open file No. 1 in the collection:<\/P><PRE class=\"codeSample\">Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading)\n<\/PRE>\n<P>Notice that we pass OpenTextFile two parameters: <B>objFile.Name<\/B>, a WMI property that returns the complete path to the file; and the constant ForReading (because we want to read from this file). We then use the <B>ReadAll<\/B> method to read the contents of the file into a variable named strContents:<\/P><PRE class=\"codeSample\">strContents = objTextFile.ReadAll\n<\/PRE>\n<P>And once we have the contents stashed safely away in memory we call the <B>Close<\/B> method and close the file.<\/P>\n<P>That brings us to the following block of code:<\/P><PRE class=\"codeSample\">objRecordSet.AddNew\nobjRecordSet(&#8220;FileName&#8221;) = objFile.Name\nobjRecordSet(&#8220;FileContents&#8221;) = strContents\nobjRecordSet.Update\n<\/PRE>\n<P>This \u2013 in case you were wondering \u2013 is the exciting, thrill-ride portion of today\u2019s column. (Yes, we know: today\u2019s entire column <I>does<\/I> seem like a thrill ride, doesn\u2019t? But this is the <I>really<\/I> good part.) As you can see, the first thing we do here is call the Recordset object\u2019s <B>AddNew<\/B> method; that\u2019s going to add a new, blank record to our database table. We then use these two lines of code to assign the file path (Name) to the FileName field, and the contents of the file (strContents) to the FileContents field:<\/P><PRE class=\"codeSample\">objRecordSet(&#8220;FileName&#8221;) = objFile.Name\nobjRecordSet(&#8220;FileContents&#8221;) = strContents\n<\/PRE>\n<P>And then we call the <B>Update<\/B> method to actually write this new record to the database. Don\u2019t forget to call this method; if you do forget, none of your changes (that is, none of your new records) will be added to the database.<\/P>\n<P>Which, of course, would sort of defeat the purpose of the script.<\/P>\n<P>After calling the Update method for file No. 1 we loop around and repeat the process with the next file in the collection (that is, the next file in the folder). Sooner or later we\u2019ll have opened and read all the files in the collection; when that happens we automatically exit the For Each loop, then use these two lines of code to sever our connection to the database:<\/P><PRE class=\"codeSample\">objRecordSet.Close\nobjConnection.Close\n<\/PRE>\n<P>At that point our script, like all good things, comes to an end.<\/P>\n<P>We hope that helps, KB. We also hope that if you (or anyone else) happens to be in <A href=\"http:\/\/www.microsoft.com\/events\/teched2007\/default.mspx\"><B>Orlando June 4-8<\/B><\/A> that you\u2019ll stop by the Scripting Guys booth and say hi. And don\u2019t worry: you won\u2019t be intruding on any family time. This time around the Scripting Son and his friend won\u2019t be going; instead, the Scripting Guy who writes this column has the \u2026 privilege \u2026 of attending the conference alongside Scripting Guy Jean Ross. They say that it\u2019s impossible to go to Orlando and <I>not<\/I> have a good time. But, then again, they never met Scripting Guy Jean Ross, did they?<\/P>\n<TABLE class=\"dataTable\" id=\"ESAAC\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P><B>Note<\/B>. No, hey, we\u2019re just kidding; Jean\u2019s is the <I>perfect<\/I> person to go to Orlando with. Well, other than the fact that she won\u2019t go on scary amusement park rides like <A href=\"http:\/\/www.universalorlando.com\/ioa_attr_fearfall.html\" target=\"_blank\"><B>Dr. Doom\u2019s Fear Fall<\/B><\/A>. And the fact that she won\u2019t go to a water park like <A href=\"http:\/\/www.wetnwildorlando.com\/Main\/Main.asp\" target=\"_blank\"><B>Wet \u2019n Wild<\/B><\/A>. And the fact that she won\u2019t \u2013 well you get the idea. If you <I>do<\/I> attend TechEd and you <I>do<\/I> swing by the Scripting Guys booth, could you wake Scripting Guy Greg Stemp up for us? Thanks.<\/P>\n<P><B>Ed<\/B><B>itor\u2019s Note:<\/B> In other words, Scripting Guy Jean Ross won\u2019t go on any rides that might make her throw up, or go anywhere where she\u2019d have to see her coworkers in bathing suits (which might also fall into that first category). And Scripting Guy Greg Stemp will be riding one ride over and over again, then sleeping through TechEd. You probably can\u2019t wait to meet these people, can you?<\/P><\/TD><\/TR><\/TBODY><\/TABLE><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I have a folder that has hundreds of text files in it. I\u2019d like to take each of those files and add the contents (as a memo field) to an Access database. How can I do that?&#8212; KB Hey, KB. You know, a few years ago the Scripting Guy who writes this [&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":[54,49,3,4,14,5],"class_list":["post-64823","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-microsoft-access","tag-office","tag-scripting-guy","tag-scripting-techniques","tag-text-files","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I have a folder that has hundreds of text files in it. I\u2019d like to take each of those files and add the contents (as a memo field) to an Access database. How can I do that?&#8212; KB Hey, KB. You know, a few years ago the Scripting Guy who writes this [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64823","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=64823"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/64823\/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=64823"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=64823"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=64823"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}