PDA

View Full Version : Solved: loop through word docs and read bookmark contents



gibbo1715
10-11-2006, 05:58 AM
Hi All, been a while

Is it possible to loop through all word documents in a given directory and read the contents of a bookmark (Or form field actually) and if it says a certain word add 1 to my count?

im using the below code to get the text currently but im sure there must be a better way

Dim test As String
test = ActiveDocument.Bookmarks("Text1").Range
MsgBox Mid(test, 11)

thanks

gibbo

gibbo1715
10-11-2006, 06:53 AM
All

Thanks for looking, managed to figure it out but would be interested if anyone can tell me a faster way

Gibbo

Option Explicit

Dim oFSO

Sub LoopFolders()
Dim oThis As Worksheet
Dim i As Integer

Set oThis = ActiveSheet

Set oFSO = CreateObject("Scripting.FileSystemObject")

selectFiles "X:\Word\", oThis

Set oFSO = Nothing

End Sub

Sub selectFiles(sPath, sh As Worksheet)
'---------------------------------------------------------------------------
Dim Folder As Object
Dim Files As Object
Dim file As Object
Dim fldr

Dim AppWrd As New Word.Application
Dim Doc As Word.Document
Dim FileName As String
Dim test As String

Set Folder = oFSO.GetFolder(sPath)

For Each fldr In Folder.Subfolders
selectFiles fldr.Path, sh
Next fldr
For Each file In Folder.Files
If file.Type = "Microsoft Word Document" Then
On Error Resume Next
Set Doc = AppWrd.Documents.Open(FileName:=file.Path, ReadOnly:=True, _
PasswordDocument:="")
Doc.Unprotect
test = Doc.Bookmarks("Text1").Range.Text
If Mid(test, 11) = "test" Then
Range("A2").Value = Range("A2").Value + 1
End If
Doc.Close False
Set Doc = Nothing
End If
Next file
Set AppWrd = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

fumei
10-11-2006, 08:20 AM
All FormFields are bookmarks, but not all bookmarks are formfields.

If they are indeed FormFields, you can access them directly using the FormFields collection, rather than the Bookmarks collection.test = Doc.FormFields("Text1").Resultif it is a text formfield.

Also, you can get that result without unprotecting the document. So unless you have as reason to, Doc.Unprotect is not needed.

Is there a specific reason for using late-binding for your FileSysystemObject?

gibbo1715
10-12-2006, 12:44 AM
Gerry

Thanks for the reply, no reason for using late binding really, just re used some code I had used for something else

Paul