sashu
sashu

Reputation: 1

How to understand the cast exception in automating Word from a VB code in Visual Studio?

I am developing a form application in the German Visual Studio 2019 that should automate Word using VB. In my VB project, I added a reference to the Microsoft.Office.Interop.Word.dll and can compile the application. To debug the application in VS, I use the code:

    Dim oWord As Microsoft.Office.Interop.Word.Application
    oWord = CreateObject("Word.Application")
    oWord.Visible = True

This trivial code should instantiate and show Word. However, I get the exception instead that Microsoft.Office.Interop.Word.ApplicationClass cannot be cast in Microsoft.Office.Interop.Word._Application

System.InvalidCastException: Das COM-Objekt des Typs "Microsoft.Office.Interop.Word.ApplicationClass" kann nicht in den Schnittstellentyp "Microsoft.Office.Interop.Word._Application" umgewandelt werden. Dieser Vorgang konnte nicht durchgeführt werden, da der QueryInterface-Aufruf an die COM-Komponente für die Schnittstelle mit der IID "{00020970-0000-0000-C000-000000000046}" aufgrund des folgenden Fehlers nicht durchgeführt werden konnte: Fehler beim Laden der Typbibliothek/DLL. (Ausnahme von HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))

As far as I understood, the reason is not quite clear. Some assume that the reason is installation of several Word versions that results in versions' incompatibility and the exception. To fix the problem, they suggest to delete double {00020970-0000-0000-C000-000000000046} items in the Windows register. I tried it, but the problem remains.

How do I fix the problem or does somebody has a similar sample automation project in VB (VB# or VC++) I can experiment with?

Upvotes: 0

Views: 420

Answers (2)

sashu
sashu

Reputation: 1

The reason of this exception was Windows with a corrupt registry.

Upvotes: 0

Mary
Mary

Reputation: 15091

At the top of the file...

Imports Microsoft.Office.Interop

Then create the object with the New keyword which calls the constructor.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim oWord As New Word.Application
    oWord.Visible = True
End Sub

Upvotes: 0

Related Questions