Дождитесь отправки на принтер (shellexecute), прежде чем продолжить - PullRequest
0 голосов
/ 27 апреля 2018

Я хочу распечатать все электронные письма и вложения в папке Outlook. Я хочу напечатать файлы Excel, Word и PFD.

Это работает, но не в правильном порядке. Письма и печатные вложения перепутаны. Поэтому я хочу синхронизировать печать. Процесс должен ждать, пока задание на печать не будет отправлено. Проблема, вероятно, в том, что команда ShellExecute работает асинхронно с VBA.

Так, как я могу позволить VBA ждать, пока ShellExecute не закончится. Я прочитал в MSDN, что мне нужно использовать CreateProcess, но я не знаю, как использовать команду печати для этого. Он только запускает приложение.

Я также пытался использовать метод Sleep в VBA, чтобы дать печати немного времени, но это не кажется правильным решением или работает очень хорошо. Пожалуйста, есть кто-нибудь совет?

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

1 Ответ

0 голосов
/ 27 апреля 2018

Объект WshShell предоставляет метод Run , который имеет необязательный параметр bWaitOnReturn. Он указывает, должен ли скрипт ждать завершения программы, прежде чем перейти к следующему оператору в вашем скрипте. Если установлено значение true, выполнение сценария останавливается до завершения программы, и Run возвращает любой код ошибки, возвращенный программой. Если установлено значение false (по умолчанию), метод Run возвращается сразу после запуска программы, автоматически возвращая 0 (не следует интерпретировать как код ошибки).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...