none
C# Word Automation Exception !!! RRS feed

  • Question

  • Hi,

    I am not pretty sure that this is the right place for this post, as I found this place :

    http://social.msdn.microsoft.com/Forums/en/worddev/threads

    But I think it is somehow C# related issue. Please point me ahead if needed.

    I am using the following code for Word Automation purpose :

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Office;
    using Microsoft.Office.Interop;
    using Word = Microsoft.Office.Interop.Word; 
    
    namespace WordAuTest
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Object oMissing = System.Reflection.Missing.Value;
                Object oTrue = true;
                Object oFalse = false;
                Word.Application oWord = new Word.Application();
                Word.Document oWordDoc = new Word.Document();
    
                oWord.Visible = true;
    
                Object oTemplatePath = System.Windows.Forms.Application.StartupPath + "\\testdot.dot";
    
                oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
    
                foreach (Word.Field myMergeField in oWordDoc.Fields)
                {
                    //iTotalFields++;
                    Word.Range rngFieldCode = myMergeField.Code;
                    String fieldText = rngFieldCode.Text;
    
                    if (fieldText.StartsWith(" MERGEFIELD"))
                    {
                        Int32 endMerge = fieldText.IndexOf("\\");
                        Int32 fieldNameLength = fieldText.Length - endMerge;
                        String fieldName = fieldText.Substring(11, endMerge - 11);
                        fieldName = fieldName.Trim();
                        if (fieldName == "name")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox1.Text);
                        }
    
                        if (fieldName == "phone")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox2.Text);
                        }
    
                        if (fieldName == "gender")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox3.Text);
                        }
                    }
                }
            }
        }
    }
    
    

    and I am getting the following execption:

     

    System.InvalidCastException was unhandled
      Message="Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."
      Source="Microsoft.Office.Interop.Word"
      StackTrace:
           at Microsoft.Office.Interop.Word.ApplicationClass.set_Visible(Boolean prop)
           at WordAuTest.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\MyPublicPC\My Documents\Visual Studio 2008\Projects\WordAuTest\WordAuTest\Form1.cs:line 30
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at WordAuTest.Program.Main() in C:\Documents and Settings\MyPublicPC\My Documents\Visual Studio 2008\Projects\WordAuTest\WordAuTest\Program.cs:line 18
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    
    

     

    I have already looked the following posts:

    http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/beb53a03-2545-493e-8ce4-c87d68e3777e/

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/1f6d4b5f-fc3d-4b1b-8446-0b7ba8d82e6d

     

    and I have already uninstalled Office 2010 and reinstalled office 2007. I have even deleted office 14 folder from drive and deleted office 14 entries in my regedit.

    And I still get the same exception.

    I am using MS. VS 2008 and office 2007 right now.

    Is the code I am using specific to Word 2003 Automation, because like I said before, I am using office 2007 ,,,and I have added references to Office 12 Object Library and Word 12 Object Library.

    Any thoughts or opinions.

    Thanks in advance.

    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    error massage text (if not shown properly above) :

    Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

    Friday, November 4, 2011 11:54 AM

All replies

  •  

    Hi,

    I am not pretty sure that this is the right place for this post, as I found this place :

    http://social.msdn.microsoft.com/Forums/en/worddev/threads

    But I think it is somehow C# related issue. Please point me ahead if needed.

     

    I am using the following code for Word Automation purpose :

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Office;
    using Microsoft.Office.Interop;
    using Word = Microsoft.Office.Interop.Word; 
    
    namespace WordAuTest
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Object oMissing = System.Reflection.Missing.Value;
                Object oTrue = true;
                Object oFalse = false;
                Word.Application oWord = new Word.Application();
                Word.Document oWordDoc = new Word.Document();
    
                oWord.Visible = true;
    
                Object oTemplatePath = System.Windows.Forms.Application.StartupPath + "\\testdot.dot";
    
                oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
    
                foreach (Word.Field myMergeField in oWordDoc.Fields)
                {
                    //iTotalFields++;
                    Word.Range rngFieldCode = myMergeField.Code;
                    String fieldText = rngFieldCode.Text;
    
                    if (fieldText.StartsWith(" MERGEFIELD"))
                    {
                        Int32 endMerge = fieldText.IndexOf("\\");
                        Int32 fieldNameLength = fieldText.Length - endMerge;
                        String fieldName = fieldText.Substring(11, endMerge - 11);
                        fieldName = fieldName.Trim();
                        if (fieldName == "name")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox1.Text);
                        }
    
                        if (fieldName == "phone")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox2.Text);
                        }
    
                        if (fieldName == "gender")
                        {
                            myMergeField.Select();
                            oWord.Selection.TypeText(textBox3.Text);
                        }
                    }
                }
            }
        }
    }
    
    

     


    and I am getting the following execption:

     

    System.InvalidCastException was unhandled
      Message="Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."
      Source="Microsoft.Office.Interop.Word"
      StackTrace:
           at Microsoft.Office.Interop.Word.ApplicationClass.set_Visible(Boolean prop)
           at WordAuTest.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\MyPublicPC\My Documents\Visual Studio 2008\Projects\WordAuTest\WordAuTest\Form1.cs:line 30
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at WordAuTest.Program.Main() in C:\Documents and Settings\MyPublicPC\My Documents\Visual Studio 2008\Projects\WordAuTest\WordAuTest\Program.cs:line 18
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    
    

     

     

    I have already looked the following posts:

    http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/beb53a03-2545-493e-8ce4-c87d68e3777e/

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/1f6d4b5f-fc3d-4b1b-8446-0b7ba8d82e6d

     

    and I have already uninstalled Office 2010 and reinstalled office 2007. I have even deleted office 14 folder from drive and deleted office 14 entries in my regedit.

    And I still get the same exception.

    I am using MS. VS 2008 and office 2007 right now.

    Any thoughts or opinions.

    Thanks in advance.

    =-=-=-=-=-=-=-=-=-=-=

    error massage text (if not shown properly above) :

    Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).


    • Edited by MyPuplicIdentity Friday, November 4, 2011 5:18 AM
    • Merged by Lie You Monday, November 7, 2011 8:55 AM Merge them to keep into the same topic for good discussion
    Friday, November 4, 2011 4:39 AM
  • This post has got really long.  :)

    Anyways,

    Is the code I am using specific to Word 2003 Automation, because like I said before, I am using office 2007 ,,,and.I have added references to Office 12 Object Library and Word 12 Object Library.

    Could this be the cause of the problem or what,

     


    Friday, November 4, 2011 8:05 AM
  • Hello,

     

    I think the problem is in this codeline:

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

    Try to use

    var oWord = new Word.Application();

    or try to cast to the correct type.

     

    Best regards,

    Silviu.


    http://www.rosoftlab.net/
    Friday, November 4, 2011 12:45 PM
  • Hello Lupu, thanks for reply.

    I edited the code with the suggestion you provided with no luck.

    The execption still appear in the same line which is:

    oWord.Visible = true;
    

    Thanks for your help again.

    Friday, November 4, 2011 12:58 PM
  • Hello,

     

    Try

    ((Microsoft.Office.Interop.Word._Application)oWord).Visible = true;

     

    Also, why are you using "Word." in the variables? Doesn`t it work without it because you have

    using Microsoft.Office.Interop;

    ?

    Best regards,

    Silviu.


    http://www.rosoftlab.net/
    Friday, November 4, 2011 1:10 PM
  • I've been using

                    Word.Application wordApp = new Word.Application();
                    wordApp.Visible = false;

    for ages without problem.

    You say you changed back from the version 14 PIAs to the version 12s when you went back to Word 2007. Have you definitely deleted the references to the version 14s? That's the only thing I can see that might be an issue.

    Friday, November 4, 2011 1:16 PM
  • Hello,

    I'd try to repair Office.


    Regards from Belarus (GMT + 2),

    Andrei Smolin
    Add-in Express Team Leader
    Friday, November 4, 2011 1:47 PM
  • I am going to try repairing office, and see what t ends with
    Friday, November 4, 2011 6:35 PM
  • Hello, Please point me if something wrong with my post, but please do not over look it.

    I am hopeless , and I had already started a thread here:

    http://social.msdn.microsoft.com/Forums/en/worddev/thread/81f887bf-2250-44e1-b518-8feae2921a9b?prof=required

    Thanks again.

    Friday, November 4, 2011 6:48 PM
  • I know you used regedit to remove Office 14, but stuff can be missed. You deleted from your HDD, but there could be duplicates. Like Silviu says, it's a little strange you have 'using Microsoft.Office.Interop' and also 'using Word = Microsoft.Office.Interop.Word'.

    Have you physically gone through the references in the Solution Explorer, right clicked the ones that begin with Microsoft.Office.Interop, and made sure they're not version 14? I may come across patronising if you have, and I apologise. It's just the one thing I can think off that would cause this.

    Friday, November 4, 2011 8:48 PM
  •  

    Hello MyPuplicIdentity,

    Welcome to the MSDN forum.

    Due to the weekend, we are very sorry for the later response.

    And I think this issue should be better support in the Word for Developers forum.

    I will merge them to keep into the same topic for good discussion.

    Thanks for your understanding and support.


    Best Regards,
    Rocky Yue[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, November 7, 2011 8:54 AM