How could I insert a formula in a Word document header? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How do you display code snippets in MS Word preserving format and syntax highlighting?Add an Image to Word Document and Scale it using VBAHow do I remedy the “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning?Tag spot in word documentMicrosoft Dynamics CRM - Insert Fields into Word DocumentWhy not inherit from List<T>?how to insert numbering that is linked to styles ms word c#Get pages of word documentCounting words in Word document, including footnoresOR Formula in Word document not returning a value

How to tell that you are a giant?

Do square wave exist?

Extracting terms with certain heads in a function

Compare a given version number in the form major.minor.build.patch and see if one is less than the other

How to answer "Have you ever been terminated?"

How do I find out the mythology and history of my Fortress?

Is there any way for the UK Prime Minister to make a motion directly dependent on Government confidence?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

How do I make this wiring inside cabinet safer? (Pic)

How would a mousetrap for use in space work?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

What would be the ideal power source for a cybernetic eye?

Fantasy story; one type of magic grows in power with use, but the more powerful they are, they more they are drawn to travel to their source

What does the "x" in "x86" represent?

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

Is there a kind of relay only consumes power when switching?

What does "lightly crushed" mean for cardamon pods?

First console to have temporary backward compatibility

What do you call the main part of a joke?

Fundamental Solution of the Pell Equation

Can a party unilaterally change candidates in preparation for a General election?

Do I really need to have a message in a novel to appeal to readers?

Significance of Cersei's obsession with elephants?

Chinese Seal on silk painting - what does it mean?



How could I insert a formula in a Word document header?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How do you display code snippets in MS Word preserving format and syntax highlighting?Add an Image to Word Document and Scale it using VBAHow do I remedy the “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning?Tag spot in word documentMicrosoft Dynamics CRM - Insert Fields into Word DocumentWhy not inherit from List<T>?how to insert numbering that is linked to styles ms word c#Get pages of word documentCounting words in Word document, including footnoresOR Formula in Word document not returning a value



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm trying to add a formula/expression in my Word document programatically. In my scenario I need to get the number of pages minus 1. If you try to do it in the document itself it should look like this:



=NUMPAGES *MERGEFORMAT -1


Now that I'm trying to do it via code I'm struggling... I've tried to do this:



RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES *MERGEFORMAT -1", true)


But in that case NUMPAGES *MERGEFORMAT doesn't work as a field but as a plain text. How could I achieve what I want ? Should I add a new field for NUMPAGES *MERGEFORMAT ?










share|improve this question






























    1















    I'm trying to add a formula/expression in my Word document programatically. In my scenario I need to get the number of pages minus 1. If you try to do it in the document itself it should look like this:



    =NUMPAGES *MERGEFORMAT -1


    Now that I'm trying to do it via code I'm struggling... I've tried to do this:



    RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES *MERGEFORMAT -1", true)


    But in that case NUMPAGES *MERGEFORMAT doesn't work as a field but as a plain text. How could I achieve what I want ? Should I add a new field for NUMPAGES *MERGEFORMAT ?










    share|improve this question


























      1












      1








      1








      I'm trying to add a formula/expression in my Word document programatically. In my scenario I need to get the number of pages minus 1. If you try to do it in the document itself it should look like this:



      =NUMPAGES *MERGEFORMAT -1


      Now that I'm trying to do it via code I'm struggling... I've tried to do this:



      RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES *MERGEFORMAT -1", true)


      But in that case NUMPAGES *MERGEFORMAT doesn't work as a field but as a plain text. How could I achieve what I want ? Should I add a new field for NUMPAGES *MERGEFORMAT ?










      share|improve this question
















      I'm trying to add a formula/expression in my Word document programatically. In my scenario I need to get the number of pages minus 1. If you try to do it in the document itself it should look like this:



      =NUMPAGES *MERGEFORMAT -1


      Now that I'm trying to do it via code I'm struggling... I've tried to do this:



      RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES *MERGEFORMAT -1", true)


      But in that case NUMPAGES *MERGEFORMAT doesn't work as a field but as a plain text. How could I achieve what I want ? Should I add a new field for NUMPAGES *MERGEFORMAT ?







      c# ms-word interop






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 21:35









      Cindy Meister

      16.1k102537




      16.1k102537










      asked Mar 22 at 9:44









      Juan Carlos RodriguezJuan Carlos Rodriguez

      664323




      664323






















          1 Answer
          1






          active

          oldest

          votes


















          1














          I don't think it will work this way. Entering braces into code does not work in any way.
          This, however, should do the trick just fine:



          doc.Variables.Add("myNumPages", doc.ComputeStatistics(Interop.WdStatistic.wdStatisticPages) - 1);
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldDocVariable, "myNumPages");


          .



          Edit/AddIt: There is another way, with the advantage of then having a dynamic field that can be updated:



          1. Insert a normal NUMPAGES field somewhere and give it a white font or make it hidden

          2. Select the field, add a bookmark "numpages" covering this entire field

          3. Now add a Formula field with the formula =numpages-1

          Example:



          var hidField = RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES");
          hidField.Result.Bookmarks.Add("numpages");
          hidField.Result.Font.Hidden = 1;
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldFormula, "numpages-1");


          You might have to play around with the range variable so as to not overwrite your hidden field.






          share|improve this answer

























          • I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

            – Juan Carlos Rodriguez
            Mar 22 at 11:51











          • You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

            – LocEngineer
            Mar 22 at 12:04











          • @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

            – LocEngineer
            Mar 22 at 13:50











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296822%2fhow-could-i-insert-a-formula-in-a-word-document-header%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I don't think it will work this way. Entering braces into code does not work in any way.
          This, however, should do the trick just fine:



          doc.Variables.Add("myNumPages", doc.ComputeStatistics(Interop.WdStatistic.wdStatisticPages) - 1);
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldDocVariable, "myNumPages");


          .



          Edit/AddIt: There is another way, with the advantage of then having a dynamic field that can be updated:



          1. Insert a normal NUMPAGES field somewhere and give it a white font or make it hidden

          2. Select the field, add a bookmark "numpages" covering this entire field

          3. Now add a Formula field with the formula =numpages-1

          Example:



          var hidField = RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES");
          hidField.Result.Bookmarks.Add("numpages");
          hidField.Result.Font.Hidden = 1;
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldFormula, "numpages-1");


          You might have to play around with the range variable so as to not overwrite your hidden field.






          share|improve this answer

























          • I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

            – Juan Carlos Rodriguez
            Mar 22 at 11:51











          • You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

            – LocEngineer
            Mar 22 at 12:04











          • @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

            – LocEngineer
            Mar 22 at 13:50















          1














          I don't think it will work this way. Entering braces into code does not work in any way.
          This, however, should do the trick just fine:



          doc.Variables.Add("myNumPages", doc.ComputeStatistics(Interop.WdStatistic.wdStatisticPages) - 1);
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldDocVariable, "myNumPages");


          .



          Edit/AddIt: There is another way, with the advantage of then having a dynamic field that can be updated:



          1. Insert a normal NUMPAGES field somewhere and give it a white font or make it hidden

          2. Select the field, add a bookmark "numpages" covering this entire field

          3. Now add a Formula field with the formula =numpages-1

          Example:



          var hidField = RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES");
          hidField.Result.Bookmarks.Add("numpages");
          hidField.Result.Font.Hidden = 1;
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldFormula, "numpages-1");


          You might have to play around with the range variable so as to not overwrite your hidden field.






          share|improve this answer

























          • I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

            – Juan Carlos Rodriguez
            Mar 22 at 11:51











          • You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

            – LocEngineer
            Mar 22 at 12:04











          • @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

            – LocEngineer
            Mar 22 at 13:50













          1












          1








          1







          I don't think it will work this way. Entering braces into code does not work in any way.
          This, however, should do the trick just fine:



          doc.Variables.Add("myNumPages", doc.ComputeStatistics(Interop.WdStatistic.wdStatisticPages) - 1);
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldDocVariable, "myNumPages");


          .



          Edit/AddIt: There is another way, with the advantage of then having a dynamic field that can be updated:



          1. Insert a normal NUMPAGES field somewhere and give it a white font or make it hidden

          2. Select the field, add a bookmark "numpages" covering this entire field

          3. Now add a Formula field with the formula =numpages-1

          Example:



          var hidField = RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES");
          hidField.Result.Bookmarks.Add("numpages");
          hidField.Result.Font.Hidden = 1;
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldFormula, "numpages-1");


          You might have to play around with the range variable so as to not overwrite your hidden field.






          share|improve this answer















          I don't think it will work this way. Entering braces into code does not work in any way.
          This, however, should do the trick just fine:



          doc.Variables.Add("myNumPages", doc.ComputeStatistics(Interop.WdStatistic.wdStatisticPages) - 1);
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldDocVariable, "myNumPages");


          .



          Edit/AddIt: There is another way, with the advantage of then having a dynamic field that can be updated:



          1. Insert a normal NUMPAGES field somewhere and give it a white font or make it hidden

          2. Select the field, add a bookmark "numpages" covering this entire field

          3. Now add a Formula field with the formula =numpages-1

          Example:



          var hidField = RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldExpression, "NUMPAGES");
          hidField.Result.Bookmarks.Add("numpages");
          hidField.Result.Font.Hidden = 1;
          RangeWord.Fields.Add(this.Range, Interop.WdFieldType.wdFieldFormula, "numpages-1");


          You might have to play around with the range variable so as to not overwrite your hidden field.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 13:49

























          answered Mar 22 at 11:23









          LocEngineerLocEngineer

          2,31211023




          2,31211023












          • I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

            – Juan Carlos Rodriguez
            Mar 22 at 11:51











          • You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

            – LocEngineer
            Mar 22 at 12:04











          • @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

            – LocEngineer
            Mar 22 at 13:50

















          • I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

            – Juan Carlos Rodriguez
            Mar 22 at 11:51











          • You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

            – LocEngineer
            Mar 22 at 12:04











          • @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

            – LocEngineer
            Mar 22 at 13:50
















          I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

          – Juan Carlos Rodriguez
          Mar 22 at 11:51





          I know the next question may seem offtopic but it's something I need to know... Are Variables references ? I mean if I decide to change my "myNumPages" variable (if it could be done), will it update all the fields which contain that variable?

          – Juan Carlos Rodriguez
          Mar 22 at 11:51













          You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

          – LocEngineer
          Mar 22 at 12:04





          You would have to recalculate the variable. I have just tried adding a few pages and then updating the field - no change. i.e. you must reassign the value to the variable, since it is static.

          – LocEngineer
          Mar 22 at 12:04













          @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

          – LocEngineer
          Mar 22 at 13:50





          @JuanCarlosRodriguez I have amended the code. The second version should be the way to go for you.

          – LocEngineer
          Mar 22 at 13:50



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55296822%2fhow-could-i-insert-a-formula-in-a-word-document-header%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript