MS Word runs on background and requests documents to be saved even though it is already saved - vb.net

I have a procedure that creates a PDF file according to an ms word template and its data is retrieved from a database.
It works fine, creates a PDF file perfectly , no run time errors. The problem is that whenever I shut off the computer, ms word prevents the shutdown and if I press cancel ms word shows a message;
The code goes like this;
Dim wordApp As Word.Application
Dim templateBookmarks As Word.Bookmarks
Dim templateName As String
Dim template As Word.Document
'Some other variables for computations
wordApp = CreateObject("Word.Application")
sourceTable = New DataTable
'Some other procs to fill the data table
templateName = "Foo Template.docx"
template = wordApp.Documents.Add(templatePath & templateName)
templateBookmarks = template.Bookmarks
templateBookmarks.Item("sample bookmark").Range.Text = "foo"
'Then fills the table in the template like...
template.Tables(1).Cell(1, 1).Range.Text = dataSource.Rows(0).Item(0)
'Then saves the document as a pdf
Dim saveName As String = "sample file"
template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
I have tried to force garbage collection for the word COM resources, as well as changing the template from an actual document i.e. docx to a word template .dotx. I also tried the method Quit() but it only shows the ms word message much earlier. This is the first time I needed to use interop so pardon if I don't have much idea about it.
The files I needed are saved, the only problem is the ms word message and unsaved and unnecessary files e.g. Document1,Document2,Document3 that seems to be created aside from the required PDF

Use the Document.Close method which closes the specified document after saving files using the PDF file format. It allows specifying the SaveChanges parameter which specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
On Error GoTo errorHandler
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
errorHandler:
If Err = 4198 Then MsgBox "Document was not closed"

Related

Cannot find bookmarks from OpenXML appended document

using the following code snippet I open a document template (DOTX) and then append another document. Both have bookmarks.
Dim m_word As WordprocessingDocument = = WordprocessingDocument.Open("FrontPage.dotx", True)
Dim altChunkId As String = "ChunkId1"
Dim mainPart As MainDocumentPart = m_word.MainDocumentPart
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(
DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Using fileStream As IO.FileStream = IO.File.Open("Appendix.dotx", IO.FileMode.Open)
chunk.FeedData(fileStream)
End Using
Dim altChunk As AltChunk = New DocumentFormat.OpenXml.Wordprocessing.AltChunk()
altChunk.Id = altChunkId
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph).Last())
mainPart.Document.Save()
Now if I try to loop trough all bookmarks like this:
Dim docbody As Body = doc.GetFirstChild(Of Body)()
For Each bookmarkStart As BookmarkStart In docbody.Descendants(Of BookmarkStart)()
' Do something with the bookmarks
Next
I only get the bookmarks of the original frontpage.dotx, none of the bookmarks of the appendix.dotx is found.
If I save the document to a file, all the bookmarks are there when I open it using Word. I can also reopen the saved file i C# and then all bookmarks can be found using the above For Each loop. The question is, how can I get all the bookmarks after appending without saving and reloading the document?
When you use AltChunk to embed a document the entire file is embedded into the document - it's NOT integrated. That only happens when the combined document is opened by Word. If you need to work through all the bookmarks you need to either
Open each document, do the bookmarks, and THEN combine the two using AltChunk OR
Not use AltChunk to combine the documents, and transfer the second document part-by-part into the first document.

Word VSTO: Save a string as an AutoText value

I am porting a Word vba project that has some older WordBasic elements into a VSTO project using vb.net. One of the tasks I need to do is programmatically save a string, or the contents of a text box on a form, to an AutoText value in the Word template.
In the old project, this was easy. The command looked something like this:
WordBasic.SetAutoText "AT Name", strSomeValue, 0
Attempting this in vb.net:
'declarations
Public appWord As Word.Application
Public tplMyTpl As Word.Template
Public doc As Word.Document
'Get the template
appWord = Me.Application
doc = appWord.ActiveDocument
tplMyTpl = doc.AttachedTemplate
'try saving autotext
tplMyTpl.AutoTextEntries.Add("AT Name", strSomeValue)
does not work because the AutoTextEntries.Add method only accepts the value as a Word.Range. A type cast error is thrown at runtime with the code above. It would have to look something like:
dim sel as Word.Selection = appWord.Selection
tplMyTpl.AutoTextEntries.Add("AT Name", sel.Range)
Problem is I do not want to insert the string into my document, select it as a Range, save the AutoText entry then delete the text. That seems like extremely sloppy coding.
You can still use WordBasic in VSTO. Just call it through your Word.Application object reference, e.g.:
appWord.WordBasic.SetAutoText("AT Name", strSomeValue, 0)
Tested and working in Word 2013.

Fill a PDF Form from MS Access

I found a post on here on how to fill a fillable PDF from from MS Access.
It is a Visual Basic code for filling out a fillable PDF. I have been using Excel to perform this function and would like to migrate my database to Access and still keep the same functionality. I have figured out how to add my VB code to the button but when I click it gives me and error. Any help that can be giving would be greatly appreciated.
I have Adobe Acrobat X Pro and MS Access 2010. My PDF files was created in word and then converted to a PDF file, I know all my field names because I created them. The PDF document is saved as c:\CX.pdf, it has 9 pages, some examples of field names on the document are: “Plant Name”, “Station Location”, “Installer or Owner”. My MS Access Data Base Fields are named the same.
Option Compare Database
Private Sub Command105_Click()
Dim FileNm, gApp, avDoc, pdDoc, jso
FileNm = "c:\CX.pdf" 'File location
Set gApp = CreateObject("AcroExch.app")
Set avDoc = CreateObject("AcroExch.AVDoc")
If avDoc.Open(FileNm, "") Then
Set pdDoc = avDoc.GetPDDoc()
Set jso = pdDoc.GetJSObject
jso.getField("CX[0].Page1[0].Plant_Name[0]").Value = "Plant_Name"
jso.getField("CX[0].Page1[0].Station_Location[0]").Value = "Station_Location"
jso.getField("CX[0].Page1[0].Installer_or_Owner[0]").Value = "Installer_or_Owner"
pdDoc.Save PDSaveIncremental, FileNm 'Save changes to the PDF document
pdDoc.Close
End If
'Close the PDF; the True parameter prevents the Save As dialog from showing
avDoc.Close (True)
'Some cleaning
Set gApp = Nothing
Set avDoc = Nothing
Set pdDoc = Nothing
Set jso = Nothing
End Sub
It was giving me the error "Object not found", now it's not giving me error but it's still not writing to the PDF.
This is a bit old but it helped me in the long run. I did figure out what was wrong. "Object not found" means that the code cannot find the PDF field and therefore you can not assign anything to the object that "getFeild()" returns. The most likely culprit is that the "path" to the Field is incorrect. Try just putting the field name and you may need to export the data to a FTF file and read the file in notepad to find the field name.
the field names will look like
T/(FeildName)v/(FeildValue)
Once the object is actually being returned you'll be able to assign it a value.

How to stop a Word Document immediately when newly created

I have a VS2010 Vb.net program that creates a Word 2007 file.
My Normal.dot file is customised to give me a new Tab with Buttons in that do specific things via VBA in the Normal.dot program when those Buttons are pressed.
This all works fine, however, I now want to add some functionality whereas as soon as the new Word document is created, it edits a Task in Outlook.
I have edited the 2 "This Document" Procedures and you can see my Normal.Dot file in the attached Screenshot.
When I run my VB.Net program to create a brand new Word 2007 document, the program does NOT stop on either of the message boxes, it just continues and opens the Word document as before, my code is below, what am I doing wrong ?!?
'Open or Create Word document for Editing
myNewsLetter = myFolder + myLeague + "News" + mySession + ".doc"
If File.Exists(myNewsLetter) Then
'do nothing
Else
myTemplate = myTempFolder + "NL Skeleton.doc"
File.Copy(myTemplate, myNewsLetter)
Create_Blank_Newsletter()
End If
'Open Word Newsletter, or switch to it if it's already open
Dim myFileOpen As Boolean
myFileOpen = IsFileOpen(myNewsLetter)
If myFileOpen = False Then
MSDoc = MSWord.Documents.Open(myNewsLetter)
End If
MSWord.WindowState = Word.WdWindowState.wdWindowStateNormal
MSWord.Visible = True
MSWord.ActiveDocument.Bookmarks("\StartOfDoc").Select()
OK, sorted this, the full discussion can be found here ... http://www.vbaexpress.com/forum/showthread.php?p=286771#post286771
Basically, I'm not creating a NEW document, I am creating a new document via a Copy and then opening that existing document !!!

Trying to open a excel template and rename or save to new location

I get the following error message when I try the following:
Dim XL As New Microsoft.Office.Interop.Excel.Application
XL.Visible = True
XL.Workbooks.Open(XLTemplatePath)
XL.SaveWorkspace(XLSaveReportPath)
XL.Workbooks.Close()
XL.Workbooks.Open(XLSaveReportPath)
"Excel cannot open the file 'ContactReports.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
What I would like to do is Open a excel file that is the XLTemplatePath and the either rename or save the file at the XLSaveReportPath and then use that renamed/saved file to fill the report out.
I am using Visual Studio 2008 in VB.NET
The saveworkspace method does not save the file. It save the workspace in the format xlw even though you are naming the file you are saving the workspace in as xls. When you try and open the document you are opening a worspace and you recieve the error.
To have this work correctly you need to get the workbook so you can sabe the workbook instead of the application.
Dim XL As New Microsoft.Office.Interop.Excel.Application
Dim XLWorkbook as new Microsoft.Office.Interop.Excel.Workbook
XL.Visible = True
XLWorkbook = XL.Workbooks.Open(XLTemplatePath)
XLWorkbook.SaveAs(XLSaveReportPath)
XL.Workbooks.Close()
XL.Workbooks.Open(XLSaveReportPath)
Should do the trick. Let us know if you have any problems.
Heare are the MSDN refrences for your review:
Application.SaveWorkspace Method
Workbook.SaveAs Method
I have used the following Visual Basic code to work with Microsoft Excel 2003. The key difference (other than Visual Basic 6 vs VB.Net) is that I use the SaveAs method of the Workbook object rather than the SaveWorkspace method.
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = True
Set ExcelDoc = ExcelApp.Workbooks.Open(FileName:=XLTemplatePath, ReadOnly:=True)
ExcelDoc.SaveAs(FileName:=XLSaveReportPath)
ExcelDoc.Close(SaveChanges:=False)
ExcelApp.Workbooks.Open(FileName:=XLSaveReportPath)