Using Word 2003 Document Variables with C#

Q

Quique

I am trying to use Word 2003 Document Variables in a C#
program.
I have added two references to my .Net project:

* Office 11 object library
* Word 11 object library

My code is something that:

....
object varName = (object)"myVariable";
Variable myVar;
myVar = WordApplication.ActiveDocument.Variables[varName];
....

Compiler generates a message like this:

.... language doesn't allows property or indexer this ...

I try to use similar collections like Selection.Fields and
it works fine.

I think that it's a bug in the MSWORD.OLB file or in the
tlibimp.exe program.

Please, help me
 
C

Cindy M -WordMVP-

Hi Quique,

Note that about all I know about C# is that it exists :)
However, I'm guessing that your problem may be that the
document variables may not yet exist. A document variable
(very old construct, from the old WordBasic days) *requires*
a value. No value, the no document variable - Word destroys
it.

So, you have to assign it a value (and that can't be a
zero-length string, either). Try using the ADD method of the
collection to assign a name and value to the object.
I am trying to use Word 2003 Document Variables in a C#
program.
I have added two references to my .Net project:

* Office 11 object library
* Word 11 object library

My code is something that:

....
object varName = (object)"myVariable";
Variable myVar;
myVar = WordApplication.ActiveDocument.Variables[varName];
....

Compiler generates a message like this:

.... language doesn't allows property or indexer this ...

I try to use similar collections like Selection.Fields and
it works fine.

Cindy Meister
INTER-Solutions, Switzerland
http://homepage.swissonline.ch/cindymeister (last update Sep
30 2003)
http://www.mvps.org/word

This reply is posted in the Newsgroup; please post any follow
question or reply in the newsgroup and not by e-mail :)
 
C

Chango V.

We had the same problem. Apparently the Variables collection object's quirks
and faults carry into the .NET world... The Primary Interop Assemblies may
solve the problem, but here's how we patched it (late binding):

Type varsType = wdDocument.Variables.GetType();
object[] args = new object[1];
args[0] = "DocTypeName";
Word.Variable dtVar = (Word.Variable) varsType.InvokeMember("Item",
BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null,
wdDocument.Variables, args);

Ugly but it works...

Good luck.

//
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top