objective: save emails as PDF files in a folder
problem: Outlook folder has over 1000 emails. Code runs for 26 emails then stops/freezes.
attempts: tried different Outlook email folders with different content all stop at 26/27.
I suspect its creating some type of memory issue? Not closing something? Thanks for any help.
here is the code
Sub save_as_PDF()
Dim objDoc As Object, objInspector As Object
Dim outApp As Object, objOutlook As Object, objFolder As Object, myItems As Object, myItem As Object
Dim FolderPath, FileName, ClientName, ModTime, ranDigits As String
Set outApp = CreateObject("Outlook.Application")
Set objOutlook = outApp.GetNamespace("MAPI")
Set objFolder = objOutlook.GetDefaultFolder(olFolderInbox).Folders("regular")
Set myItems = objFolder.Items
FolderPath = "C:\Users\xxxxx\Documents\My Documents\__AA My Daily\vbaOutlookTestFolder\"
On Error Resume Next
For Each myItem In myItems
Set objInspector = Nothing
Set objDoc = Nothing
Set objInspector = Nothing
Set objDoc = Nothing
FileName = myItem.To
FileName = Replace(FileName, ".", "")
Set objInspector = myItem.GetInspector
Set objDoc = objInspector.WordEditor
objDoc.ExportAsFixedFormat FolderPath & FileName & ".pdf", 17
Next myItem
End Sub
attempts: tried different Outlook email folders with different content all stop at 26/27.
I expected it to convert every email item in the folder to a pdf
I suspect its creating some type of memory issue? Not closing something? Thanks
CodePudding user response:
The problem is related to the following line of code:
objDoc.ExportAsFixedFormat FolderPath & FileName & ".pdf", 17
The FileName
is not unique and can remain the same for most of the items in the folder.
FileName = myItem.To
Instead, you need to generate a unique filename to avoid any troubles with saving pdf files. Try to add any ID to the string to avoid duplicates in the same folder.
A similar issue was described in the pdf files not saving with ExportAsFixedFormat thread.
CodePudding user response:
myItem.To
can contain (in case of multiple To recipients) ";"
, which is invalid in file names.
Never use On Error Resume Next
unless you actually check Err.Number
- it just mask the exception and you don't know what hits you.