none
Open an existing document RRS feed

  • Question

  • Imports Word = Microsoft.Office.Interop.Word
    Imports System.IO
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim myStream As Stream = Nothing
            Dim openFileDialog1 As New OpenFileDialog()
            openFileDialog1.InitialDirectory = "C:\Temp"
    
            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Try
                    myStream = openFileDialog1.OpenFile()
                    If (myStream IsNot Nothing) Then
                        Dim oWord As Word.Application
                        Dim oDoc As Word.Document
                        Dim oPara1 As Word.Paragraph
                        oWord = CreateObject("Word.Application")
                        oWord = New Word.Application
                        oWord.Visible = True
                        oDoc = oWord.Documents.Add
    
                        'Open an existing document.
                        oWord.Documents.Open(openFileDialog1.FileName, ReadOnly:=False)
                        oDoc = oWord.ActiveDocument
    
                        'Insert a paragraph at the beginning of the document.
                        oPara1 = oDoc.Content.Paragraphs.Add
                        oPara1.Range.Text = "Heading 1"
                        oPara1.Range.Font.Bold = True
                        oPara1.Format.SpaceAfter = 24    '24 pt spacing after paragraph.
                        oPara1.Range.InsertParagraphAfter()
                    End If
                Catch Ex As Exception
                    MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
                Finally
                    ' Check this again, since we need to make sure we didn't throw an exception on open.
                    If (myStream IsNot Nothing) Then
                        myStream.Close()
                    End If
                End Try
            End If
    
            'All done. Close this form.
            Me.Close()
    
        End Sub
    End Class
    As I run this code, Word document opens, but as read-only mode. How to enable edit document from code?
    • Edited by annee a Wednesday, November 15, 2017 7:52 AM
    Wednesday, November 15, 2017 1:02 AM

Answers

  • How to change this permission? Where may be mistake?
    When I try to upload document from defined location like:
    oWord.Documents.Open("C:\Temp\Sample.docx") 
    (code was a bit different - without OpenFileDialog)
    It opened as normal, non Read-only and made changes

     In your original posted code,  you are loading the document into a Stream before you are opening the document with Word.  That may have something to do with the 'Read Only' problem.  The Stream is not doing anything for you and is not needed at all.  You just want to open the document with the Word Application as shown in the example below.

     You also appear to be creating two word applications in a row for oWord,  you only need to create it once,  also shown in the example below.

     Note that you should also ALWAYS make sure you Close and release the COM objects when you are done using them in your application as shown in the example too.

     You can also look at the msdn documents on the Microsoft.Office.Interop.Word Namespace to read more details on the classes and interfaces and see what they are for and how they can be used.

     The example below will open an existing MS Word document that the user selects with an OpenFileDialog,  add a new paragraph to the beginning of the document,  set some of the paragraph's format and font properties,  then save it.

    Imports MsWord = Microsoft.Office.Interop.Word
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using ofd As New OpenFileDialog()
                ofd.Filter = "Word Document|*.doc;*.docx"
                ofd.FilterIndex = 1
    ofd.InitialDirectory = "C:\Testfolder" If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then Dim oWord As MsWord.Application = New MsWord.Application 'create a new Word Application oWord.Visible = True 'sets the Word Application's window to Visible Dim oDoc As MsWord.Document = oWord.Documents.Open(CObj(ofd.FileName)) 'open the user selected Word Document Dim oPara1 As MsWord.Paragraph = oDoc.Paragraphs.Add(oDoc.Paragraphs(1).Range) 'add a new Paragraph before the 1st Paragraph in the Word Document 'set up the font you want to use oPara1.Range.Font.Name = "Comic Sans MS" oPara1.Range.Font.Bold = 1 '1=True | 0=False oPara1.Range.Font.Size = 30 oPara1.Range.Font.Color = MsWord.WdColor.wdColorRed 'set the Text you want in this paragraph oPara1.Range.Text = "Heading 1" & Environment.NewLine 'add a new line character at the end of the text you insert oDoc.Save() 'save the document or use the SaveAs method to save it as a new document 'oDoc.SaveAs("C:\SomeFolder\MyMsDocument.docx") ReleaseComObject(oPara1) 'release the Paragraph Com Object oDoc.Close() 'close and release the Document Com Object ReleaseComObject(oDoc) oWord.Quit() 'close and release the Word Application Com Object ReleaseComObject(oWord) End If End Using Me.Close() End Sub Private Sub ReleaseComObject(obj As Object) System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing End Sub End Class

     

     And here is another spin-off of doing the same thing but,  just a little differently...

    Imports MsWord = Microsoft.Office.Interop.Word
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using ofd As New OpenFileDialog()
                ofd.Filter = "Word Document|*.doc;*.docx"
                ofd.FilterIndex = 1
                ofd.InitialDirectory = "C:\Testfolder"
    
                If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                    Dim oWord As MsWord.Application = New MsWord.Application 'create a new Word Application
                    oWord.Visible = True 'sets the Word Application's window to Visible. Set this to False if you don't want to see the word application
    
                    Dim oDoc As MsWord.Document = oWord.Documents.Open(CObj(ofd.FileName)) 'open the user selected Word Document
                    Dim oPara1 As MsWord.Paragraph = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\startofdoc").Range) 'use the default "StartOfDoc" bookmark to get the range to add the new paragraph
    
                    oPara1.Range.Font.Name = "Comic Sans MS"
                    oPara1.Range.Font.Bold = 1 '1=True | 0=False
                    oPara1.Range.Font.Size = 24
                    oPara1.Range.Font.Color = MsWord.WdColor.wdColorBlue
                    oPara1.Range.Font.Underline = MsWord.WdUnderline.wdUnderlineSingle
                    oPara1.Range.Text = "My Special Page Heading" & Environment.NewLine
                    oPara1.SpaceAfter = 40
                    oPara1.Range.InsertParagraphAfter()
    
                    oDoc.Save()
    
                    ReleaseComObject(oPara1)
                    oDoc.Close()
                    ReleaseComObject(oDoc)
                    oWord.Quit()
                    ReleaseComObject(oWord)
                End If
            End Using
            Me.Close()
        End Sub
    
        Private Sub ReleaseComObject(obj As Object)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    Wednesday, November 15, 2017 5:45 PM
  •  Look back into your first question about this topic (link below) and go through the links i gave you in my first post there.  The last link i gave you (Working with Word document content objects) shows all kinds of VB.Net examples on how to iterate through Pages, Paragraphs, Sentences, and Words and getting the Range object of them.

     Once you have the Range object of the Paragraph, Sentence, Word,  or whatever you want to change,  you can set the font, font color, or other formatting options in the same way i showed in my above example to set the Paragraph.Range.Font properties.

    Open edited Word document


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Tuesday, November 28, 2017 2:08 AM
    • Marked as answer by annee a Tuesday, November 28, 2017 7:07 AM
    Tuesday, November 28, 2017 1:44 AM

All replies

  • Hello,

    I try to test your code and I find this error message:

    And I try to change the file, then it can save.

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 15, 2017 9:33 AM
    Moderator
  • How to change this permission? Where may be mistake?
    When I try to upload document from defined location like:
    oWord.Documents.Open("C:\Temp\Sample.docx") 
    (code was a bit different - without OpenFileDialog)
    It opened as normal, non Read-only and made changes

    • Edited by annee a Wednesday, November 15, 2017 11:00 AM
    Wednesday, November 15, 2017 10:54 AM
  • How to change this permission? Where may be mistake?
    When I try to upload document from defined location like:
    oWord.Documents.Open("C:\Temp\Sample.docx") 
    (code was a bit different - without OpenFileDialog)
    It opened as normal, non Read-only and made changes

     In your original posted code,  you are loading the document into a Stream before you are opening the document with Word.  That may have something to do with the 'Read Only' problem.  The Stream is not doing anything for you and is not needed at all.  You just want to open the document with the Word Application as shown in the example below.

     You also appear to be creating two word applications in a row for oWord,  you only need to create it once,  also shown in the example below.

     Note that you should also ALWAYS make sure you Close and release the COM objects when you are done using them in your application as shown in the example too.

     You can also look at the msdn documents on the Microsoft.Office.Interop.Word Namespace to read more details on the classes and interfaces and see what they are for and how they can be used.

     The example below will open an existing MS Word document that the user selects with an OpenFileDialog,  add a new paragraph to the beginning of the document,  set some of the paragraph's format and font properties,  then save it.

    Imports MsWord = Microsoft.Office.Interop.Word
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using ofd As New OpenFileDialog()
                ofd.Filter = "Word Document|*.doc;*.docx"
                ofd.FilterIndex = 1
    ofd.InitialDirectory = "C:\Testfolder" If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then Dim oWord As MsWord.Application = New MsWord.Application 'create a new Word Application oWord.Visible = True 'sets the Word Application's window to Visible Dim oDoc As MsWord.Document = oWord.Documents.Open(CObj(ofd.FileName)) 'open the user selected Word Document Dim oPara1 As MsWord.Paragraph = oDoc.Paragraphs.Add(oDoc.Paragraphs(1).Range) 'add a new Paragraph before the 1st Paragraph in the Word Document 'set up the font you want to use oPara1.Range.Font.Name = "Comic Sans MS" oPara1.Range.Font.Bold = 1 '1=True | 0=False oPara1.Range.Font.Size = 30 oPara1.Range.Font.Color = MsWord.WdColor.wdColorRed 'set the Text you want in this paragraph oPara1.Range.Text = "Heading 1" & Environment.NewLine 'add a new line character at the end of the text you insert oDoc.Save() 'save the document or use the SaveAs method to save it as a new document 'oDoc.SaveAs("C:\SomeFolder\MyMsDocument.docx") ReleaseComObject(oPara1) 'release the Paragraph Com Object oDoc.Close() 'close and release the Document Com Object ReleaseComObject(oDoc) oWord.Quit() 'close and release the Word Application Com Object ReleaseComObject(oWord) End If End Using Me.Close() End Sub Private Sub ReleaseComObject(obj As Object) System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing End Sub End Class

     

     And here is another spin-off of doing the same thing but,  just a little differently...

    Imports MsWord = Microsoft.Office.Interop.Word
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using ofd As New OpenFileDialog()
                ofd.Filter = "Word Document|*.doc;*.docx"
                ofd.FilterIndex = 1
                ofd.InitialDirectory = "C:\Testfolder"
    
                If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                    Dim oWord As MsWord.Application = New MsWord.Application 'create a new Word Application
                    oWord.Visible = True 'sets the Word Application's window to Visible. Set this to False if you don't want to see the word application
    
                    Dim oDoc As MsWord.Document = oWord.Documents.Open(CObj(ofd.FileName)) 'open the user selected Word Document
                    Dim oPara1 As MsWord.Paragraph = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\startofdoc").Range) 'use the default "StartOfDoc" bookmark to get the range to add the new paragraph
    
                    oPara1.Range.Font.Name = "Comic Sans MS"
                    oPara1.Range.Font.Bold = 1 '1=True | 0=False
                    oPara1.Range.Font.Size = 24
                    oPara1.Range.Font.Color = MsWord.WdColor.wdColorBlue
                    oPara1.Range.Font.Underline = MsWord.WdUnderline.wdUnderlineSingle
                    oPara1.Range.Text = "My Special Page Heading" & Environment.NewLine
                    oPara1.SpaceAfter = 40
                    oPara1.Range.InsertParagraphAfter()
    
                    oDoc.Save()
    
                    ReleaseComObject(oPara1)
                    oDoc.Close()
                    ReleaseComObject(oDoc)
                    oWord.Quit()
                    ReleaseComObject(oWord)
                End If
            End Using
            Me.Close()
        End Sub
    
        Private Sub ReleaseComObject(obj As Object)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    Wednesday, November 15, 2017 5:45 PM
  • Is there any function to open/read from file and change formatting (size, colour) on existing text in file?

    annee

    Tuesday, November 28, 2017 12:36 AM
  • Is there any function to open/read from file and change formatting (size, colour) on existing text in file?

    You are probably referring to a Word document, not a text file.  See:
    https://msdn.microsoft.com/en-us/library/kw65a0we.aspx

    Tuesday, November 28, 2017 1:08 AM
  •  Look back into your first question about this topic (link below) and go through the links i gave you in my first post there.  The last link i gave you (Working with Word document content objects) shows all kinds of VB.Net examples on how to iterate through Pages, Paragraphs, Sentences, and Words and getting the Range object of them.

     Once you have the Range object of the Paragraph, Sentence, Word,  or whatever you want to change,  you can set the font, font color, or other formatting options in the same way i showed in my above example to set the Paragraph.Range.Font properties.

    Open edited Word document


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Tuesday, November 28, 2017 2:08 AM
    • Marked as answer by annee a Tuesday, November 28, 2017 7:07 AM
    Tuesday, November 28, 2017 1:44 AM