Solved

Outlook VBA Save PDF's Error

Posted on 2014-04-20
15
400 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Office 365 Training for IT Pros

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

 

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
 

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 47

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

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
EXCEL String-handling question ... 7 51
Open attachments in viewer, not main app 4 29
Excel - Active X Checkboxes Groups 45 35
Outlook mail to Access 8 21
You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
The viewer will learn how to simulate a series of coin tosses with the rand() function and learn how to make these “tosses” depend on a predetermined probability. Flipping Coins in Excel: Enter =RAND() into cell A2: Recalculate the random variable…
The viewer will learn how to simulate a series of sales calls dependent on a single skill level and learn how to simulate a series of sales calls dependent on two skill levels. Simulating Independent Sales Calls: Enter .75 into cell C2 – “skill leve…

734 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