Solved

Outlook VBA Save PDF's Error

Posted on 2014-04-20
15
394 Views
Last Modified: 2014-06-27
The following code saves the attachments to a folder for all of the selected emails within a folder from outlook. This code works great except for the fact that it will only save around 200 emails worth. Once the code runs and gets to around 200 it errors and quits.

Was wondering if there is limit of emails that can be selected and processed through the VBA, or is there a setting somewhere that can be changed.

Public Sub SaveSelectedAttachments()
On Error GoTo ErrorHandler
Dim olns As Outlook.NameSpace
Dim objMsg As Object
Dim objAttachments As Outlook.Attachments
Dim objSelectedItems As Outlook.Selection
Dim f, i, j, k, counter As Integer
Dim attPath, attFileName As String, strDesktop As String, strR As String
Set olns = Application.GetNamespace("MAPI")
Set objSelectedItems = olns.Application.ActiveExplorer.Selection

strDesktop = "C:\Users\Jbryan\Desktop\SavedPDFS"
msgfolder = strDesktop

For Each objMsg In objSelectedItems
    k = k + 1
    j = 0
    If objMsg.Class = olMail Then
      Set objAttachments = objMsg.Attachments
        counter = objAttachments.Count
      If counter > 0 Then
        With objMsg
            strR = Format(.ReceivedTime, "Short Date")
        End With
        strR = Replace(strR, "/", "-", 1)
                        
            For i = objAttachments.Count To 1 Step -1
                j = j + 1
                f = f + 1
                iExt = Len(objAttachments.Item(i).FileName) - InStrRev(objAttachments.Item(i).FileName, ".")
                strE = Right(objAttachments.Item(i).FileName, iExt)
                attFileName = Left(objAttachments.Item(i).FileName, Len(objAttachments.Item(i).FileName) - iExt - 1)
                attFileName = strR & "_" & k & "_" & j & ".pdf"
                attPath = msgfolder & "\" & attFileName
                objAttachments.Item(i).SaveAsFile attPath
            Next i

        End If
    End If

  Next objMsg
ExitSub:
  Set objAttachments = Nothing
  Set objMsg = Nothing
  Set objSelectedItems = Nothing
  Set olns = Nothing
  MsgBox "Attachments have been successfully saved."
Exit Sub

ErrorHandler:
 MsgBox "Saveattachments( ) Subroutine" & vbCrLf & vbCrLf & "Error Code: " & Err.Number & vbCrLf & Err.Description
  
  Err.Clear
  GoTo ExitSub
End Sub

Open in new window

0
Comment
Question by:jb702
  • 7
  • 5
15 Comments
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 40011933
what exact error ?  what line throw it ?

unless u have a lot of attachments and counter f is overflowing ?   try dimming as long. wont slow code much.
0
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 40011947
'more error handling
MsgBox "Saveattachments( ) Subroutine" & vbCrLf & vbCrLf & "Error Code: " & Err.Number & vbCrLf & Err.Description & vbCrlf & "Failed on message#" & str(k) & " --- Attachment" & str(j)
0
 

Author Comment

by:jb702
ID: 40011950
this is the error i got before i redimmed f to long my code processed 183 attachments.
then after re-dim of f to long it processed 182 attachments of 332 total available attachments to save.

The folder is on my desktop, and i am renaming the "eReceipt.pdf" before i save it so there is no duplicate issue. this is weird.


Error snapshot
0
 

Author Comment

by:jb702
ID: 40011951
I changed the error handler as suggested and this is the message result.

code saved 171 attachments of a possible 426




Revised Error
0
 

Author Comment

by:jb702
ID: 40011956
Decided to run another batch this time with 262 available attachments.  Here is the error message.  This time it saved 197 attachments.

Error3
0
 

Author Comment

by:jb702
ID: 40011959
I wanted to see if it would error on the same message again, so i selected the same 126 emails with a total of 198 attachments and low and behold it did error out on the same message and same attachment as previous post. But there is nothing different with this attachment. It is just like all the others.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:jb702
ID: 40011960
commented out the Error Handling code and ran same set of emails, and code broke at this line.

objAttachments.Item(i).SaveAsFile attPath

with the same error.
0
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 40011969
the error code being negative suggests it is an error within Outlook.... and probably with the attachment ?  there is an attachment type property that may be worth checking.
http://msdn.microsoft.com/en-us/library/office/ff868693(v=office.15).aspx


is it the same message each time ?

alternative is to log the error and keep processing the rest of the messages.  You could do this by setting a flag or catagory on the offending msg.

see http://msdn.microsoft.com/en-us/library/office/dn320330(v=office.15).aspx
Categories, Sensitivity or FlagRequest properties as you can later sort by these.
0
 

Author Comment

by:jb702
ID: 40011982
Ok, so here is what i did next, i ran the code again with the same set of emails except i stopped short of the email that was creating the error. My code ran fine, saved 182 attachments.

then i ran the code on the next set of emails which included the email that was causing the error. The code ran fine saved 80 attachments including the attachments that were in the email that was causing the error above.

Any ideas now?
0
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 40011997
No....

the err number still suggests an issue with outlook.

but only alternate is that these filenames were duplicate but that seems unlikley.

if you are able to do more testing, try using Timer function to force a uniquie id

attFileName = strR & "_" & Format(k,"0000") & "_" & Format(Timer*10,"00000") & ".pdf"
DoEvents

Open in new window


note i convert all the numbers to strings using format function rather than let VBA 'cast' the number to variant then to string.  keeps names consistent as well.

the DoEvents is there in case it is a timing issue with saving.
0
 

Accepted Solution

by:
jb702 earned 0 total points
ID: 40056626
I never resolved,please close question.
0
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 40102307
its up to you to close question...
0
 
LVL 45

Expert Comment

by:Martin Liss
ID: 40161948
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Resolve Outlook connectivity issues after moving mailbox to new Exchange 2016 server
Check out this infographic on what you need to make a good email signature that will work perfectly for your organization.
The view will learn how to download and install SIMTOOLS and FORMLIST into Excel, how to use SIMTOOLS to generate a Monte Carlo simulation of 30 sales calls, and how to calculate the conditional probability based on the results of the Monte Carlo …
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now