Print File - Macro - vba

I have created a macro that I can use to print PDF files. The PDF files will be saved in a folder to print. The path will be given that folder path where I save all PDF files. My questions are:
1) Once the files are saved in folder, is it possible to sort it automatically like first come first print. Now the issue is - prints did not come out in order of how the files are – we have to reconcile all files, so looking for each one in a random list order would take lots of time.
2) Is it possible to have the files automatically deleted from the folder after the printing is completed?
Public Sub Print_All_PDF_Files_in_Folder()
Dim folder As String
Dim PDFfilename As String
folder = "\\maple.fg.rbc.com\data\toronto\user_3\315606053\myWorkspace\Desktop\test" 'CHANGE AS REQUIRED
If Right(folder, 1) <> "\" Then folder = folder & "\"
PDFfilename = Dir(folder & "*.pdf", vbNormal)
While Len(PDFfilename) <> 0
If Not PDFfilename Like "*ecg*" Then
Print_PDF folder & PDFfilename
End If
PDFfilename = Dir() ' Get next matching file
Wend
End Sub
Sub Print_PDF(sPDFfile As String)
Shell "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe /p /h " & Chr(34) & sPDFfile & Chr(34), vbNormalFocus
' This is path of Adobe in the desktop
End Sub

There is no build in way to sort files. However, it is rather easy to read the filenames and -dates into arrays and sort them manually, but you have to use the FilesystemObject rather than using dir to get the file dates.
You can find an example to do so for example here: https://social.msdn.microsoft.com/Forums/office/en-US/5f27936e-1d98-44df-8f69-0f81624c4b92/read-files-in-a-folder-in-descending-order-with-file-name-or-date-created?forum=accessdev
The command to delete a file with VBA is kill, or you can use the .DeleteFile method of FilesystemObject. However, this will work only if the printing is already done, so you have to wait for your shell-command to finish. For this, you have to use the wscript.shell, see for example here https://stackoverflow.com/a/8906912/7599798

Related

Search for file in folder backwards

So far all the examples for checking if a file is in a directory has been to get a list of files in that directory then compare your items to it. This is a lot of overload for me. I have a list of about 125 files and the directory I want to search in has 8000 files. Can someone instruct me on how to use a file with a list of file names and search a directory for each file.
Moved here from comments:
The code below works, but because it's searching through 8000 files in
a directory the code takes a long time to work. I have a document with
350 lines of file names. Instead of going through each file in the
directory for a match to one of the file names in my document. I'd
like to take my list and search the directory for that file. This way
I'm only looping 350 times instead of 8000
Here is my code.
Dim fileNames As String() = System.IO.Directory.GetFiles(imgLocation)
Dim i As Integer
statusText = "Copying Image Files"
i = 0
' Loop over the filenames retrieved
For Each fileName As String In fileNames
' Check if the files is contained or not in the request list
If GraphicList.Contains(Path.GetFileNameWithoutExtension(fileName)) Then
'Debug.Write("Filename " & fileName & vbCr)
Dim FileNameOnly = Path.GetFileName(fileName)
Dim copyTo As String
copyTo = createImgFldr & "\" & FileNameOnly
System.IO.File.Copy(fileName, copyTo, True)
' Do not write to file inside the loop, just add the fact to the list
' Debug.Write("Copy image " & FileNameOnly & vbCr)
imgFilename = (FileNameOnly) + vbCrLf
ImageCount1 = i
BackgroundWorker1.ReportProgress(100 * i / GraphicList.Count())
foundImgFiles.Add(FileNameOnly)
Else
Debug.Write("Missing " & FileNameOnly & vbCr)
notfoundImgFiles.Add(fileName)
End If
i = i + 1
Next

VBA unable to move on to next file in Directory, instead picking file named ".."

I am having a little issue with the Loop function to open files within a Directory. Find the code below:
'Build the complete folder path:
strTargetFolder_Batch = "I:\PerfTeam"
strTargetFolder_Batch = strTargetFolder_Batch & strMonthNo & " " & strMonthName & " " & strYear & "\" & "Attribution - Draft"
If Right(strTargetFolder_Batch, 1) <> "\" Then
strTargetFolder_Batch = strTargetFolder_Batch & "\"
End If
If Not CreateFolder(strTargetFolder_Batch) Then
MsgBox "Unable to create the folder:" & vbCrLf & strTargetFolder_Batch, vbExclamation
Else
End If
FolderPath = strTargetFolder_Batch
'Sets Parameters to Open the file
MyFolder = FolderPath 'location of files
MyExtension = "*.xlsx*"
MyFile = Dir(MyFolder & MyExtension)
Do While MyFile <> "" 'will start LOOP until all files in MyFolder have been looped through
Set oWbk = Workbooks.Open(MyFolder & "\" & MyFile)
*Batch Run is a Boolean function*
'*** 1. Calls Import Data Macro, which Imports the Data ***'
Call Import_new_data(Batch_Run, oWbk)
'*** 2. Calls Data Collector Macro, which Analyses the Data ***'
Call Data_Collector(Batch_Run)
'*** 3. Calls Report Production Macro, which Produces Report ***'
Call Report_Production_Sub(Batch_Run)
ContinueLoop:
MyFile = Dir
'**^^ Here is where the Macro breaks after completing a full first iteration** !
Loop
What essentially the macro does, it picks up data from the opened file, closes the file and then analyses it, before creating a report out of it. It should then move on the second file in the folder and perform the same operation.
While the first file gets opened fine, and analysed as it should, the problem arises moving on to the second file. The variable MyFile in fact picks up a 'Ghost' file named ".." which then throws an error of course as it does not exist. Doing some research I have found out this may relate to the Directory path.
Any help would be super appreciated!
Calling the Dir function with parameter starts a search for matching files. If nothing is specified as second parameter, is will search only regular files (no directories, no hidden files etc).
Any following calls to Dir (without parameter) will continue the last search initiated by a Dir(with parameter).
The .. you get as result of the Dir within your loop is not a file, it's a folder (up directory). You will get this only when you started a Dir with option vbDirectory as second parameter. As this parameter is missing in your code, I would strongly assume that anywhere in your code (that is not displayed) a new Dir-search is started (which destroys the search results of a previous Dir-search).
Update: If you need to check if a folder exists but don't want to destroy your Dir-Loop, you could use the FileSystemObject. The FileSystemObject is usefull for several things concerning files and folders.
if CreateObject("Scripting.FileSystemObject").FolderExists("<enter your path>") then

Merging all PDF's in a folder but having a certain one always first

So I am writing a script for a client (I don't use VB) and it needs to pull all files from specified folders which I'm using an INI file to accomplish. It then combines every PDF in the folder, sends an email to a fax machine and sends the combined PDF to a new folder.
The issue I'm having is I can't seem to figure out how to make sure the first file selected in the PDF is the one I want. I made a dummy PDF and named it "_.pdf" hoping that since it would alphabetically land first that it would be combined first. But that isn't how VB is doing things when it pulls the directory. There doesn't seem to be any constant sorting to my knowledge. So I created a function to sort all files in a folder into an array which works. Now my problem is combining the PDF. The code I was using was simply combining an entire directory in command line. So I'm a bit lost.
Function CombinePDF(folder, combinedFile)
'On Error Resume Next
Dim cmdToRun
set Shell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set outputPDF = CreateObject("System.Collections.ArrayList")
For Each f in fso.GetFolder("c:\TestScript\" + folder).Files
outputPDF.Add f.Name
Next
outputPDF.Sort()
For Each pdf in outputPDF
'The below line is the issue. I had a working one here with *.pdf off
'of the folder. But this is the current code
cmdToRun = "pdftk c:\TestScript\" + folder + "\" + pdf + _
"output c:\TestScript\" + combinedFile + ".pdf"
Shell.Run(cmdToRun)
Next
WScript.Sleep 1000
Set objFolder = CreateObject("Scripting.FileSystemObject")
For Each oFile in objFolder.GetFolder("C:\TestScript\" + folder).Files
If oFile.Name <> "_.pdf" Then
'oFile.Move "C:\TestScript\" + folder + "-Processed\"
End If
Next
End Function
As shown in the documentation HERE, if you have to merge 2 input files say in1.pdf and in2.pdf into a new PDF say out1.pdf, you have to write the command:
pdftk in1.pdf in2.pdf cat output out1.pdf
So, you need to construct a string which contains the paths to all the input files separated by a space.
If you have the sorted file names in the array list, then you can try replacing:
For Each pdf in outputPDF
cmdToRun = "pdftk c:\TestScript\" + folder + "\" + pdf + "output c:\TestScript\" + combinedFile + ".pdf"
Shell.run(cmdToRun)
Next
with
inputFiles=""
For Each pdf in outputPDF
inputFiles = inputFiles & "c:\TestScript\" & folder & "\" & pdf& " "
Next
cmdToRun = "pdftk " & inputFiles & "output c:\TestScript\" + combinedFile + ".pdf"
Shell.run(cmdToRun)

Find all the PDFs in a folder using Visual Basic in Access

So I am very new with using Visual Basic and I am having trouble. I want to open a folder and read all the PDFs in the folder for content. I found this code on the Microsoft Guidelines, but received errors regarding expectations of certain codes:
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.pdf")
Listbox1.Items.Add(foundFile)
Next
Does anyone know why I am getting such errors?
See if this is useful
Sub Dougsloop()
Dim Filename As String
Dim path As String
path = "path to folder" & "\"
Filename = Dir(path & "*.pdf")
Do While Len(Filename) > 0
debug.print; FileName
'Listbox1.Items.AddItem (Filename) replace debug w/this
Filename = Dir
Loop
End Sub

VBA Saving (and converting) a Document From .docm to .docx

I have the following code at the end of a project:
'Save the Document
Dim Directory As String, FileName As String
Directory = "C:\Users\" & (Environ$("Username")) & _
"\Desktop\STL\"
If Len(Dir(Directory, vbDirectory)) = 0 Then
MkDir Directory
End If
FileName = sDNUM & " " & Format(Date, "YYYY-MM-DD") & ".docx"
SaveAs Directory & FileName
MsgBox "File saved to:" & vbNL & Directory & FileName
and I am trying to get the file to save as a docx (non-macro enabled) after running a macro-enabled workbook.
The problem is by using the above method to save my file, upon attempting to open the newly saved file I receive the following error message:
The file < filename > cannot be opened because there are problems with the contents.
What method should I use to properly save these documents?
Miscellaneous notes for the curious:
vbNL is just a function for vbNewLine. I use it quite often and I guess I am just too lazy to type it out all the time so I made a function to shorten the text.
sDNUM is also just another function that is irrelevant to the issue.
Saving the file with a docx extension does not automatically convert it as non-macro-enabled.
Change
SaveAs Directory & FileName
to
SaveAs2 Directory & FileName, wdFormatXMLDocument
For more information on the SaveAs2 method, see here.