When creating MailingLabel documents in Word (in my case version 2010) I can no longer save changes to the original Word document.
The following code demonstrates the issue:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim wordApp As Word.Application
Dim wordDoc As Word.Document
Dim wordLabel As Word.Document
Try
'Start Word:
wordApp = New Word.Application
'Add and save a document with 'Any text':
wordDoc = wordApp.Documents.Add
wordDoc.Range.Text = "Any text"
wordDoc.SaveAs("C:\Users\User\AppData\Local\Temp\Worddocument.docx")
'Create a mailinglabel document based on an existing 'label':
wordLabel = wordApp.MailingLabel.CreateNewDocument("label", "", "", False, 0, False, False)
'Code for printing the label goes here......
wordLabel.Close(False)
'Change, save, close and re-open the document:
wordDoc.Range.Text = "Another text"
wordDoc.Save() 'THIS FIRST SAVE WORKS CORRECTLY
wordDoc.Close(False)
wordDoc = wordApp.Documents.Open("C:\Users\User\AppData\Local\Temp\Worddocument.docx")
'Again create a mailinglabel document based on an existing 'label':
wordLabel = wordApp.MailingLabel.CreateNewDocument("label", "", "", False, 0, False, False)
'Code for printing the label goes here......
wordLabel.Close(False)
'Change and save the document:
wordDoc.Range.Text = "Again another text"
wordDoc.Save() 'THIS SECOND SAVE GENERATES THE ERROR 'Word cannot complete the save due to a file permission error'
Catch ex As Exception
MsgBox(ex.Message)
Finally
wordLabel.Close(False)
wordDoc.Close(False)
wordApp.Quit(False)
End Try
End Sub
After generating the first labeldocument the wordDoc is changed, saved, closed and re-opend. This save works correctly.
Then a labeldocument is generated a second time. And the following document change and subsequent save will generate the error.
It lookes like wordLabel is changing something in wordDoc that prevents it from proper saving, but I cannot find any reason for that. I do close the wordLabel but that does not help either.
Two things are essential for this error to occur:
- the in between closing and re-opening of wordDoc;
- the renewed creation of wordLabel.
If one of them is omitted the save will work correctly.
Can anyone think of a reason and how this can be avoided?