1

I want to print all emails and attachments of an Outlook folder. I want to print excel, word and pfd files.

This works but not in the right order. Emails en printed attachments get mixed-up. So i want to synchronize the printing. The process has to wait until the print job has been send. The problem is probably that ShellExecute command works asynchronically from the VBA.

So how can I let the VBA wait until the ShellExecute has finished. I've read on the MSDN that I have to use the CreateProcess but I don't know how to use a print command on this. It only runs an application.

I also tried to use the Sleep method in VBA to give the printing some time but it doesn't seems to be the right solution or work very good. Please has anyone an advice?

Private Declare Function ShellExecute Lib "shell32.dll" Alias _
      "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
      ByVal lpFile As String, ByVal lpParameters As String, _
      ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

      Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)



    Sub SaveBijlageArgumenten()

    SaveEmailAttachmentsToFolder "Postvak IN", "Account...", "xlsx", "xls", "pdf", "doc", "docx", "C:\....."

    End Sub



    Sub SaveEmailAttachmentsToFolder(OutlookInbox As String, OutlookAccount As String, _
                                    ExtString As String, ExtString2 As String, ExtString6 As String, ExtString3 As String, ExtString4 As String, _
                                    ExtString5 As String, DestFolder As String)

    Dim ns As NameSpace
    Dim Inbox As MAPIFolder
    Dim SubFolder As MAPIFolder
    Dim Item As Object
    Dim Atmt As Attachment
    Dim FileName As String
    Dim MyDocPath As String
    Dim I As Integer
    Dim wsh As Object
    Dim fs As Object
    Dim xlApp As Object
    Dim myBook As Object



    ' Create Excel Application
    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = False 'Visible is False by default, so this isn't necessary

    On Error GoTo ThisMacro_err

    Set ns = GetNamespace("MAPI")
    Set Inbox = ns.Folders(OutlookAccount)
    Set SubFolder = Inbox.Folders(OutlookInbox)



    I = 0

    ' Check subfolder for messages and exit of none found
    If SubFolder.Items.Count = 0 Then
        MsgBox "There are no messages in this folder : " &    OutlookFolderInInbox, _
               vbInformation, "Nothing Found"
        Set SubFolder = Nothing
        Set Inbox = Nothing
        Set ns = Nothing
        Exit Sub
    End If

    'Create DestFolder if DestFolder = ""
    Set fs = CreateObject("Scripting.FileSystemObject")
    If DestFolder = "" Then
        Set wsh = CreateObject("WScript.Shell")
        Set fs = CreateObject("Scripting.FileSystemObject")
        MyDocPath = wsh.SpecialFolders.Item("mydocuments")
        DestFolder = MyDocPath & "\" & Format(Now, "dd-mmm-yyyy hh-mm-ss")
        If Not fs.FolderExists(DestFolder) Then
            fs.CreateFolder DestFolder
        End If
    Else
        DestFolder = DestFolder & "\" & Format(Now, "dd-mmm-yyyy hh-mm-ss")
        If Not fs.FolderExists(DestFolder) Then
            fs.CreateFolder DestFolder
        End If
    End If

    If Right(DestFolder, 1) <> "\" Then
        DestFolder = DestFolder & "\"
    End If

    'On Error Resume Next
    ' Check each message for attachments and extensions

    For Each Item In SubFolder.Items
        Item.PrintOut Background:=False
        Item.UnRead = False

        Sleep 500

        For Each Atmt In Item.Attachments
            If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString) Or _
        LCase(Right(Atmt.FileName, Len(ExtString2))) = LCase(ExtString2) Then
                FileName = DestFolder & Item.SenderName & " " & Atmt.FileName
                Atmt.SaveAsFile FileName

                Set myBook = xlApp.Workbooks.Open(FileName, UpdateLinks:=0)

                myBook.PrintOut Background:=False
                myBook.Close SaveChanges:=False

                I = I + 1

            ElseIf LCase(Right(Atmt.FileName, Len(ExtString3))) = LCase(ExtString3) Or LCase(Right(Atmt.FileName, Len(ExtString4))) = LCase(ExtString4) _
                    Or LCase(Right(Atmt.FileName, Len(ExtString5))) = LCase(ExtString5) Then

                FileName = DestFolder & Item.SenderName & " " & Atmt.FileName
                Atmt.SaveAsFile FileName

                ShellExecute 0, "print", FileName, vbNullString, vbNullString, 0

                Sleep 3000

                I = I + 1

            End If



        Next Atmt

    Next Item

    On Error GoTo ThisMacro_err


    ' Show this message when Finished
    If I > 0 Then
        MsgBox "De bestanden in de bijlage zijn opgeslagen op onderstaande locatie: " _
             & DestFolder, vbInformation, "Klaar!"
    Else
        MsgBox "Er bevonden zich geen bijlagen bij de emails", vbInformation, "Klaar!"
    End If

    ' Clear memory
    ThisMacro_exit:
    Set SubFolder = Nothing
    Set Inbox = Nothing
    Set ns = Nothing
    Set fs = Nothing
    Set wsh = Nothing
    Set xlApp = Nothing
    Set myBook = Nothing
    Set AcroExchApp = Nothing
    Set AcroExchAVDoc = Nothing
    Exit Sub

    ' Error information
      ThisMacro_err:
    MsgBox "An unexpected error has occurred." _
         & vbCrLf & "Please note and report the following information." _
         & vbCrLf & "Macro Name: SaveEmailAttachmentsToFolder" _
         & vbCrLf & "Error Number: " & Err.Number _
         & vbCrLf & "Error Description: " & Err.Description _
         , vbCritical, "Error!"
    Resume ThisMacro_exit

End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
TallR
  • 11
  • 2
  • 1
    Possible duplicate of https://stackoverflow.com/questions/8902022/wait-for-shell-to-finish-then-format-cells-synchronously-execute-a-command There are a load of workable solutions there. – QHarr Apr 27 '18 at 06:11
  • Possible duplicate of [Wait for Shell to finish, then format cells - synchronously execute a command](https://stackoverflow.com/questions/8902022/wait-for-shell-to-finish-then-format-cells-synchronously-execute-a-command) – niton Apr 30 '18 at 11:41

1 Answers1

1

The WshShell object provides the Run method which has the bWaitOnReturn optional parameter. It indicates whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Thank you! I'm trying to figure out how I can use the Run method but don't get it right. Do you have an explame how I can use it in my code? The thing is I want to print the files. – TallR Apr 28 '18 at 05:23