ComplexFields.vb
''
'' This code is part of GrapeCity Documents for Word samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
''
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Linq
Imports GrapeCity.Documents.Word

'' This sample demonstrates the use of complext fields.
'' It adds a complex field that tests whether the current date
'' Is the New Year day, And modifies the text in the document
'' accordingly. See also DateAndTime sample.
Public Class ComplexFields
    Function CreateDocx() As GcWordDocument
        Dim doc = New GcWordDocument()
        Dim sec = doc.Body.Sections.First

        '' Add a title
        sec.GetRange().Paragraphs.Add("Testing whether it is the New Year yet").Style = doc.Styles(BuiltInStyleId.Title)

        '' Add a paragraph And get its range:
        Dim rng = sec.GetRange().Paragraphs.Add().GetRange()
        '' Add a static text:
        rng.Runs.Add("Today is ")

        '' Add a complex field with "IF" instruction. We also provide 
        '' a pre-calculated value for the sake of PDF export, as GcWord
        '' does Not yet support field calculation - see DateAndTime.
        '' Note also that because the code field will Not be calculated
        '' in the PDF export, the "NOT " won't be bold in it:
        Dim val As String
        If DateTime.Now.DayOfYear = 1 Then
            val = ""
        Else
            val = "NOT "
        End If
        Dim f = rng.ComplexFields.Add("IF ", val)
        '' Add a complex field with "DATE" instruction:
        f.GetCodeRange().ComplexFields.Add(" DATE \@ ""M-d"" ")
        '' Add additional instruction to the "IF" field to compare the nested
        '' DATE field result with "1-1" And return "NOT " if it Is true,
        '' also make the "NOT " bold if visible: 
        f.CodeFields.Add("<> ""1-1"" ""Not """).ParentRun.Font.Bold = True

        '' Add a static text
        rng.Runs.Add("New Year's Day.")

        '' Done
        Return doc
    End Function
End Class