Ryan Pearson
Ryan Pearson

Reputation: 23

System.Runtime.InteropServices.COMException when I run this Interop code with word

When I run this code to take the text off a word document it ends with multiple System.Runtime.InteropServices.COMException 's

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If Origcv = "" Then
        Label10.Text = "Select a CV"
    Else
        ' Create application instance.
        Dim app As Application = New Application

        ' Open specified file.
        Dim doc As Document = app.Documents.Open(Origcv)

        ' Loop through all words.
        Dim count As Integer = doc.Words.Count
        Dim cvw(count) As String
        For i As Integer = 1 To count
            ' Write word to screen.
            Dim text As String = doc.Words(i).Text

            cvw(i) = doc.Words(i).Text
        Next
        ' Quit the application.
        app.Quit()

The errors all come on the doc.words(I).text even though the .count has succeeded. I have installed all components of word and .net and still can't get this to work. I used to have it working fine when I used the same code before on my laptop before it was factory reset so I assume I am missing some kind of component or setting, the interop.word reference is recognized and has the file path on the references tab. Any help here need to get this finished quickly and this is literally the first hurdle.

Any help appreciated

Upvotes: 0

Views: 2458

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25693

I believe your problem is Dim app As Application = New Application This kind of construct is always dangerous. Many namespaces use Application - you have no qualifier that tells .NET which application is meant. The fact that Documents.Open works could also be because the namespace .NET is referencing also has a Documents class.

If you fully qualify it:

Dim app As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application()

I believe the problem will go away.

If it does, put an Imports at the top of the module that assigns an Alias to the namespace then use the Alias to qualify objects in the Word namespace (makes things shorter):

Imports Word = Microsoft.Office.Interop.Word

Then

Dim app as Word.Application = New Word.Application()
Dim doc as Word.Document = app.Documents.Open(Origcv)

Upvotes: 2

Related Questions