Re: Look for ASK field first before creating it. by Klaus
Klaus
Tue May 13 04:56:58 PDT 2008
Hi Pia,
You likely need a bit more than something that fits in an "IF" :-/
Loop through all the fields in the first paragraph (or the whole doc...
shouldn't take that long and might be safer).
See if there's an ASK field with the code already:
(The sample code is just for one of the ASK fields...)
Dim rngSearch As Range
' If you just want to look in the first paragraph:
Set rngSearch = ActiveDocument.Paragraphs(1).Range
' or if you aren't sure and want to look in the whole content:
' Set rngSearch = ActiveDocument.Content
Dim myField As Field
Dim sCode As String
Dim boolAlreadyThere As Boolean
boolAlreadyThere = False
sCode = "ASK Type ""Type"" \d ""<Type>"""
For Each myField In rngSearch.Fields
If myField.Type = wdFieldAsk And Trim(myField.Code) = sCode Then
boolAlreadyThere = True
End If
Next myField
' If you haven't found it, insert the ASK field:
If Not boolAlreadyThere Then
Selection.Fields.Add _
Range:=Selection.Range, _
Type:=wdFieldEmpty, _
Text:=sCode, _
PreserveFormatting:=False
Debug.Print sCode
Else
' Just for debugging:
' Debug.Print sCode, "already there"
End If
Regards,
Klaus
"PiaD" wrote:
> Hi -
> I have a macro that inserts 2 ASK fields at the top of an active document
> as
> follows:
> I would like to first look for the ASK fields first, and only add them if
> they do not exist yet. Can someone help with the IF statement needed?
>
> Sub AddFieldCodes()
> ' Used to add ASK field codes to an existing document, not initially
> created
> using this template.
> ' Add ASK Reference Field Codes at start of document.
> Selection.GoTo What:=wdGoToPage, Which:=wdGoToFirst, Name:=""
> Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=
> _
> " ASK Name ""Name"" \d ""<Name>"" ", _
> PreserveFormatting:=False
> Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=
> _
> " ASK Type ""Type"" \d ""<Type>"" ", _
> PreserveFormatting:=False
> End Sub