Closing word when using interop library - VB.net - vb.net

I have successfully been able to convert a word doc to pdf - but I can't get the winword process to end.
Dim wordApplication As Object = New Microsoft.Office.Interop.Word.Application
Dim wordDocument As Object
wordApplication.displayalerts = Word.WdAlertLevel.wdAlertsNone
wordDocument = New Microsoft.Office.Interop.Word.Document
'wordDocument = Nothing
Dim outputFilename As String
Dim filename As String
filename = "c:\TestInvoice.doc"
Try
wordDocument = wordApplication.Documents.Open(filename, ReadOnly:=False)
outputFilename = System.IO.Path.ChangeExtension(filename, "pdf")
If Not wordDocument Is Nothing Then
wordDocument.ExportAsFixedFormat(outputFilename, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 0, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, True, True, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, True, True, False)
End If
'Threading.Thread.Sleep(3000)
If File.Exists(System.IO.Path.ChangeExtension(filename, "pdf")) Then
MessageBox.Show(System.IO.Path.ChangeExtension(filename, "pdf"))
End If
'wordDocument = Nothing
'wordApplication.Documents(filename).Close(Word.WdSaveOptions.wdDoNotSaveChanges)
'wordDocument.dispose()
'wordApplication.quit(False)
wordDocument.close()
wordApplication.application.quit(False)
wordApplication = Nothing
I've tried pretty much everything and have been scratching my head for the past few days - can you point me in the right direction?

Have you tried a Using statement?
Try wrapping everything in this.
Using wordApplication As Object = New Microsoft.Office.Interop.Word.Application
End Using

Related

Kofax power PDF VBA dll reference

Just wanted to add information on the below post (but seems I cant).
https://safeweb.hsbcpb.com/https://stackoverflow.com/questions/39269911/nuance-power-pdf-automation-using-excel-vba-macro
The reference is now:
"C:\Program Files (x86)\Kofax\Power PDF 31\bin\PDFCore8_x64.dll"
even if called powerPDF and the documentation said so to create the with "powerdpdf.app", the following code work fine for me (just in case someone was looking for a solution like I did).
Function copy_pdf_values_wiht_nuance(path As String) As String
Dim PDFApp As Object
Dim dvOpenDoc As Object
Dim ddDoc As Object
Set PDFApp = CreateObject("nuancePDF.App")
Set dvOpenDoc = CreateObject("nuancePDF.DVDoc")
If dvOpenDoc.Open(path) = False Then
PDFApp.Exit
Exit Function
End If
Set ddDoc = dvOpenDoc.GetDDDoc()
PDFApp.MenuItemExecute ("SelectAll")
PDFApp.MenuItemExecute ("Copy")
PDFApp.Exit
'Set ddPage = ddDoc.AcquirePage(0)
'Set hl = CreateObject("NuancePDF.HiliteList")
'hr = hl.Add(12, 1)
'hr = hl.Add(52, 2)
'Set ts = ddPage.CreatePageHilite(hl)
'hr = dvOpenDoc.SetTextSelection(ts)
'dvOpenDoc.ShowTextSelect
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
copy_pdf_values_wiht_nuance = strContents
End Function
Copy and paste content of a PDF, having had the wrong reference.

Populate PDF Combo Box Via VBA

I have the below code to populate a combobox in a PDF document. As far as I can tell, the code is correct, according to the Acrobat Forms API Reference
However the code fails on the PopulateListOrComboBox call with this error:
Method 'PopulateListOrComboBox' of object 'IField' failed
Dim acroApp As Acrobat.acroApp
Set acroApp = New Acrobat.acroApp
Dim myForm As Acrobat.AcroAVDoc
Set myForm = New Acrobat.AcroAVDoc
Dim bOK As Boolean
bOK = myForm.Open("C:\Users\sholtzman\downloads\wordFormTest.pdf", "temp")
Dim theRealForm As AFORMAUTLib.AFormApp
Set theRealForm = New AFORMAUTLib.AFormApp
Dim pdField As AFORMAUTLib.Field
Set pdField = theRealForm.Fields.Add("triaCoverage", "combobox", 0, 10, 20, 100, 200)
Dim items(2) As String
items(0) = " "
items(1) = "Accept"
items(2) = "Reject"
pdField.PopulateListOrComboBox items
Furthermore, I tested this piece of code as well to try to fill it, but it also failed with the error:
Automation error Unspecified error
Dim myPDForm As Acrobat.AcroPDDoc
Set myPDForm = myForm.GetPDDoc
Dim jso As Object
Set jso = myPDForm.GetJSObject
jso.getField("triaCoverage").setItems(1) = " "
Lastly, when I save and close the document after adding the combobox, I can go in
and set list values manually. Any ideas how I can get this to work through code?
I did some more research and have found one answer just now by replacing the line:
jso.getField("triaCoverage").setItems(1) = " "
with
jso.getField("triaCoverage").setItems(items)
However, I prefer to use the PopulateListOrComboBox method if at all possible, so i will leave this unanswered for some time.

Office application hangs during document opening via interop

I am trying to open a file but the Office application hangs during document opening in VB.NET.
I have this code:
Dim oProp As Object
Dim strPropValue As String
Dim lngRetVal As Integer
Dim strmsg As String
Dim lngretcode As Integer
Dim strPropertyName As String
Dim oWordDoc As Word.Document
Dim ObjOfficeAPP As Object
ObjOfficeAPP = New Word.Application()
GetWORDKEYS = cstFAILURE
ObjOfficeAPP.DisplayAlerts = WdAlertLevel.wdAlertsAll
ObjOfficeAPP.Application.Visible = True
oWordDoc = ObjOfficeAPP.Documents.Open(FileName:=strpFileName, Visible:=False)
I have problems on the line:
oWordDoc = ObjOfficeAPP.Documents.Open(FileName:=strpFileName, Visible:=False)
The debugger hangs on the Documents.Open() call, and just stays there waiting - without firing any type of exception or error. We have looked in the event log but only found the following.
My problem is, how can I set to open this document and not to block on the line with the Documents.Open() call?
Here are few points that could help:
Don't use the Application property for setting the Visible property:
ObjOfficeAPP.Visible = True
Don't set the DisplayAlerts property before opening a document.
Use the System.Reflection.Missing.Value for missing arguments.
You may find the How to automate Word from Visual Basic .NET to create a new document article helpful which explains the required steps for automating Word and provides a sample code:
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add

html file save restore from vba

I want to re-use a snapshot of a web response for testing an app that needs to do some web-scraping. What I tried to do is just save the response (from Chrome) and reload the the string from the file:
doc.body.innerHtml = StringFromFile
This doesn't work though, although it looks like good html. By not work, I mean data that is in tag "Table"(6) when going through the web is not found. Is there a better way to load the html doc?
The code below is an attempt to both save an existing doc to file and then reuse it. Its worthless but maybe it will help someone set me straight on this.
Cheers
Private Function GetEWhipersTestHtmlDoc() As HTMLDocument
Dim doc As HTMLDocument
Set doc = New HTMLDocument
Dim sText As String
sText = GetStringFromFile(GetFileName("UnconfirmedRelease"))
doc.body.innerHTML = sText
Set GetEWhipersTestHtmlDoc = doc
End Function
Private Function GetFileName(testName As String) As String
GetFileName = ThisWorkbook.path & Application.PathSeparator & _
"Earnings Whispers Test Scenarios" & Application.PathSeparator & testName & ".txt"
Debug.Assert Dir(GetFileName) <> ""
End Function
Private Function SaveHtmlStringToFile(testName As String, sInnerHtml As String) As String
Dim fso As Object
Dim oFile As Object
Dim sPath As String
Set fso = CreateObject("Scripting.FileSystemObject")
sPath = GetFileName(testName)
Set oFile = fso.CreateTextFile(sPath)
oFile.WriteLine sInnerHtml
oFile.Close
End Function
** UPDATE **
Saving doc.body.outerHtml seems to be an upgrade from what I had. The text can turned into the web page using 'code snippet'. I am getting an error when trying to put the saved text back into a new document though:
Err 600, Application-defined or object-defined error
Private Function GetEWhipersTestHtmlDoc() As HTMLDocument
Dim doc As New HTMLDocument
Dim sText As String
' Error Handling
On Error GoTo ErrHandler
sText = GetStringFromFile(GetFileName("UnconfirmedRelease"))
doc.body.outerHTML = sText <---- ** ERROR is Here
Set GetEWhipersTestHtmlDoc = doc
Exit Function
ErrHandler:
Select Case DspErrMsg("blah")
Case Is = vbAbort: Stop: Resume 'Debug mode - Trace
Case Is = vbRetry: Resume 'Try again
Case Is = vbIgnore: 'End routine
End Select
End Function
final update
thanks to Tim and David I got something usable. The only hair of Tim's final solution is that HtmlDocument.Write is restricted as far as VBA is concerned. So to 'fool' the compiler, I needed to declare it as an Object:
Dim doc As Object <--- don't let vba know we want to write to HTMLDoc
Set doc = New HTMLDocument
Dim sText As String
sText = GetStringFromFile(GetFileName("UnconfirmedRelease"))
doc.Open
doc.Write sText <-- no intellisense, but compiles...and works!
doc.Close

Closing Word app, vb.net

i am trying to search within word documents, using vb.net it worked but i cant seem to close the files after searching them, here is the code i use
how to close the word apps after being searched ?
Dim oWord As Word.Application = Nothing
Dim oDocs As Word.Documents = Nothing
Dim oDoc As Word.Document = Nothing
Dim folderDlg As New FolderBrowserDialog
folderDlg.ShowNewFolderButton = True
If (folderDlg.ShowDialog() = DialogResult.OK) Then
Dim root As Environment.SpecialFolder = folderDlg.RootFolder
End If
Dim l_Dir As IO.DirectoryInfo
Dim fldpath As String = folderDlg.SelectedPath
If IO.Directory.Exists(fldpath) Then
l_Dir = New IO.DirectoryInfo(fldpath)
For Each l_File In Directory.GetFiles(fldpath, "*.docx")
Dim searchFor As String = TextBox1.Text
oWord = New Word.Application()
oWord.Visible = False
oDocs = oWord.Documents
oDoc = oDocs.Open(l_File, False)
oDoc.Content.Find.ClearFormatting()
Dim findText As String = searchFor
Try
If oDoc.Content.Find.Execute(findText) = True Then
MessageBox.Show("OK.")
oWord.NormalTemplate.Saved = True
oWord.ActiveDocument.Close(False)
oDoc.Close()
oWord.Quit()
If Not oDoc Is Nothing Then
Marshal.FinalReleaseComObject(oDoc)
oDoc = Nothing
End If
If Not oDocs Is Nothing Then
Marshal.FinalReleaseComObject(oDocs)
oDocs = Nothing
End If
If Not oWord Is Nothing Then
Marshal.FinalReleaseComObject(oWord)
oWord = Nothing
End If
Else
MessageBox.Show("No.")
End If
Catch ex As Exception
End Try
ComboBox1.Items.Add(l_File)
Next
End If
First thing you should bear in mind is that "releasing the objects" in Word is not as difficult as in Excel and thus you are (unnecessarily) over-complicating things. In any case, you should intend to not over-declare variables (what is the exact point of oDocs?). And, lastly, you should always perform a step-by-step execution when things go wrong to find out what might be happening (you are applying your "objects release" only for "OK" cases, not in any situation: when the result is "No", the objects would have to be released too).
Here you have a corrected code accounting for all the aforementioned issues:
Dim oWord As Word.Application = Nothing
Dim oDoc As Word.Document = Nothing
Dim folderDlg As New FolderBrowserDialog
folderDlg.ShowNewFolderButton = True
If (folderDlg.ShowDialog() = DialogResult.OK) Then
Dim root As Environment.SpecialFolder = folderDlg.RootFolder
End If
Dim l_Dir As IO.DirectoryInfo
Dim fldpath As String = folderDlg.SelectedPath
If IO.Directory.Exists(fldpath) Then
l_Dir = New IO.DirectoryInfo(fldpath)
For Each l_File In Directory.GetFiles(fldpath, "*.docx")
Dim searchFor As String = TextBox1.Text
oWord = New Word.Application()
oWord.Visible = False
Try
oDoc = oWord.Documents.Open(l_File, False)
oDoc.Content.Find.ClearFormatting()
Dim findText As String = searchFor
Try
If oDoc.Content.Find.Execute(findText) = True Then
MessageBox.Show("OK.")
Else
MessageBox.Show("No.")
End If
Catch ex As Exception
End Try
oWord.NormalTemplate.Saved = True
ComboBox1.Items.Add(l_File)
Catch ex As Exception
End Try
oDoc = Nothing
oWord.Quit()
oWord = Nothing
Next
End If
NOTE: note that, when iterating through all the Word files in a folder (and, in general, ones from any MS Office program), you can find temporary copies (starting with "~$...") which might trigger an error when being opened (and thus not allow the object-releasing part to come into picture); also, in general, when opening files something might go wrong; this is what explains the new try...catch I added and why I put the releasing part after it.
I don't know Vb.net, but in F# I used
System.Runtime.InteropServices.Marshal.ReleaseComObject xlApp |> ignore
after ".Quit()", to end the process, but you must search, how to give the name of your word application at the place of xlApp
I will place this after the "End If" at the end.
I hope it will be helpfull for you