Find a variable search string

J

John

I need to use VBA to extract a string/s from a word2000 document. The
problem is the end part of the string will be variable within the
document. For example, I need to find every occurance of the string
{MERGEFIELD DI0010} where the last part (DI0010) could in fact be any
string. In short I need to find everything between the {braces} where
the first word is MERGEFIELD. Any help would be greatly appreciated.
 
D

Doug Robbins - Word MVP

Hi John,

Use

Dim afield As Field, astring As String
For Each afield In ActiveDocument.Fields
If afield.Type = wdFieldMergeField Then
astring = afield.Code
MsgBox astring
End If
Next afield

Please post any further questions or followup to the newsgroups for the
benefit of others who may be interested. Unsolicited questions forwarded
directly to me will only be answered on a paid consulting basis.

Hope this helps
Doug Robbins - Word MVP
 
J

John

Thanks Doug. It is not a real mergefield as such though. Just a marker
in the doucment. Its a 3rd party app that requires it this way. I have
managed to get what I want but I dont know if it is the most efficient
way. I used the follwing code. Funny but word still opens even though
I set visible property to false.

Dim MyWord As Word.Application
Set MyWord = New Word.Application

MyWord.Visible = False
MyWord.Documents.Open "c:\Test.doc"

lstDataItems.Clear
bFlag = False

Set myRange = MyWord.ActiveDocument.Range(0,
MyWord.Documents(1).Characters.Count)
For Each aWord In myRange.Words
If bFlag Then
lstDataItems.AddItem (Trim(aWord.Text))
bFlag = False
End If

If Trim(aWord.Text) = "MERGEFIELD" Then
bFlag = True
End If
Next aWord

MyWord.Quit
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top