Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Filling in a docvariable in Word docx using C#

Status
Not open for further replies.

TiltingCode

Programmer
Apr 10, 2009
61
US
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:
Code:
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):
Code:
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;
It won't compile and here's the error I get which is located at the WordDocument.Variables("replace1") = "This is a test";. (Using the value property doesn't work either):

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


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

Any help will be greatly appreciated.
 
untested but have you tried square brackets?
Code:
WordDocument.Variables["replace2"].Value = "it's only a test!";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top