If someone asked you to add a conditional header or footer to a document in Microsoft Word, would you panic? Some users might because the interface offers no such option. You can use the Different Odd & Even Pages option, but that’s not the same thing.
A conditional header or footer will display, or not, depending on whether an expression returns TRUE or FALSE. In this article, I’ll show you three ways to use fields to generate a conditional header or footer, although the examples will all be in the footer.
SEE: 83 Excel tips every user should master (TechRepublic)
I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. Word fields have been around for a long time. This article assumes you have basic Word skills, but even a beginner should be able to follow the instructions to success. You can download the demonstration .docx and .doc files, but I encourage you to practice entering the fields yourself. Word Online doesn’t display headers and footers; nor can you manipulate them. However, they are still there, and they will print.
What’s a field in Word?
If you’re familiar with Word fields, you’re a step ahead. If not, they’re not difficult to use, but the process might feel a bit odd at first. Fields are little programs that complete a specific task, similar to a macro, but you don’t need to write any code. Everything the field needs to do its job is already there, except for the information you supply.
You use fields almost every time you use Word, but you just don’t realize it. For instance, when you use the interface to display a page number in the header or footer, you’re using a field! If you’d like to see that at work, open a new document and enter a page number in the header. Then, select the page number and press Alt + F9. Word converts the page number to its underlying { PAGE } field. In this mode, you can modify the field. Press Alt + F9, which acts as a toggle, again to see the page number.
The expression to display on last page of the Word doc
It’s common to display a different header or footer on the first or last page of a document. You can use the built-in Different First Page option to display a different header on the first page. There’s no such option for the last page; determining the last page requires a simple field expression in the form
{ IF {PAGE} = { NUMPAGES }, “true text” “false text”}
It’s easy to decipher: If the current page number, { PAGE } equals the total number of pages, { NUMPAGES } print “true text”. If the two page numbers don’t match, the expression prints “false text”.
Let’s look at a quick example using a three-page document:
- Open the header or footer by double-clicking in the top or bottom margin.
- Word will position the cursor at the left margin, which is fine.
- In this next part, we’ll be entering the fields manually, which I think is the easiest way to enter nested fields. To insert a blank field, press Ctrl + F9 and type IF. (Case doesn’t really matter.)
- While still inside the If field, press Ctrl + F9 a second time to enter a blank field and enter PAGE.
- Move the cursor to the right of the closing } character in the { PAGE } field and enter =.
- Press Ctrl + F9 a third time and enter NUMPAGES.
- Move the cursor to the right of the closing } character in the NUMPAGES field and enter “Last page” “Not the last page”.
Figure A shows the nested fields. Do not enter the {} characters from the keypad; it won’t work. You must enter the blank fields using Ctrl + F9 and enter the content inside those brackets. Now, select the entire nested field expression and press Alt + F9 to evaluate the results (Figure A). As you can see, the last page is the current page.
Figure A
I’ve shown you only one way to enter fields, but there are other methods. Before we continue, I want to share another way to enter nested fields that you might find easier. You can type the field name, such as IF or NAME, select that name and press Ctrl + F9. Doing so will convert IF or NAME to a field and insert the brackets.
This simple expression works fine until you have unnumbered pages in your document. For instance, the document might have a table of contents or a title page that you don’t want in the page count. When this happens, you must find a way to accommodate those pages.
SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)
If you’re excluding only the first page, use the Different First Page option. Doing so will inhibit a page number, and Word won’t include that page in the final page count. Excluding other pages might require a section break or an expression that evaluates those pages. The following expression excludes a two-page section at the beginning of the document that’s not included in the total page count:
{ IF {PAGE} = { NUMPAGES – 2 } , “Last page” “Not the last page”}
The expression is almost the same as the first, but the -2 component subtracts 2, the total number of pages you want to exclude from the page count.
If you want the expression to return nothing, use the empty string character, “”. For example, the following nested field expression will return a string on the last page and return nothing on all other pages:
{ IF {PAGE} = { NUMPAGES } , “” “Not the last page” }
Now let’s look at a condition that seems a bit more complex.
How to specify page numbers in a footer in Word
What happens when you have a footer that you want to print only on specific pages? You use the same fields to express the specific page numbers and use the appropriate true and false text. Let’s suppose that you want to print a page number only on pages 5 and 6?
The problem only seems more complex, but in truth, it’s simpler. Instead of a nested expression, use two expressions:
{ If {Page } = “5” “Page 5” “” }
{ If {Page } = “6” “Page 6” “” }
Figure B shows the page number on page 6.
Figure B
Both conditions are simple to satisfy using two different expressions instead of a nested expression. Now, let’s look at something you might think impossible using fields.
How to display an image in a header or footer in Word
If asked if you can display a conditional image in the header or footer, you might reply, “No.” That’s not correct. You treat an image the same as any other text or value. First, you need to insert the image file into the document and save it as AutoText. Then, you insert the AutoText into the footer or header.
First, let’s add TechRepublic’s logo to the document as an AutoText element:
- Insert the picture into the body of the document (not a header or footer) as you would any other image file.
- Select the image and click the Explore Quick Parts dropdown.
- Choose Save Selection to Quick Parts Gallery.
- In the resulting dialog, give the image a name, such as TRLogo (see Figure C).
- Click OK.
Figure C
Now that you have the image as an AutoText item in the document, you can insert it into the header as follows:
- Position the cursor in the header or footer where you want it to appear.
- Using Figure D as a guide, enter the { IF } field up to the first ” character.
- Click the Insert tab.
- From the Explore Quick Parts dropdown (Text group), choose AutoText.
- Select the image (Figure E) and click OK.
Figure F shows the TechRepublic.com logo in the footer, conditionally; it appears only on the last page thanks to the conditional field expression shown in Figure D.
Figure D
Figure E
Figure F
This introduction to displaying conditional content, including images, in a document’s header or footer is just the beginning. You can use the following comparison operators: =, <>, <=, and >=. You’ve learned how to nest fields, which is extremely useful. However, even when you could use a nested expression, you don’t always have to, as shown in the second example. Remember to always use F9 to insert and modify fields.
Stay tuned
I mentioned earlier that there are more ways to enter fields than the one I worked you through in the first example. A future article will include all of the ways to enter Word fields.
If you run into a conditional header or footer request that you can’t handle, take a look at Word fields. They’re not magic, but it kind of feels like magic when they do what you want.
Illustration: Lisa Hornung, Getty Images/iStockPhoto
If someone asked you to add a conditional header or footer to a document in Microsoft Word, would you panic? Some users might because the interface offers no such option. You can use the Different Odd & Even Pages option, but that’s not the same thing.
A conditional header or footer will display, or not, depending on whether an expression returns TRUE or FALSE. In this article, I’ll show you three ways to use fields to generate a conditional header or footer, although the examples will all be in the footer.
SEE: 83 Excel tips every user should master (TechRepublic)
I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. Word fields have been around for a long time. This article assumes you have basic Word skills, but even a beginner should be able to follow the instructions to success. You can download the demonstration .docx and .doc files, but I encourage you to practice entering the fields yourself. Word Online doesn’t display headers and footers; nor can you manipulate them. However, they are still there, and they will print.
What’s a field in Word?
If you’re familiar with Word fields, you’re a step ahead. If not, they’re not difficult to use, but the process might feel a bit odd at first. Fields are little programs that complete a specific task, similar to a macro, but you don’t need to write any code. Everything the field needs to do its job is already there, except for the information you supply.
You use fields almost every time you use Word, but you just don’t realize it. For instance, when you use the interface to display a page number in the header or footer, you’re using a field! If you’d like to see that at work, open a new document and enter a page number in the header. Then, select the page number and press Alt + F9. Word converts the page number to its underlying { PAGE } field. In this mode, you can modify the field. Press Alt + F9, which acts as a toggle, again to see the page number.
The expression to display on last page of the Word doc
It’s common to display a different header or footer on the first or last page of a document. You can use the built-in Different First Page option to display a different header on the first page. There’s no such option for the last page; determining the last page requires a simple field expression in the form
{ IF {PAGE} = { NUMPAGES }, “true text” “false text”}
It’s easy to decipher: If the current page number, { PAGE } equals the total number of pages, { NUMPAGES } print “true text”. If the two page numbers don’t match, the expression prints “false text”.
Let’s look at a quick example using a three-page document:
- Open the header or footer by double-clicking in the top or bottom margin.
- Word will position the cursor at the left margin, which is fine.
- In this next part, we’ll be entering the fields manually, which I think is the easiest way to enter nested fields. To insert a blank field, press Ctrl + F9 and type IF. (Case doesn’t really matter.)
- While still inside the If field, press Ctrl + F9 a second time to enter a blank field and enter PAGE.
- Move the cursor to the right of the closing } character in the { PAGE } field and enter =.
- Press Ctrl + F9 a third time and enter NUMPAGES.
- Move the cursor to the right of the closing } character in the NUMPAGES field and enter “Last page” “Not the last page”.
Figure A shows the nested fields. Do not enter the {} characters from the keypad; it won’t work. You must enter the blank fields using Ctrl + F9 and enter the content inside those brackets. Now, select the entire nested field expression and press Alt + F9 to evaluate the results (Figure A). As you can see, the last page is the current page.
Figure A
Use a nested field expression to create a conditional header or footer.
I’ve shown you only one way to enter fields, but there are other methods. Before we continue, I want to share another way to enter nested fields that you might find easier. You can type the field name, such as IF or NAME, select that name and press Ctrl + F9. Doing so will convert IF or NAME to a field and insert the brackets.
This simple expression works fine until you have unnumbered pages in your document. For instance, the document might have a table of contents or a title page that you don’t want in the page count. When this happens, you must find a way to accommodate those pages.
SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)
If you’re excluding only the first page, use the Different First Page option. Doing so will inhibit a page number, and Word won’t include that page in the final page count. Excluding other pages might require a section break or an expression that evaluates those pages. The following expression excludes a two-page section at the beginning of the document that’s not included in the total page count:
{ IF {PAGE} = { NUMPAGES – 2 } , “Last page” “Not the last page”}
The expression is almost the same as the first, but the -2 component subtracts 2, the total number of pages you want to exclude from the page count.
If you want the expression to return nothing, use the empty string character, “”. For example, the following nested field expression will return a string on the last page and return nothing on all other pages:
{ IF {PAGE} = { NUMPAGES } , “” “Not the last page” }
Now let’s look at a condition that seems a bit more complex.
How to specify page numbers in a footer in Word
What happens when you have a footer that you want to print only on specific pages? You use the same fields to express the specific page numbers and use the appropriate true and false text. Let’s suppose that you want to print a page number only on pages 5 and 6?
The problem only seems more complex, but in truth, it’s simpler. Instead of a nested expression, use two expressions:
{ If {Page } = “5” “Page 5” “” }
{ If {Page } = “6” “Page 6” “” }
Figure B shows the page number on page 6.
Figure B
Use two expressions to satisfy the pages 5 and 6 condition.
Both conditions are simple to satisfy using two different expressions instead of a nested expression. Now, let’s look at something you might think impossible using fields.
How to display an image in a header or footer in Word
If asked if you can display a conditional image in the header or footer, you might reply, “No.” That’s not correct. You treat an image the same as any other text or value. First, you need to insert the image file into the document and save it as AutoText. Then, you insert the AutoText into the footer or header.
First, let’s add TechRepublic’s logo to the document as an AutoText element:
- Insert the picture into the body of the document (not a header or footer) as you would any other image file.
- Select the image and click the Explore Quick Parts dropdown.
- Choose Save Selection to Quick Parts Gallery.
- In the resulting dialog, give the image a name, such as TRLogo (see Figure C).
- Click OK.
Figure C
Name the image something meaningful so it’s easy to recall.
Now that you have the image as an AutoText item in the document, you can insert it into the header as follows:
- Position the cursor in the header or footer where you want it to appear.
- Using Figure D as a guide, enter the { IF } field up to the first ” character.
- Click the Insert tab.
- From the Explore Quick Parts dropdown (Text group), choose AutoText.
- Select the image (Figure E) and click OK.
Figure F shows the TechRepublic.com logo in the footer, conditionally; it appears only on the last page thanks to the conditional field expression shown in Figure D.
Figure D
Enter the field expression up to the logo image.
Figure E
Select TRLogo, the image AutoText you previously added.
Figure F
Fields are so versatile that you can even display an image conditionally.
This introduction to displaying conditional content, including images, in a document’s header or footer is just the beginning. You can use the following comparison operators: =, <>, <=, and >=. You’ve learned how to nest fields, which is extremely useful. However, even when you could use a nested expression, you don’t always have to, as shown in the second example. Remember to always use F9 to insert and modify fields.
Stay tuned
I mentioned earlier that there are more ways to enter fields than the one I worked you through in the first example. A future article will include all of the ways to enter Word fields.
Microsoft Weekly Newsletter
Be your company’s Microsoft insider by reading these Windows and Office tips, tricks, and cheat sheets.
Delivered Mondays and Wednesdays
Sign up today
Also see
Denial of responsibility! NewsBit.us is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – [email protected]. The content will be deleted within 24 hours.
I am trying to use the IF field code in Word but I am getting radically unpredictable behavior.
My syntax is this:
{IF PAGE = NUMPAGES "YES" "NO"}
I have inserted it into a footer, text box, inline with the document and anything else I can think of to troubleshoot. My outcomes have been getting either a «1» the last page number, nothing or syntax errors with no real pattern as to why. What am I doing wrong? This is not for a mail merge, this is for a word template.
Thanks for any help.
Dave
25.2k10 gold badges55 silver badges69 bronze badges
asked Sep 4, 2013 at 10:35
0
For starters, you need to nest the { PAGE } and { NUMPAGES } fields like this
{ IF { PAGE } = { NUMPAGES } «YES» «NO» }
where every pair of { } is a pair of the special field code braces that you can insert using ctrl-F9 on Windows Word.
If you are using chapter-page numbering that doesn’t work, but
{ IF { PAGE #0 } = { NUMPAGES } «YES» «NO» }
works in at least some cases.
answered Sep 4, 2013 at 17:06
1
- Remove From My Forums
-
Question
-
I need to insert Page Number in MS Word using C#. Manually i can insert the Page number with condiction. I need to get the below formula.
{IF{PAGE} = 1 «» «{PAGE}»}
I dont want to show the page number on the first page. How can i do it programmatically.
Please help me out.
Thankz alot.
All replies
-
Hello Abhi,
We could insert a page number programmatically. For this, please refer to this resource: http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx. To show the page number on the second page, I have followed this page in UI. However, the VBA codes are same when selecting/clearing the Different First Page on Design Tab. As far as I know, Word object model does not expose such a property/method to achieve this point.
However, I have an alternatively way. We could access each page, access the footer of this page, and set the value as the page number. To get each page, please refer to these threads: extract content of the particular pages and How to change INCLUDETEXT value in the footer in Word 2003. Here is a thread which may interest you: http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/ede895ef-2112-4ada-b119-389fdf5a5372/.
Also, are you working with VSTO technology? What the formula means? Would you please tell us more information for this?
If I have mistaken this issue, or you have any further question, please feel free to follow up.
Best regards,
Bessie
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us. -
Hi Abhi_ahaa
This isn’t straight-forward, which is why I haven’t replied before — I’m just so busy. And most of the examples I know of are in VBA; the principle remains the same for C#, you just need to understand how it works so that you can adapt the syntax to C#. Here’s one simple example. I don’t particularly care for this approach, myself, but it has the advantage of being fairly simple to understand.
FWIW Dave is incorrect in stating that you cannot use a Range. It can be done, but the actual code is somewhat long and complex. I’m very busy right now and don’t have time to type out the necessary code in C#, but I can describe the basics of how another approach works:
You insert the outermost field, first (in your case the IF field). Where you need to insert nested fields, put a placehoder in the If field code’s text. Make sure, as you create the field, that you assign it to a field object so that you can work with that object’s Range directly. Your code would look something like this (pseudocode!):
Word.Field fld = doc.Fields.Add([fieldtypeEmpty], «If XXX = 1 » ‘XXX'», [false]);
Word.Range rng = fld.Result;
rng.IncludeFieldCodes = true; //this will return the field code, not the result for the Range when you query Range.TextAt this point, you can either «walk» the characters in the Range in order to locate the placeholder and insert the required field codes, or you can use Word’s built-in Range.Find functionality to locate the placeholders, then insert the additional fields.
Cindy Meister, VSTO/Word MVP
-
Hi Bessie Zhao and Cindy Meister,
Thankz for replyig my post. The Program am doing is pasted below. Please go through it.
//Button EVENT
private void Button1_Click(object sender, RibbonControlEventArgs e)
{
string text = «{IF{SECTIONPAGES} = 1 » ‘{PAGE}’}»; // change string value to «Page { PAGE } of { NUMPAGES }»Test1(text);
}//FUNCTION Test1
private void Test1(string myTemplates)
{
if (Globals.ThisAddIn.Application.Documents.Count > 0)
{
object typemissing = Type.Missing;
object units = Word.WdUnits.wdCharacter;
object count = 1;
Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
Word.Selection Selection = document.Application.Selection;try
{
//error checking codes in case user insert standards over selected existing ones
if (Selection.Type == Microsoft.Office.Interop.Word.WdSelectionType.wdSelectionInlineShape)
{
Selection.MoveRight(ref units, ref count, ref typemissing);
}
else
{
for (int i = 1; i <= Selection.ContentControls.Count; i++)
{
object index = i;
Word.ContentControl cc = Selection.ContentControls.get_Item(ref index);
cc.Delete(false);
}
}string CommandString = myTemplates;
Dictionary<string, string> commandQueue = ExtractCommandsFrom(CommandString);
object fieldEmpty = Word.WdFieldType.wdFieldEmpty;
object preserveFormatting = true;foreach (string key in commandQueue.Keys)
{
if (key[0] == ‘F’)
{
object FieldText = commandQueue[key];
Word.Field abc = Selection.Fields.Add(Selection.Range, ref fieldEmpty, ref FieldText, ref preserveFormatting);
abc.Update();
}
else
{
string TypeText = commandQueue[key];
Selection.TypeText(TypeText);
}
}
Selection.TypeParagraph();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}//FUNCTION ExtractCommandsFrom
public Dictionary<string, string> ExtractCommandsFrom(string CommandString)
{
//For example: Page { PAGE } of { NUMPAGES }
//is translated into Dictionary of actions as
// commandQueue[0] = Page; commandQueue[1] = PAGE
// commandQueue[2] = of; commandQueue[3] = NUMPAGES
//int TotalLength = CommandString.Length;
Dictionary<string, string> commandQueue = new Dictionary<string, string>();
StringBuilder TypeTexts = new StringBuilder();
StringBuilder FieldText = new StringBuilder();
bool CollectFieldState = false;for (int i = 0; i < TotalLength; i++)
{
char currentChar = CommandString[i];switch (currentChar)
{
case ‘{‘:
if (CollectFieldState == false)
{
commandQueue.Add(«T» + i.ToString(), TypeTexts.ToString());
TypeTexts.Length = 0;
CollectFieldState = true;
continue;
}
break;case ‘}’:
if (CollectFieldState == true)
{
commandQueue.Add(«F» + i.ToString(), FieldText.ToString());
FieldText.Length = 0;
CollectFieldState = false;
continue;
}
break;default:
break;
}if (CollectFieldState == true)
{ FieldText.Append(currentChar); }
else
{ TypeTexts.Append(currentChar); }
}
return commandQueue;
}This program works for me except the IF condition statement. If i add an IF statement then the out put wont come correct. I have tried the Word.WdFieldType.wdFieldIF. it is also not woking. please help me out.
-
1. I suggest you do a «MessageBox.Show» (or log, or something) to check what value is being passed to ref FieldText
2. The field code you assign to string text, at the top, is incorrect. It needs a space after the IF
3. You don’t say HOW it’s not working. If you don’t describe exactly what you’re getting and how it’s not right, we can’t help you effectively. How does the field code look after it’s inserted into the document? (You can toggle codes/results using Alt+F9)
Cindy Meister, VSTO/Word MVP
-
Hi Cindy Meister,
As per your suggession, I tried space after string IF — > string text = «{IF{SECTIONPAGES} = 1 » ‘{PAGE}’}»; .
And the result am getting is = 1 » ‘1 that is {IF{SECTIONPAGES*MERGEFORMAT} = 1 «» ‘{PAGE*MERGEFORMAT}
Awaiting for your earliest reply. Thank you.
-
<<As per your suggession, I tried space after string IF — > string text = «{IF{SECTIONPAGES} = 1 » ‘{PAGE}’}»; .
And the result am getting is = 1 » ‘1 that is {IF{SECTIONPAGES*MERGEFORMAT} = 1 «» ‘{PAGE*MERGEFORMAT}>>
I don’t understand what you’re saying, here. You still have no space after the IF. Your string needs to look more like:
«{ IF { SectionPages } = 1 » ‘{ Page }’ }»
And as far as I can tell you haven’t shown us exactly what’s being passed into the variable FieldText.
BTW, I very much recommend you leave * Mergeformat out.
Cindy Meister, VSTO/Word MVP
-
Marked as answer by
Monday, January 11, 2010 10:12 AM
-
Unmarked as answer by
Cindy Meister MVP
Thursday, January 14, 2010 7:34 AM
-
Marked as answer by
-
Hi Cindy Meister,
Yes i have tried space after string IF -> string text = «{ IF { SECTIONPAGES } = 1 » ‘{ PAGE }’ }»;In the previous post code.. the commandString will assign to the dictonary named «commandQueue».The command Ques Value looks like
index values
————————
0 { [ T10, ] }
1 { [ F20, IF { SECTIONPAGES ] }
2 { [ T30, = 1 » ‘]}
3 { [ F40, Page ]}The above values which starts with » F» are passing to the FieldText. But it is executing one by one. The Inner Opening bracket of the IF ie. { SECTIONPAGES is not counting.
-
I understand, in general terms, what your code is supposed to be doing. We have a similar kind of approach in our VBA Word Programming book (German language). But I don’t understand the details of the .NET things you’re using well enough to be able to spot what the problem is. And I don’t have time to take it apart and test it.
All I can recommend is that you
1. Pare the code down to the absolute bare minimum and test on a «plain» document (take out the stuff about content controls, inline shapes, etc.)
2. Walk it through, step-by-step, and check exactly what it’s doing. As this isn’t VBA, you unfortunately can’t see the result as it’s happening. So I’d say start with a very simple type of field — just a Page field, for example, and see if that gives you the right result. If it doesn’t, you know you’re not inserting the field codes correctly.
3. Once you can insert a single field, try nesting one field within another — just one. For example, you could do a { Quote { Page } }.
Once you get that to work, try it with the Quote field, with a bit of text in addition. Once you’ve got that down, a more complex field such as your IF field shouldn’t be such a stretch.
I’m sure the problem is in some small detail…
Cindy Meister, VSTO/Word MVP
Creating nested fields is complicated using the object model — there’s nothing in it to facilitate the process. Trying to mimic the UI by creating the innermost field(s), selecting them, then inserting field brackets is a bit tricky and code for every combination must be written.
Using the object model, it makes more sense to create the outermost field writing placeholders for the fields to nest within it. Then Word’s Range.Find functionality can pick up the placeholders and insert field codes in their place.
Here’s some sample code to create the conditional footer text you describe:
//Returns the changed field code
private string GenerateNestedField(Word.Field fldOuter,
string sPlaceholder)
{
Word.Range rngFld = fldOuter.Code;
Word.Document doc = (Word.Document) fldOuter.Parent;
bool bFound;
string sFieldCode;
//Get the field code from the placeholder by removing the { }
sFieldCode = sPlaceholder.Substring(1, sPlaceholder.Length - 2); //Mid(sPlaceholder, 2, Len(sPlaceholder) - 2)
rngFld.TextRetrievalMode.IncludeFieldCodes = true;
bFound = rngFld.Find.Execute(sPlaceholder);
if (bFound) doc.Fields.Add(rngFld, Word.WdFieldType.wdFieldEmpty, sFieldCode, false);
return fldOuter.Code.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
getWordInstance(); //Object defined as a class member for Word.Application
Word.Document doc = wdApp.ActiveDocument;
Word.View vw = doc.ActiveWindow.View;
Word.Range rngTarget = null;
Word.Field fldIf = null;
string sIfField, sFieldCode;
string sQ = '"'.ToString();
bool bViewFldCodes = false;
sIfField = "IF {Page} = {NumPages} " + sQ + "Last" + sQ + " " + sQ + "Other" + sQ;
rngTarget = doc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
bViewFldCodes = vw.ShowFieldCodes;
//Finding text in a field codes requires field codes to be shown
if(!bViewFldCodes) vw.ShowFieldCodes = true;
//Create the nested field: { IF {Pages} = {NumPages} "Last" "Other" }
fldIf = doc.Fields.Add(rngTarget, Word.WdFieldType.wdFieldEmpty, sIfField, false);
sFieldCode = GenerateNestedField(fldIf, "{Page}");
sFieldCode = GenerateNestedField(fldIf, "{NumPages}");
rngTarget.Fields.Update();
vw.ShowFieldCodes = bViewFldCodes;
}