Search code examples
c#.netms-wordoffice-interopoffice-automation

C# Why do I get a compiler error Word.Application when I have a reference to MS.Office.Interop


I have a strange compiler error that I the name "Word" cannot be found in my namespace. Yet, I have using Microsoft.Office.Interop; and I added also using Microsoft.Office.Interop.Word; just to be sure.

So I use this line of code:

using Microsoft.Office;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;

Word.Application oWord = new Word.Application();

But I still get the compiler error:

The type or namespace name 'Word' could not be found (are you missing a using directive or an assembly reference?)

This happens regardless of the examples I see on msdn or else are word for word the same (no pun intended ☺).

So I have to put in the reference in the code:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

Can anybody advise me why is this or what I am doing wrong? Thanks in advance.


Solution

  • The fully qualified type name is Microsoft.Office.Interop.Word.Application, and when you use a using directive (using Microsoft.Office.Interop.Word) that will let you alias the fully qualified type using just the name Application. Be aware that Application is a common name in various frameworks, and it may not be possible to use when the type name exists in other namespaces. This will result in an ambiguous error.

    You can also use an alias statement to provide a work-around with the multiple type name I mention above.

    using WordApplication = Microsoft.Office.Interop.Word.Application;
    

    If you needed to provide integration to multiple Office Interops, this could work by adding another statement.

    using ExcelApplication = Microsoft.Office.Interop.Excel.Application;