Невозможно привести com объект типа microsoft office interop word applicationclass

Пытаюсь запустить простейший код консольного приложения:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;

namespace ConsoleAppTestWord
{
    class Program
    {
        static void Main(string[] args)
        {
            Application app = new Application();
            Document doc = app.Documents.Add(Visible:true);
            doc.Save();
            doc.Close();
            app.Quit();

        }
    }
}

На строке Document doc = app.Documents.Add(Visible:true); выдает ошибку:

Невозможно привести COM-объект типа
«Microsoft.Office.Interop.Word.ApplicationClass» к интерфейсному типу
«Microsoft.Office.Interop.Word._Application».

Что я делаю не так?

Vadim Ovchinnikov's user avatar

задан 24 апр 2018 в 4:09

Генрих's user avatar

8

Проблема в том какие версии установлены у вас на машине и что прописано в реестре ключей Windows.

  1. Найди версию Office прописанную в реестре Windows

Для 64bit Office ищи тут:
HKEY_CLASSES_ROOTWOW6432NodeInterface[00020970-0000-0000-C000-000000000046]TypeLib

Для 32bit Office ищи тут:
HKEY_CLASSES_ROOT Interface[00020970-0000-0000-C000-000000000046]TypeLib

Поиск ключа версии Office

  1. Найди ключ в этом каталоге

HKEY_CLASSES_ROOT WOW6432Node TypeLib[the TypeLib ID you just found].
Поиск ключа 2

  1. Убедись что версии в обоих каталогах совпадают и в ключе №2 прописана только одна! версия.

Оригинал статьи тут: https://social.msdn.microsoft.com/Forums/vstudio/en-US/d34c4f78-46f3-478e-9c44-95ea8461e46f/unable-to-cast-com-object-of-office-interop-word?forum=vsto

ответ дан 10 мая 2018 в 18:32

Rustem Bayetov's user avatar

1

  • Hi,

    >>Unable to cast COM object of type ‘Microsoft.Office.Interop.Word.ApplicationClass’ to interface type ‘Microsoft.Office.Interop.Word._Application’.

    This problem is caused by incorrect COM Interop settings in the Windows registry. This can be caused by installing a newer version of Microsoft
    Office, and then removing it and installing an older version instead.

    You should check the version of registry key is 8.6 in:

    64bit Office:

    HKEY_CLASSES_ROOTWOW6432NodeInterface[00020970-0000-0000-C000-000000000046]TypeLib

    32bit Office:

    HKEY_CLASSES_ROOT Interface[00020970-0000-0000-C000-000000000046]TypeLib

    And the then browse to the registry key HKEY_CLASSES_ROOT WOW6432Node TypeLib[the TypeLib ID you just found].

    In this key,
    there should only be 1 subkey, and it should be the same as the Version value you found previously.If this key contains mutiple subkeys, you should remove it from registry.

    To resolve this problem, you can also repair Microsoft Office 2013. To do this, follow these steps:

    1. Click on your Start menu and open the Control Panel

    2. Click on Uninstall a Program (or Add/Remove programs in Windows XP)

    3. Locate the entry for Microsoft Office and click on it. After you click on it, you should see a button labeled Change appear either next to it, or at the top of the
    list (depending on what version of Windows you have). Click this Change button.

    4. Once Microsoft Office setup appears, choose the Repair option and click Next to have Microsoft Office repair itself. You may need to reboot your computer once this
    process is complete; Microsoft Office setup will tell you if you need to do this once it is done.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Edited by

      Tuesday, March 25, 2014 9:36 AM

    • Marked as answer by
      Marvin_Guo
      Monday, March 31, 2014 12:01 PM

  • My application has a feature to export to Microsoft Word, but it hasn’t worked since I’ve upgraded from Microsoft Office 2010 to Microsoft Office 2013.

    Here is the code:

    Microsoft.Office.Interop.Word.Application appVersion = new Microsoft.Office.Interop.Word.Application();
    appVersion.Visible = false;
    

    and this is the error 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)).

    Someone told me to edit the registry, but the IID «{00020970-0000-0000-C000-000000000046}» does not exist in my registry.

    Air's user avatar

    Air

    8,1162 gold badges50 silver badges85 bronze badges

    asked Mar 12, 2014 at 2:00

    aiyagaze's user avatar

    1

    Running a repair installation of Office usually resolves that issue.

    answered Mar 20, 2014 at 11:47

    cremor's user avatar

    cremorcremor

    6,5391 gold badge29 silver badges72 bronze badges

    1

    I switched from using Word Interop to using Late Binding. Quick fix that didn’t affect refactoring a lot of code…

    Before:

    OfficeWord.Application msword = new OfficeWord.Application();
    

    After:

    Type wordType = Type.GetTypeFromProgID("Word.Application");
    dynamic msword = Activator.CreateInstance(wordType);
    

    Solved my issues on a bunch of corporate computers that started seeing this problem after an Office upgrade by Client Support.

    Matt Ke's user avatar

    Matt Ke

    3,47912 gold badges31 silver badges48 bronze badges

    answered Jun 22, 2020 at 17:02

    Popeye's user avatar

    2

    I had the exact same problem and reinstalling Office 2013 solved my issue.

    answered Aug 15, 2015 at 5:05

    Alex Jolig's user avatar

    Alex JoligAlex Jolig

    14k20 gold badges137 silver badges167 bronze badges

    Old question, however I ran into the same thing, same exact error message when trying to create a new word application. The problem was simple, once I closed VS in frustration and went to do other work. When I opened word, it had retrieved documents that had not been saved when Word closed down and wanted to know what I wanted to do with them. I told it to delete them, closed word and my code worked fine. Still working on a way around this but I thought I would drop this in here to save someone else from reinstalling office when it was something simple.

    answered Sep 3, 2020 at 16:04

    Kassabba's user avatar

    KassabbaKassabba

    3404 silver badges15 bronze badges

    • Remove From My Forums
    • Вопрос

    • Добрый день!

      Есть скрипт на powershell, который должен открыть документ Word и внести там кое-какие правки.
      Система Windows 8.1, в системе установлен MS Office 2010.

      При выполнении строки $MSWord = New-Object -ComObject word.application
      в переменной нет объекта — она пуста.

      Соответственно, в строчке $MSWord.documents.open($fullPath) происходит ошибка «Невозможно вызвать метод для выражения со значением NULL».

      Подскажите, куда копать, что надо сделать, чтобы объект создавался?

      • Изменено

        19 августа 2014 г. 8:58

      • Перемещено
        Elina Lebedeva
        19 августа 2014 г. 9:10

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    
    void sgfg(string name)
            {
                plus();
                try
                {
                    //name = @"C:Otch.doc";
             Microsoft.Office.Interop.Word.Application wordapp=new Microsoft.Office.Interop.Word.ApplicationClass();
            Word.Document worddocument;
            object misValue = System.Reflection.Missing.Value;
        //  wordapp.Visible=true;
            plus();
             Object template = Type.Missing;
     Object newTemplate = false;
     Object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
     Object visible = true; 
    plus();
     worddocument= wordapp.Documents.Add( ref template, ref newTemplate, ref documentType, ref visible);
     Word.Paragraphs wordparagraphs;
     Word.Paragraph  wordparagraph;
     wordparagraphs=worddocument.Paragraphs;
    plus();
     object oMissing = System.Reflection.Missing.Value;
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      plus();
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      plus();
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      plus();
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing); worddocument.Paragraphs.Add(ref oMissing); worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      worddocument.Paragraphs.Add(ref oMissing);
      //  worddocument.Paragraphs.Add(ref oMissing);         
    plus();
    wordparagraph=(Word.Paragraph)wordparagraphs[1];
      wordparagraph.Range.Text=Tipusil1;  
      if(g1==1)
      {
    Form2 f=new Form2();
    Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==2)
      {
        Shema2 f=new Shema2();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
       if (g1==3)
      {
        Shema3 f=new Shema3();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
       plus();
    if (g1==4)
      {
        Shema4 f=new Shema4();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==5)
      {
        Shema5 f=new Shema5();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==6)
      {
        Shema6 f=new Shema6();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==7)
      {
        Shema7 f=new Shema7();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==8)
      {
        Shema8 f=new Shema8();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
      if (g1==9)
      {
        Shema9 f=new Shema9();
        Clipboard.SetImage(f.pictureBox1.Image);
    f.Close();
      }
      plus();
    wordapp.ActiveDocument.Paragraphs[2].Range.Paste();
    Clipboard.Clear();
    wordparagraph=(Word.Paragraph)wordparagraphs[3];
      wordparagraph.Range.Text="ХАРАКТЕРИСТИКИ:";  
      worddocument.Content.ParagraphFormat.Alignment=Word.WdParagraphAlignment.wdAlignParagraphCenter;
      wordparagraph=(Word.Paragraph)wordparagraphs[4];
        wordparagraph.Range.Text="Напряжение выхода : "+TEMPNapvyh1+" "+TEMPNapvyhRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
        wordparagraph=(Word.Paragraph)wordparagraphs[5];
    wordparagraph.Range.Text="Коэффициент усиления : "+TEMPKoefUs1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft; 
     
    wordparagraph=(Word.Paragraph)wordparagraphs[6];
    wordparagraph.Range.Text="Частота : "+TEMPChast1+" "+TEMPChastRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
     wordparagraph=(Word.Paragraph)wordparagraphs[7];
    wordparagraph.Range.Text="Фаза : "+TEMPFaza1+" "+TEMPFazaRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
      wordparagraph=(Word.Paragraph)wordparagraphs[8];
    wordparagraph.Range.Text="Напряжение : "+TEMPNap1+" "+TEMPNapRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
       wordparagraph=(Word.Paragraph)wordparagraphs[9];
    wordparagraph.Range.Text="Резистор R1 : "+TEMPR11+" "+TEMPR1Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
         
    int chis=10;
        if(g1==1|g1==2|g1==7)
        { 
             wordparagraph=(Word.Paragraph)wordparagraphs[10];
    wordparagraph.Range.Text="Резистор R2 : "+TEMPR21+" "+TEMPR2Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
        
         chis=11;
        }
          if(g1==3)
        {
         wordparagraph=(Word.Paragraph)wordparagraphs[10]; 
     wordparagraph.Range.Text="Резистор R2 : "+TEMPR21+" "+TEMPR2Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
           wordparagraph=(Word.Paragraph)wordparagraphs[11];    
    wordparagraph.Range.Text="Резистор R3 : "+TEMPR31+" "+TEMPR3Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
         wordparagraph=(Word.Paragraph)wordparagraphs[12];
         wordparagraph.Range.Text="Резистор Roc : "+TEMPRoc1+" "+TEMPRocRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
        // wordparagraph=(Word.Paragraph)wordparagraphs[13];
         chis=12;
        }
            if(g1==4|g1==5)
        {
    wordparagraph=(Word.Paragraph)wordparagraphs[10];           
    wordparagraph.Range.Text="Конденсатор C1 : "+TEMPC11+" "+TEMPC1Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
         
         chis=11;
        }
         if(g1==9)
        { 
              wordparagraph=(Word.Paragraph)wordparagraphs[10];
    wordparagraph.Range.Text="Напряжение диода : "+TEMPNapd1+" "+TEMPNapdRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
       
         chis=11;
        }   
         if(g1==7)
        {  wordparagraph=(Word.Paragraph)wordparagraphs[10];
            wordparagraph.Range.Text="Напряжение диода : "+TEMPNapd1+" "+TEMPNapdRads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
        wordparagraph=(Word.Paragraph)wordparagraphs[11];
    wordparagraph.Range.Text="Напряжение второй точки : "+TEMPNap21+" "+TEMPNap2Rads1;
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphLeft;
         
         chis=12;
        }
         
        
         chis=wordparagraphs.Count; 
    Clipboard.SetImage(fff1);
    wordapp.ActiveDocument.Paragraphs[chis].Range.Paste();
    Clipboard.Clear();
    wordparagraph=(Word.Paragraph)wordparagraphs[chis];
    wordparagraph.Format.Alignment=Word.WdParagraphAlignment.wdAlignParagraphCenter;
     
     
     //Подготавливаем параметры для сохранения документа
      worddocument.SaveAs(name,Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing,  Type.Missing, 
      Type.Missing,  Type.Missing,  Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing,  Type.Missing,Type.Missing);
     
            
        Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
        Object originalFormat = Word.WdOriginalFormat.wdWordDocument;
        Object routeDocument = Type.Missing;
        
      
        worddocument.Close(ref saveChanges,ref originalFormat, ref routeDocument);
        wordapp.Quit(ref saveChanges,ref originalFormat, ref routeDocument);
        releaseObject(wordapp);
        wordapp = null;
      
        
        this.Hide();
        MessageBox.Show("Файл успешно сохранен!","Сохранение",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
                catch { MessageBox.Show("Ошибка при сохранении! Попробуйте еще раз!","Сохранение",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    this.Close();};
            //g1=1; 
            this.Close();
            }

    Понравилась статья? Поделить с друзьями:
  • Невозможно привести com объект типа microsoft office interop excel applicationclass
  • Невозможно привести com объект типа excel applicationclass к интерфейсному типу excel application
  • Невозможно получить доступ к excel файлу
  • Невозможно подключиться к microsoft excel driver 1с
  • Невозможно переместить ячейки в таблице или диапазоне с примененным фильтром excel