I am writing a function that returns a text string based on certain input.
The macro calling the function will insert the string into a table cell. In
some cases, I would like the string to contain a field so that when the
document is updated, the actual string will take on the value of the field in
that document.
Is there a way to do this? The only way I can find involves using the Add
method but this works on a document range object.
If anyone can help I would greatly appreciate it.
There's no way to embed an actual field in a string, because a string is
just a sequence of characters. However, once the string is inserted in the
document, a part of the string can be converted into a field code, and the
resulting field replaces that part of the text. Here's a demo macro to show
what I mean:
Sub StringAndFieldDemo()
' choose any characters that won't
' occur in an input string
Const Ldelim = "{"
Const Rdelim = "}"
Dim oDoc As Document
Dim oTbl As Table
Dim oRg As Range
Dim oStr As String
' the delimiters in this string are
' ordinary characters surrounding
' what will become a field code
oStr = "This => " & Ldelim & "DocProperty Author" _
& Rdelim & " <= is a field."
' choose where to put it
Set oDoc = Documents.Add
Set oTbl = oDoc.Tables.Add(Range:=oDoc.Range, _
numrows:=3, numcolumns:=3)
Set oRg = oTbl.Cell(2, 2).Range
' insert the string
oRg.Text = oStr
' contract the range to cover only
' the field code, and remove the delimiters
With oRg
.MoveStartUntil cset:=Ldelim, Count:=wdForward
.MoveEndUntil cset:=Rdelim, Count:=wdBackward
.Text = Replace(.Text, Ldelim, "")
.Text = Replace(.Text, Rdelim, "")
End With
' the magic statement:
' replace the text of the range with a field
' whose code is the text of the range
oDoc.Fields.Add Range:=oRg, _
Type:=wdFieldEmpty, Text:=oRg.Text
oDoc.Fields.Update
End Sub

Signature
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
> I am writing a function that returns a text string based on certain
> input. The macro calling the function will insert the string into a
[quoted text clipped - 6 lines]
>
> If anyone can help I would greatly appreciate it.