Forum Discussion

begizorrotz's avatar
begizorrotz
Copper Contributor
Jul 28, 2021
Solved

Word automation fails

Years ago I wrote an application in VB.NET that opens Word documents to make certain corrections to them, and it has been running smoothly until now. The code is as follows:   Imports Microsoft.Of...
  • begizorrotz's avatar
    Aug 08, 2021

    This is not a solution, but...

    I have proceeded to change the declarations of the variables, as follows:

    Before:

    Friend WithEvents oWord As Word.Application
    Friend WithEvents oDoc As Document

    Now:

    Friend WithEvents oWord As Object
    Friend WithEvents oDoc As Object

    In the same way, I've modified the word and document application mapping code, as follows:

    Before:

    oWord = CreateObject("Word.Application")
    oWord.Visible = True
    oDoc = oWord.Documents.Open(Trim(Main.docName.Text), varMissing, varMissing,
    varMissing, varMissing, varMissing, varMissing, varMissing,
    varMissing, varMissing, varMissing, varMissing, varMissing,
    varMissing, varMissing, varMissing)

    Now:

    oword = ctype(createobject("word.application"), microsoft.office.interop.word.application)
    oDoc = CType(oWord.Documents.Open(Main.docName.Text, varMissing, varMissing,
    varMissing, varMissing, varMissing, varMissing, varMissing,
    varMissing, varMissing, varMissing, varMissing, varMissing,
    varMissing, varMissing, varMissing), Microsoft.Office.Interop.Word.Document)

    with the result that it works. But with the change I lost the ability to handle the "DocumentBeforeClose" event, which prevented the document from being closed outside the control of the application.

    Additionally, the following code, (which previously did not produce any error)

    rngParagraphs = oWord.ActiveDocument.Range(Start:=oWord.ActiveDocument.Paragraphs(1). Range.Start, End:=oWord.ActiveDocument.Paragraphs(oWord.ActiveDocument.Paragraphs.Count). Range.End)

    causes the "Count is read-only" error.

    But replacing it with:

    Dim nParg As Single = oWord.ActiveDocument.Paragraphs.Count
    rngParagraphs = oWord.ActiveDocument.Range(Start:=oWord.ActiveDocument.Paragraphs(1). Range.Start, End:=oWord.ActiveDocument.Paragraphs(nParg). Range.End)

    or what is the same, substituting .Activedocument.Paragraphs.Count for a variable in which the content has previously been loaded, works perfectly, which perplexes me.

    He said that this is not a solution, just a palliative with problems. But I wanted to close the consultation with some more information.

Resources