Programming Word from Visual Basic RRS feed

  • Question

  • I use VB in VS2010.

    I am trying to program word (Word 2010 ver.14) with the following simple program.

    Imports Microsoft.Office.Interop.Word
    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim wrdApp = New Microsoft.Office.Interop.Word.Application
            Dim wrdDoc = New Microsoft.Office.Interop.Word.Document

            wrdApp.Visible = True
            wrdDoc = wrdApp.Documents.Add
            Dim wrdSelection = wrdApp.Selection()
            Dim Filename As String = "c:\Hello"
                wrdDoc.SaveAs(Filename, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument)
            Catch ex As Exception
            End Try

        End Sub
    End Class

    The document is created successfully but the SaveAs fails with the error message

    "Word cannot save or create this file. Make sure that the disk you want to save the file on is not full, write-protected, or damaged."

    There is nothing wrong with the disk! It is in regular use saving far larger programs than this and there is 1.6GB of free space on it.

    Any suggestions???


    Also I have another program (15000+ lines) with a similar code.
    Sometimes it works; at other times it fails with an RTC_E_* error.
    Apparently this is a recognised problem (something to do with thread contention) but although I have searched forums and elsewhere I cannot find a resolution.
    Any ideas on this one?
    Thanks again


    Monday, June 24, 2013 12:20 PM


  • Don't use the New keyword for a Document object. This line of code is incorrect and will cause problems:

    Dim wrdDoc = New Microsoft.Office.Interop.Word.Document

    Instead, use:

    Dim wrdDoc as Word Document = wrdApp.Documents.Add

    I also recommend you do some research into how to effectively use Word's object model. The Selection object is not the optimal way to work with document content. You should use the Range object whenever possible.

    Cindy Meister, VSTO/Word MVP, my blog

    Monday, June 24, 2013 3:35 PM