Question

Word-VBA-read file & write to properties

Asked by: rdmjrb

Hello,

I have a project that needs to do the following once a quarter and will involve 200+ documents each time so I'm looking for a semi-portable solution.
1. Set the document properties in a standardized fashion.

Each document follows a strict template so I will be able to open the file, "scrape" the data I need, re-format it for the properties, set the new properties, save and close the file.

I propose the following using VBA code:
(simplified for brevity)
1. open the file
2. do a search in the file for a person's name (Instr, Mid, etc.) (always located in the same place)
3. re-format the name (Last, First M.) set that name into the title property
4. save file
5. close file

I'm looking for specific code and am open to a whole new proccess, this is what i've come up with so far....

cheers!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2001-07-05 at 08:54:45ID20146327
Tags

vba

,

file

,

read

,

word

Topic

Microsoft Office Suite

Participating Experts
1
Points
100
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Multiple criteria with InStr function?
    Please have a look at the multiple criteria that I am testing for to return the word "Green". Currently I am checking for 16 different words, but I need to check for about 40 possible words. Is there a better way for me to do this exercise? Should I move everythi...
  2. VBA Word Pasting Question
    Is there a way using VBA to extract say Lines 1-200,000 in a Word document and paste it into Excel. Thanks.
  3. VBA InStr Malfunction
    A seemingly simple use of InStr always returns the value 0. Here's the details... Dim posStr As Integer Dim srchStr As String .... posStr = InStr(1, UCase(txt), UCase(srchStr)) .... MsgBox "[1] " + srchStr + " - " + txt + Ch...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: GudarePosted on 2001-07-05 at 12:10:37ID: 6256927

If you would clarify, are you looking for the code that would do your proposed method, or a new method?

-Craig

 

by: rdmjrbPosted on 2001-07-05 at 13:57:49ID: 6257311

Gudare/Craig:

>>am open to a whole new proccess

If you suggest an easier solution, I would be open to it, as i said, the solution I posted was my best guess.

Regards, rdmjrb

 

by: GudarePosted on 2001-07-05 at 14:17:57ID: 6257397

Well, the following code will get you through opening the files for usage, but without a file or specific examples of your datascrape/wanted results once you've got it open, I'll show you the part for dealing with the file itself:

Sub OpenCloseFiles()

    ' Load all files wanted to be used in macro into one folder with
    ' no other files inside that folder. Modify FILE_PATH constant
    ' to read correct path.
   
    Dim strFileName As String
    Dim docOpenedFile As Document
   
    Const FILE_PATH As String = "C:\My Documents\"
   
    strFileName = Dir(FILE_PATH)
   
    Do Until strFileName = ""
        If Not ((strFileName = ".") Or (strFileName = "..")) Then
            If Not GetAttr(FILE_PATH & strFileName) = vbDirectory Then
                docOpenedFile = Application.Documents.Open(FILE_PATH & strFileName)
                ' Perform datascrape and operations here.
                docOpenedFile.Close
            End If
        End If
        strFileName = Dir()
    Loop

End Sub

-Craig

 

by: rdmjrbPosted on 2001-07-05 at 14:55:42ID: 6257508

Craig:

The datascrape would be something like this:

Each document contains 4 pieces of information:
1. Name (First Middle/M. Last) - which I would convert to (Last, First Middle/M.)
2. Group
3. Title
4. FocusDescription

I will place the data into 2 properties:
1. Title (Name - Group - OfficeLocation - (Title))
2. Comments (FocusDescription)

Since I do not have the OfficeLocation within the document each location will have its own function with the OfficeLocation hardcoded.

Let me know if you need further information.

Regards, rdmjrb

 

by: GudarePosted on 2001-07-05 at 15:11:44ID: 6257552

Definately, I'd need to see a sample document, basically, so I know how to get at the data, ie: Field bookmarks, which paragraph number, so on, so forth. Right now, I'm basically blind as to where the data is within a word document. If you'd like, email me a sample at craigt.farrell@pchelps.com, and I'll be happy to review it. Also, the properties you're discussing, where do you intend to save these, into the General Properties of the entire document as custom properties or if not that, please be more specific as to your intended storage.

 

by: rdmjrbPosted on 2001-07-05 at 15:27:46ID: 6257590

Craig:

1. check your email for the document.
2. i will save them into the regular properties as said in the previous post (Title, Comments)

Regards, rdmjrb

 

by: GudarePosted on 2001-07-05 at 16:12:45ID: 6257740

Quick and dirty.

Option Explicit

Sub OpenCloseFiles()
On Error GoTo Err_OpenCloseFiles

   ' Load all files wanted to be used in macro into one folder with
   ' no other files inside that folder. Modify FILE_PATH constant
   ' to read correct path.
   
   Dim strFileName As String
   Dim docOpenedFile As Document
   
   Const FILE_PATH As String = "C:\My Documents\"
   
   strFileName = Dir(FILE_PATH)
   
   Do Until strFileName = ""
       If Not ((strFileName = ".") Or (strFileName = "..")) Then
           If Not GetAttr(FILE_PATH & strFileName) = vbDirectory Then
               docOpenedFile = Application.Documents.Open(FILE_PATH & strFileName)
               DataScrape docOpenedFile
               docOpenedFile.Close
           End If
       End If
       strFileName = Dir()
   Loop

Exit_OpenCloseFiles:
    On Error Resume Next
    docOpenedFile.Close
    Set docOpenedFile = Nothing
    Exit Sub

Err_OpenCloseFiles:
    Select Case Err.Number
    Case Else
        MsgBox Err.Number & ": " & Err.Description, vbCritical, "OpenCloseFiles"
        Resume Exit_OpenCloseFiles
    End Select

End Sub

Sub DataScrape(ByRef doc As Document)
   
    Dim strTitle As String
    Dim strComment As String
    Dim strTemp As String
   
    Const LOCATION As String = "Enter Location Here"
   
    ' Get Name
    ' Remove the paragraph mark at end of paragraph
    strTemp = Left(doc.Paragraphs(4).Range.Text, Len(doc.Paragraphs(4).Range.Text) - 1)
    strTitle = Right(strTemp, Len(strTemp) - InStr(InStr(strTemp, " ") + 1, strTemp, " ")) & ", " & Left(strTemp, InStr(InStr(strTemp, " ") + 1, strTemp, " ") - 1)
   
    ' Get Group
    strTemp = Left(doc.Paragraphs(8).Range.Text, Len(doc.Paragraphs(8).Range.Text) - 1)
    strTitle = strTitle & " - " & strTemp
   
    ' Get Office Location
    strTitle = strTitle & LOCATION
   
    ' Get Title
    strTemp = Left(doc.Paragraphs(5).Range.Text, Len(doc.Paragraphs(5).Range.Text) - 1)
    strTitle = strTitle & " - (" & strTemp & ")"
   
    strComment = Left(doc.Paragraphs(11).Range.Text, Len(doc.Paragraphs(11).Range.Text) - 1)

    doc.BuiltInDocumentProperties("Title") = strTitle
    doc.BuiltInDocumentProperties("Comments") = strComment

End Sub

 

by: rdmjrbPosted on 2001-07-06 at 07:32:52ID: 6259913

craig:

getting invalid use ofproperty here:
>>docOpenedFile = Application.Documents.Open(FILE_PATH & strFileName)

also, these files are within the same directory, example, all of houston in the houston dir, sanFran in sanFran, etc.

thanks, ron

 

by: GudarePosted on 2001-07-06 at 11:18:51ID: 6260156

My bad, line of code should read: set docOpened File = ...

 

by: rdmjrbPosted on 2001-07-06 at 13:28:27ID: 6260537

Craig:

The code is running fine now, but it only sets the Title property=<<IMAGE01>>


The rest of the Title or Comments properties are not being set.

Also I see the searches are hardcoded:
' Get Group
   strTemp = Left(doc.Paragraphs(8).Range.Text, Len(doc.Paragraphs(8).Range.Text) - 1)

And so on, but these values will continually be different as some Group names are 6 chars and others are 23.

If you show an example of how to serach for, say a colon, then begin the search at that point and stop when there is a chr(13) or chr(10), this would encompass all groups.

Example:
Group Name:
Information Technology Group chr(13) & chr(10)
<<New Line Here>>

Once I see this logic I can code for the rest of the searchs in this manner.
   

 

by: GudarePosted on 2001-07-06 at 13:36:37ID: 6260563

Actually, it's hardcoded to look for the paragraph number, not the length of text, it doesn't care about the length of text, only removing the char(13) at the end, therefore you shouldn't need to search as long as they keep the same # of paragraphs. As to pulling the wrong information, this worked perfectly against the test file you sent me, so I don't know why you're seeing image1. *shrugs* Sorry, according to what you gave me, the scrape works correctly. Are you running it against the same file?  If so, what version of Word, we might be in diff versions?

 

by: rdmjrbPosted on 2001-07-06 at 13:57:49ID: 6260629

Craig:

Ok I dig. It's working fine for the test doc,but not for a realone. Check email, getting this error:

5:Invalid procedure or call.

How can I use the code in a directory that contains multiple files?

 

by: GudarePosted on 2001-07-06 at 14:21:06ID: 6260689

Two problems were occuring:
First, Paragraph 5, not 4, for the user's name, was failing on blank line, had to change both halves of the equation.

I was using a nested instr that needed the middle initial to exist or it would fail, not a big worry. It now contains an if statement to deal with the issue.

This code if you run: OpenCloseFiles will loop through *every* file in a folder, so it's already setup to do that, that's what the dir() is all about.

I modified this code slightly to deal with the save over message, so you should be good to go. Copy/paste this in and give it a whirl.

Option Explicit

Sub OpenCloseFiles()
On Error GoTo Err_OpenCloseFiles

  ' Load all files wanted to be used in macro into one folder with
  ' no other files inside that folder. Modify FILE_PATH constant
  ' to read correct path.
 
  Dim strFileName As String
  Dim docOpenedFile As Document
 
  Const FILE_PATH As String = "C:\data\client\rdm\"
 
  strFileName = Dir(FILE_PATH)
 
  Do Until strFileName = ""
      If Not ((strFileName = ".") Or (strFileName = "..")) Then
          If Not GetAttr(FILE_PATH & strFileName) = vbDirectory Then
              Set docOpenedFile = Application.Documents.Open(FILE_PATH & strFileName)
              DataScrape docOpenedFile
              docOpenedFile.Save
              docOpenedFile.Close
          End If
      End If
      strFileName = Dir()
  Loop

Exit_OpenCloseFiles:
   On Error Resume Next
   docOpenedFile.Close
   Set docOpenedFile = Nothing
   Exit Sub

Err_OpenCloseFiles:
   Select Case Err.Number
   Case Else
       MsgBox Err.Number & ": " & Err.Description, vbCritical, "OpenCloseFiles"
       Resume Exit_OpenCloseFiles
   End Select

End Sub

Sub DataScrape(ByRef doc As Document)
   
   Dim strTitle As String
   Dim strComment As String
   Dim strTemp As String
   Dim LastNamePosition As Integer
   
   Const LOCATION As String = "Toronto"
   
   ' Get Name
   ' Remove the paragraph mark at end of paragraph
   strTemp = Left(doc.Paragraphs(5).Range.Text, Len(doc.Paragraphs(5).Range.Text) - 1)
   LastNamePosition = InStr(strTemp, " ")
   If LastNamePosition <> 0 Then
        If InStr(LastNamePosition + 1, strTemp, " ") <> 0 Then
            LastNamePosition = InStr(LastNamePosition + 1, strTemp, " ")
        End If
    End If
   strTitle = Right(strTemp, Len(strTemp) - LastNamePosition) & ", " & Left(strTemp, LastNamePosition - 1)
   
   ' Get Group
   strTemp = Left(doc.Paragraphs(8).Range.Text, Len(doc.Paragraphs(8).Range.Text) - 1)
   strTitle = strTitle & " - " & strTemp
   
   ' Get Office Location
   strTitle = strTitle & " - " & LOCATION
   
   ' Get Title
   strTemp = Left(doc.Paragraphs(6).Range.Text, Len(doc.Paragraphs(6).Range.Text) - 1)
   strTitle = strTitle & " - (" & strTemp & ")"
   
   strComment = Left(doc.Paragraphs(11).Range.Text, Len(doc.Paragraphs(11).Range.Text) - 1)

   doc.BuiltInDocumentProperties("Title") = strTitle
   doc.BuiltInDocumentProperties("Comments") = strComment

End Sub



 

by: rdmjrbPosted on 2001-07-06 at 14:52:30ID: 6260747

Craig:

ok...its running like a champion,however I placed some files in the directory to test and they were not modified. Only 2 files were modified: original(containing the macro) and another misc one. Then I deleted the misc one and re-ran itand only the orig one was modified.

What do you think the problem is?

And do I have to open all the files before the code works?

 

by: GudarePosted on 2001-07-06 at 15:09:52ID: 6260779

To confirm:
The files are in the directory main, not in a subfolder of the directory.

The files are .doc files

If you step through, do the files open and close without saving changes?

 

by: rdmjrbPosted on 2001-07-06 at 15:27:52ID: 6260815

Yes
Yes

and sometimes

Here is what happens:
1. I have 3 files: 1.doc, 2.doc, 3.doc
2. The macro is in 1.doc
3. I run the macro successfully
4. Changes occur in all files
5. Add 3 more files:4.doc and so on
6. Run the macro from 1.doc and changes do not occur
7. Add the macro to 4.doc and run
8. changes occur

Its strange...i want to have one directory and one template file that contains the macro, and any file in that directory willhave changes made no matter what order and so on.

I am trying to troubleshoot it, but without much luck.

 

by: rdmjrbPosted on 2001-07-06 at 15:30:53ID: 6260820

perhaps there is a variable being left open or some liek this...

 

by: GudarePosted on 2001-07-06 at 15:52:45ID: 6260851

I don't know, let me think on that set of problems over the weekend. Something's gotta be triggering it but I'll be danged if I know what...

 

by: rdmjrbPosted on 2001-07-11 at 21:50:45ID: 6275729

Gudare:

The problem mentioned above is in-frequent and is minuscule compared to the precision and speed in which you delivered a the solution.

Cheers - rdmjrb

 

by: GudarePosted on 2001-07-12 at 07:15:36ID: 6277292

My thanks.

Unfortunately I just can't get the problem to occur locally, been trying all week, sorry for not updating you. Appreciate the acceptance of the answer, but I just can't find it.

Good luck to you. :)

-Craig

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...