Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling in a docvariable in Word docx using C#

I've done this a hundred times in VB 6 but it's driving me nuts using C# 2008 and Word 2007. I created a docx file with two docvariables:

Some text here....

{docvariable replace1}
{docvariable replace2}

More text here......

I created a macro first to do it and it works:

Sub FillDocVariable()
'
' FillDocVariable Macro
'
'

  ActiveDocument.Variables("replace1").Value = "This is a test"
  ActiveDocument.Variables("replace2").Value = "it is only a test."
  ActiveDocument.Fields.Update

End Sub

Here's my C# code (mind you I'm learning this as I go):

using Microsoft.Office.Interop.Word;
 object paramMissing = Type.Missing;
       object openfileName = @"C:\testing\Documents\1.docx";

      ApplicationClass WordApplication = new ApplicationClass();
      Document WordDocument = WordApplication.Documents.Open(ref openfileName, 
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing);

      WordDocument.Variables("replace1") = "This is a test";
      WordDocument.Variables("replace2").Value = "it's only a test!";
      WordDocument.Fields.Update;

Here's the error I get:

Error 1 Non-invocable member 'Microsoft.Office.Interop.Word._Document.Variables' cannot be used like a method. Blockquote

like image 398
Norm Avatar asked Sep 05 '10 17:09

Norm


2 Answers

If you're interested, the way to do this via VS 2010 & Word 2010 is as follows:

Application app = new Application();
Document doc = word.Documents.Add(filepath);
doc.Variables["var_name"].Value = your_value_here;
doc.Fields.Update();
doc.Save();
doc.Close();
app.Quit();
like image 93
Jay Avatar answered Oct 14 '22 07:10

Jay


I think that you missed a ".value" in your code...

WordDocument.Variables("replace1") = "This is a test";

should be written as:

WordDocument.Variables("replace1").Value = "This is a test";
like image 32
Serge Lavoie Avatar answered Oct 14 '22 06:10

Serge Lavoie