Hi,
My basic requirement is to search a directory of word documents to see what other documents they reference in their text. Basically, these are specific task procedures that refer back to standard operating procedures. As the SOPs are revised/superceded/obseleted, I'd like a way to pull the references out and understand which specific task procedures are affected.
I found a similar requirement and helpful code from cytop in this thread:
Search multiple word documents for specific content and paste into excel.
My search requirement is different from that thread in that I don't know the individual document numbers beforehand, but the document numbers I'd like to search for are in a format of:
abc-####-##
abc-####-##-###
xyz-####-##-###
where abc and xyz are letters and # are numbers. I'd like to search for and record into Excel any references in the target documents. There are a limited number of alphabetic sequences, so I'd probably search for something like:
abc-*
xyz-*
The code provided by cytop in that thread is great, but I'd like to extend it. I modified it slightly (see below) to use a wildcard search and count the number of hits in each document. I have not had luck in retrieving the "whole word" of the hit that was found. Once I have that I believe that I could easily shove it into a cell of the spreadsheet.
Sub SearchDocs()
Dim oWRD As Object '** Word.Application
Dim oDOC As Object '** Word.Document
Dim oFound As Object '** Word.Range
Dim rCell As Excel.Range
Dim lngCol As Long
Dim intFound As Integer
Dim strFile As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
lngCol = 1
'** Set oWRD = New Word.Application
Set oWRD = CreateObject("Word.Application")
oWRD.Visible = True
'// XL2007 specific
Sheet1.Range("B2:XFD100000").ClearContents
strFile = Dir$(Sheet1.Range("B1").Value & "\*.doc?")
lngCol = 2
'// loop matching files
Do While strFile <> vbNullString
'open
Set oDOC = oWRD.Documents.Open(Sheet1.Range("B1").Value & "\" & strFile)
With Sheet1.Cells(2, lngCol)
.Value = strFile
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 90
.EntireColumn.ColumnWidth = 3.35
End With
For Each rCell In Sheet1.Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row)
With oDOC.Content.Find
.ClearFormatting
.Text = rCell.Value
.MatchCase = False
.MatchWholeWord = False
'.MatchPrefix = True
.MatchWildcards = True
.Execute
intFound = 0
Do While .Found = True
'Count each hit
intFound = intFound + 1
.Execute
Loop
'Write number of hits for search string in target document to spreadsheet
Sheet1.Cells(rCell.Row, lngCol).Value = intFound
End With
Next
Application.ScreenUpdating = True
DoEvents
Application.ScreenUpdating = False
lngCol = lngCol + 1
oDOC.Close
'// get next file
strFile = Dir$()
Loop
MsgBox "Finshed...", vbInformation
ErrHandler:
Application.ScreenUpdating = True
oWRD.Application.Quit
End Sub
Display More
Thanks,
Jim