Printing pdf through automating word with VB net without showing dialog - vb.net

I've finally encountered a problem, where I didn't already find the answer here or anywhere else on the web:
My program grabs some measurement values from an instrument (I cannot directly control it so I have to wait until the measurement was done by the user and parse the report), calculates some derived values and shall put these values back into the pdf report, which was automatically generated by the instrument control software.
It all works until I come to the line where the printout is started. It always opens the word print dialog instead of silently overwriting my file. I actually don't understand what I am doing wrong when calling PrintOut.
Here is the example code:
Imports Microsoft.Office.Interop
Module Example
Private Sub PrintReport()
Dim intAnswer As Integer
Dim strReportFileName As String = ""
Dim appWord As New Word.Application
Dim wdDoc As Word.Document
dim strPPF as string = "0.5" 'For testing, normally a parameter
dim strFolder as string = "C:\UVVis-Data" 'For testing, normally a parameter
'Find and open the PDF file of the report:
strReportFileName = (From fi As IO.FileInfo In (New IO.DirectoryInfo(strFolder.GetFiles("*.pdf")) Order By fi.LastWriteTime Descending Select fi)(0).FullName 'It will be always the newest file in that folder
appWord.Visible = False 'hide word from the user
wdDoc = appWord.Documents.Open(strReportFileName) 'open the PDF report
'Replace the placeholders which were defined in the report template earlier:
With appWord.Selection.Find
.Text = "#PPF#"
.Replacement.ClearFormatting()
.Replacement.Text = strPPF
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
'Print out the modified report:
'wdDoc.PrintOut(False, False,, strReportFileName,,,,,,, True) 'this was my first approach
wdDoc.PrintOut(Background:=False, Append:=False, OutputFileName:=strReportFileName, PrintToFile:=True) 'this also doesn't work as intended
'Close the file and restore word to it's normal state:
wdDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges)
appWord.Visible = True
appWord.Quit()
End Sub
end Module

Use the Document.ExportAsFixedFormat method which saves a document as PDF or XPS format.
Public Sub ExportAsFixedFormat_Example()
wdDoc.ExportAsFixedFormat pbFixedFormatTypePDF, "pathandfilename.pdf"
End Sub

Thank you for the input.
I found a second problem with my code: I cannot overwrite the original document once it is open in word.
I solved this by first moving the pdf to a temporary folder, opening that temporary file in word and deleting it after word is closed.

Related

How to search and replace across multiple word documents in the same folder?

I've tried to use the below code which I found on this conversation How To Search And Replace Across Multiple Files In Word? supplied by Charles Kenyon. However, it doesn't seem to work for me. I've enabled macros on my word and added the below code as a new module in Macros. When I go to replace all, it'll replace the text as per normal, but after doing this, when I open up the other macros enabled word doc, I find that the same text is still in these docs, without being replaced. Am I doing something wrong? Namely, I also wish to add a wildcard entry into my replace all, will the below code work or can someone suggest a better alternative? I have tested the below code with and without wildcard entries to no avail. I've also tried the code on this page in my macros but it also didn't work How to find and replace a text in multiple Word documents using VBAThanks for any help!
Option Explicit
Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
PathToUse = "C:\Test\"
'Error handler to handle error generated whenever
'the FindReplace dialog is closed
On Error Resume Next
'Close all open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges
'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will
'only be displayed for the first document
FirstLoop = True
'Set the directory and type of file to batch process
myFile = Dir$(PathToUse & "*.doc")
While myFile <> ""
'Open document
Set myDoc = Documents.Open(PathToUse & myFile)
If FirstLoop Then
'Display dialog on first loop only
Dialogs(wdDialogEditReplace).Show
FirstLoop = False
Response = MsgBox("Do you want to process " & _
"the rest of the files in this folder", vbYesNo)
If Response = vbNo Then Exit Sub
Else
'On subsequent loops (files), a ReplaceAll is
'executed with the original settings and without
'displaying the dialog box again
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
End If
'Close the modified document after saving changes
myDoc.Close SaveChanges:=wdSaveChanges
'Next file in folder
myFile = Dir$()
Wend
End Sub

MS Word VBA: Get document's attached template

(Using Windows 10 and MS Word 2016. Global templates are: Normal.dotx and Autoload.dotm. Attached template to some docs is: Reference.dotx)
Hello everyone,
I'm having problems in VBA getting the attached template of a document.
I have a global template that loads when I load MS Word, called Autoload.dotm. But, for some specific documents, they use an attached template, which is not the global template (Autload.dotm) or the regular template (Normal.dotx). This attached template is called Reference.dotx.
So I use ActiveDocument.AttachedTemplate. But this returns Autoload.dotm, not Reference.dotx. I need to find out if the attached template defined in Developer->Document Template->Templates tab->Document Template is Reference.dotx. (Don't think it makes a difference, but the "Automatically update document styles" checkbox is checked.) Does anyone know how I can find if a document uses Reference.dotx? I don't need any of the global templates returned.
The code I'm using to try to get the attached template is simple:
If (ActiveDocument.AttachedTemplate = "Reference.dotx") Then
PrepareDocument_enabled = True
End If
Maybe this will help you? It will show the template used.
Sub Macro1()
Dim strPath As String
strPath = Dialogs(wdDialogToolsTemplates).Template
MsgBox strPath
End Sub
Otherwise, you can use this to change the template
Sub ChangeAttachedTemplate()
Dim oDoc As Document
Dim oTemplate As Template
Dim strTemplatePath As String
Set oDoc = ActiveDocument
If oDoc.Type = wdTypeTemplate Then Exit Sub
Set oTemplate = oDoc.AttachedTemplate
Debug.Print oTemplate.FullName
' Path is probably: C:\Users\USERNAME\AppData\Roaming\Microsoft\Templates\
If InStr(UCase(oTemplate.FullName), UCase("Path of the template")) > 0 Then
oDoc.AttachedTemplate = "PATH TO TEMPLATE" & "TEMPLATE NAME.dotm"
End If
End Sub

Automation of PDF String Search using Excel VBA - OLE error

I'm getting this error, "Microsoft Excel is waiting for another application to complete an OLE action" when trying to automate a PDF string search and record findings in excel. For certain PDFs this error is not popping. I assume this is due to the less optimized PDFs taking a longer time to search string while indexing page by page.
To be more precise, I have a workbook containing two sheets. One contains a list of PDF file names and the other has a list of words that I want to search. From the file list the macro would open each PDF file and take each word from the list of words and perform a string search. If found it would record each finding in a new sheet in the same workbook with the file name and the found string.
Below is the code I'm struggling with. Any help is welcome.
Public Sub SearchWords()
'variables
Dim ps As Range
Dim fs As Range
Dim PList As Range
Dim FList As Range
Dim PLRow As Long
Dim FLRow As Long
Dim Tracker As Worksheet
Dim gapp As Object
Dim gAvDoc As Object
Dim gPDFPath As String
Dim sText As String 'String to search for
FLRow = ActiveWorkbook.Sheets("List Files").Range("B1").End(xlDown).Row
PLRow = ActiveWorkbook.Sheets("Prohibited Words").Range("A1").End(xlDown).Row
Set PList = ActiveWorkbook.Sheets("Prohibited Words").Range("A2:A" & PLRow)
Set FList = ActiveWorkbook.Sheets("List Files").Range("B2:B" & FLRow)
Set Tracker = ActiveWorkbook.Sheets("Tracker")
'For each PDF file list in Excel Range
For Each fs In FList
'Initialize Acrobat by creating App object
Set gapp = CreateObject("AcroExch.App")
'Set AVDoc object
Set gAvDoc = CreateObject("AcroExch.AVDoc")
'Set PDF file path to open in PDF
gPDFPath = fs.Cells.Value
' open the PDF
If gAvDoc.Open(gPDFPath, "") = True Then
'Bring the PDF to front
gAvDoc.BringToFront
'For each word list in the range
For Each ps In PList
'Assign String to search
sText = ps.Cells.Value
'This is where the error is appearing
If gAvDoc.FindText(sText, False, True, False) = True Then
'Record findings
Tracker.Range("A1").End(xlDown).Offset(1, 0) = fs.Cells.Offset(0, -1).Value
Tracker.Range("B1").End(xlDown).Offset(1, 0) = ps.Cells.Value
End If
Next
End If
'Message to display once the search is over for a particular PDF
MsgBox (fs.Cells.Offset(0, -1).Value & " assignment complete")
Next
gAvDoc.Close True
gapp.Exit
set gAVDoc = Nothing
set gapp = Nothing
End Sub
I have now found the answer to this problem.
I'm using Acrobat Pro and whenever I open a PDF file, it opens with limited features due to Protected View settings. If I disable this function or if I click Enable All Features and save changes to the PDF files, VBA macro runs smooth.
It's funny, I'm posting an answer to my own problem.

VBA Excel - Unable to open existing Word Document file

I have a simple macro that opens a Word Document using Excel. I made sure the Word Object Library is properly referenced but when running this macro it freezes after Documents.Open is called (based on me seeing where it fails in the debugger). I don't know if it is a OLE Automation Error but the macro freezes and I have to force close Excel.
Public Const Dir = "C:/Temp/"
Public Const File = "temp.docx"
Public Sub OpenFile()
Dim f As String: f = Dir & File
Dim oWord As Object, oDoc As Object
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents.Open(f)
oDoc.Visible = True
End Sub
I get this message as well: (even though there is no other application open)
Is there an alternative to opening a file with Excel and how I rewrite my program?
As requested - this is a common problem
You should change your Dir variable - that's a reserved name - and you're probably getting a Word error you can't see when you try to open that "file".
You should also change your File variable name too - that can be a reserved word too depending on references you've set
Added Comment:
With regard to it freezing - you can remove the oDoc.Visible = True statement and replace it with oWord.Visible = True BEFORE the problem statement Set oDoc = oWord.Documents.Open(f). That would popup the error indicating you had a problem with your filename

Save Excel Sheet text only to text file VBA

I am trying to copy the values of one column in a sheet to a text file. The code I currently have causes runtime error 434.
Sheets("Output to fcf.1").Columns("A").SaveToText "P:\4_Calcs\02. Flag Mapping\test_.txt"
If I try and save the whole sheet
Sheets("Output to fcf.2").SaveToText "P:\Clear Project Drive\CLE10276 AWS SMP Model Assessmnts\4_Calcs\02. Flag Mapping\test2_.txt"
I get the entire sheet converted into text rather than just the text in the sheet. Is there a simple way to do this?
Thanks in advance!
Not sure which Excel version you have but I don't see a method for SaveToText.
But this procedure should work, or at least get you started...
Sub SaveColumn(sheetName As String, columnName As String, fileName As String)
Dim cell
Dim fso
Dim file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, True)
For Each cell In Sheets(sheetName).Columns(columnName).Cells
If cell.Value <> "" Then
file.WriteLine cell.Value
End If
Next
file.Close
Set file = Nothing
Set fso = Nothing
End Sub
To call it...
SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt"
This is designed to be used as a macro.
Step by step guide:
1) From excel, hit Alt+F11 on your keyboard.
2) From the menu bar, click Insert, then Module
3) Copy and paste the code provided below into the new module that opens.
NOTE: DocPath = "C:\docs\data.txt" should be wherever you want the output file saved, including the file's actual name. Remember, the folder you want the output file to be located in should ALREADY exist. This does not create the folder if it can't be found.
4) From the menu bar, click Tools, then References. Make sure both "Microsoft Office 14.0 Object Library" as well as "Microsoft Word 14.0 Object Library" are checked, and hit okay (See screenshot for details)
5) Save the document as an .xlsm file (This file type supports Macros)
6) Close the VBA editor. Back in Excel, on the ribbon click View and then Macros. Your new macro should be in the list as ExportToTXT
7) Select it and hit run.
Sub ExportToTXT()
Dim DocPath As String
Dim MsgBoxCompleted
Columns("A").Select
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = False
Selection.Copy
DocPath = "C:\docs\data.txt"
'Create and save txt file
AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
Application.CutCopyMode = False
AppWord.Quit (wdDoNotSaveChanges)
Set AppWord = Nothing
MsgBoxCompleted = MsgBox("Process complete.", vbOKOnly, "Process complete")
End Sub
Good luck, and if you have any questions, don't hesitate to ask.
NOTE: These directions might seem overly simplified for your skill level, but I wrote the answer like this to potentially help others in the future.
EDIT
Change
DocPath = "C:\docs\data.txt"
to
DocPath = "C:\docs\data.fcf"
And change
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
to
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath
The output file will be .fcf format. Whether or not it will open properly is something I'm not sure of. You'd have to test in the program you're using.