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

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

Related

Print File - Macro

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

VBA excel: how to add text to all files on a folder

I need to add text string to all files on a folder, as a footer
For example, on the folder on the path and called C:\mobatchscripts\
I have a random number of txt files, with text.
I want to add a line for example "text" on each of the text files on the folder
I have little knowledge of vba programming, but for what I have read I can use append, but I need something that loop on the files on the folder, and modify them.
So far I tried this:
Sub footer()
Dim FolderPath As String
Dim FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\mobatchscripts\"
FileName = Dir(FolderPath)
Do While FileName <> ""
Open FileName For Append As #1
Print #1, "test"
Close #1
FileName = Dir
Loop
End Sub
But seems that its not looking into the files, or appending the text.
On the assumption that you're writing to text files (I see "batchscripts" in the path), you need a reference to the Microsoft Scripting Runtime (Within the VBE you'll find it in Tools, References)
Option Explicit
Public Sub AppendTextToFiles(strFolderPath As String, _
strAppendText As String, _
blnAddLine As Boolean)
Dim objFSO As FileSystemObject
Dim fldOutput As Folder
Dim filCurrent As File
Dim txsOutput As TextStream
Set objFSO = New FileSystemObject
If objFSO.FolderExists(strFolderPath) Then
Set fldOutput = objFSO.GetFolder(strFolderPath)
For Each filCurrent In fldOutput.Files
Set txsOutput = filCurrent.OpenAsTextStream(ForAppending)
If blnAddLine Then
txsOutput.WriteLine strAppendText
Else
txsOutput.Write strAppendText
End If
txsOutput.Close
Next
MsgBox "Wrote text to " & fldOutput.Files.Count & " files", vbInformation
Else
MsgBox "Path not found", vbExclamation, "Invalid path"
End If
End Sub
I'd recommend adding error handling as well and possibly a check for the file extension to ensure that you're writing only to those files that you want to.
To add a line it would be called like this:
AppendTextToFiles "C:\mobatchscripts", "Test", True
To just add text to the file - no new line:
AppendTextToFiles "C:\mobatchscripts", "Test", False
Alternatively, forget the params and convert them to constants at the beginning of the proc. Next time I'd recommend working on the wording of your question as it's not really very clear what you're trying to achieve.

MS Access Lotus notes attach multiple files from a folder

I need to figure out how to put a code in MS Access vba for attaching all the files in a selected folder.
Right now I can do just one from a specific location:
PathLocation = "C:\Test\test.PDF"
If Not IsNull(PathLocation) Then
txtAttach = PathLocation
Set objAttachment = objMailDocument.CREATERICHTEXTITEM("strFileAttachment")
Set objEmbedObject = objAttachment.EMBEDOBJECT(1454, "", txtAttach, "strFileAttachment")
End If
But what I really want is to collect all the stuff from the Test folder.
You need the Dir- statement to run through all files in the directory:
Dim PathLocation As String
Dim fileName As String
Dim filePath as String
PathLocation = "C:\Test\"
If Not IsNull(PathLocation) Then
Set objAttachment = objMailDocument.CREATERICHTEXTITEM("strFileAttachment")
fileName = Dir$(PathLocation & "*.*", 0)
Do While fileName <> ""
filePath = PathLocation & fileName
Set objEmbedObject = objAttachment.EMBEDOBJECT(1454, "", filePath, "")
fileName = Dir$()
Loop
End If
To run through e.g. just PDFs replace the *.* in the code above by *.pdf
Hope this should help,there is an example attached at the end as well.
http://bytes.com/topic/access/insights/916710-select-file-folder-using-filedialog-object

Compare Multiple Pairs of Docs

I am a professor in an English department, and my composition students often write multiple drafts of their essays. I use Word 2010 to track their changes.
I discovered VBA code on another site (located here). I created a new macro. It prompts me correctly for the base, new, and comparison folders, but the output is null.
I have the files in both the base and new folders named identically and saved in .doc format. I also set the trust center options in Word to 1) enable all macros and 2) trust access to the VBA project object model.
Sub CompareAllFiles()
Dim strFolderA As String
Dim strFolderB As String
Dim strFolderC As String
Dim strFileSpec As String
Dim strFileName As String
Dim objDocA As Word.Document
Dim objDocB As Word.Document
Dim objDocC As Word.Document
strFolderA = InputBox("Enter path to base documents:")
strFolderB = InputBox("Enter path to new documents:")
strFolderC = InputBox("Enter path for document comparisons to be saved:")
strFileSpec = "*.doc"
strFileName = Dir(strFolderA & strFileSpec)
Do While strFileName <> vbNullString
Set objDocA = Documents.Open(strFolderA & strFileName)
Set objDocB = Documents.Open(strFolderB & strFileName)
Application.CompareDocuments _
OriginalDocument:=objDocA, _
RevisedDocument:=objDocB, _
Destination:=wdCompareDestinationNew
objDocA.Close
objDocB.Close
Set objDocC = ActiveDocument
objDocC.SaveAs FileName:=strFolderC & strFileName
objDocC.Close SaveChanges:=False
strFileName = Dir
Loop
Set objDocA = Nothing
Set objDocB = Nothing
End Sub
If you and your students are using Word 2010 then the extension would most likely be .docx:
strFileSpec = "*.docx"
Have you tried running the code step-by-step with the VBA debugger, to see what is the exact point of failure? See here (under the section entitled Stepping Through Code) for a simple introduction.
Some kind VBA guru figured it out for me: I need to enter a \ at the end of the folder paths. Without the final backslash, the script was not able to locate the folders, and thus it wasn't processing any files. After adding the final \ to all three folder paths, the code ran perfectly.
As a bonus, the code processes both .doc and .docx files. I thought I was going to have to convert all my .docx files to .doc before processing, but the code is smarter than that.
Eureka!

Dir Function in Excel 2010 VBA not working

I am trying to loop through a given directory to find the latest downloaded csv file. For some reason my Dir function won't find any file even if the file does exist. I am not totally familiar with VBA so i may perhaps be missing some sort of reference to perform the Dir function, but I can't find anything online that tells me I need to. All the examples and forums use Dir just like I do, but I can't get mine to work. Here is the code, please tell me if you can see what I am doing wrong:
Public Function Get_File() as string
Dim filePath As String
ChDir ("..")
filePath = CurDir
'Goes back to Documents directory to be in same directory as macro
ChDir (filePath & "\Documents")
filePath = filePath & "\Downloads\test.txt"
filePath = getLatestFile(filePath)
Get_File = filePath
End Function
Public Function getLatestFile(pathToFile As String) As String
Dim StrFile As String
Dim lastMod As Variant
Dim nextMod As Variant
Dim lastFileName As String
StrFile = Dir(pathToFile)
lastFileName = StrFile
lastMod = FileDateTime(StrFile)
While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
nextMod = FileDateTime(StrFile)
If nextMod > lastMod Then
lastFileName = StrFile
lastMod = nextMod
End If
Wend
getLatestFile = lastFileName
End Function
The test.txt file is in my Downloads file and the filePath string prints out to be the correct path, but I keep getting an error stating that it can't find the file. It fails at the first use of Dir(pathToFile). Any help would be greatly appreciated.
Dir() only returns the filename portion of the path, i.e., it does not return the folder portion. For example,
Dir("C:\MyPath\MyFile.txt")
returns MyFile.txt not C:\MyPath\MyFile.txt