Fornecimento de atualizações de status para macro que entra em estado de não resposta até a conclusão

StackOverflow https://stackoverflow.com//questions/9622983

  •  09-12-2019
  •  | 
  •  

Pergunta

Eu tenho uma macro VBA para pesquisar arquivos de email.

Ao pesquisar dezenas de milhares de e-mails (ou mesmo apenas algumas centenas em minha máquina de teste), ele exibe o status por alguns segundos e, em seguida, entra no estado Não respondendo enquanto analisa o restante dos e-mails.

Isso fez com que usuários impacientes encerrassem a tarefa prematuramente e gostaria de corrigir isso fornecendo atualizações de status.

Codifiquei a solução a seguir e acredito que o problema está na maneira como o GarbageCollector funciona no VBA durante o Loop.

Public Sub searchAndMove()

    UserForm1.Show

    ' Send a message to the user indicating
    ' the program has completed successfully, 
    ' and displaying the number of messages sent during the run.

End Sub

Private Sub UserForm_Activate()

Me.Width = 240
Me.Height = 60

Me.Label1.Width = 230
Me.Label1.Height = 50

Dim oSelectTarget As Outlook.Folder
Dim oMoveTarget As Outlook.Folder
Dim oSearchCriteria As String

' Select the target folder to search and then the folder to
' which the files should be moved
Set oSelectTarget = Application.Session.PickFolder
Set oMoveTarget = Application.Session.PickFolder

oSearchCriteria = InputBox("Input search string: ")

Dim selectedItems As Outlook.Items
Set selectedItems = oSelectTarget.Items
Dim selectedEmail As Outlook.MailItem

Dim StatusBarMsg As String
StatusBarMsg = ""

Dim initialCount As Long
initialCount = selectedItems.count


Dim movedCounter As Long
movedCounter = 0
Dim x As Long
Dim exists As Long

' Function Loop, stepping backwards
' to prevent errors derived from modifying the collection
For x = selectedItems.count To 1 Step -1
    Set selectedEmail = selectedItems.Item(x)
    ' Test to determine if the subject contains the search string

    exists = InStr(selectedEmail.Subject, oSearchCriteria)
    If Len(selectedEmail.Subject) > 999 Then
        selectedEmail.Move oMoveTarget
    Else:
        If exists <> 0 Then
            selectedEmail.Move oMoveTarget
            movedCounter = (movedCounter + 1)
        Else: End If
    End If
    Set selectedEmail = Nothing
    StatusBarMsg = "Processing " & x & " out of " & initialCount & " messages."

    UserForm1.Label1.Caption = StatusBarMsg
    UserForm1.Repaint
Next x

Dim Msg As String
Dim Response
Msg = "SearchAndMove has detected and moved " & movedCounter & _
  " messages since last run."
Response = MsgBox(Msg, vbOKOnly)


' Close the References to prevent a reference leak
Set oSelectTarget = Nothing
Set oMoveTarget = Nothing
Set selectedItems = Nothing
Set selectedEmail = Nothing

Unload Me

End Sub
Foi útil?

Solução

Mude a linha

UserForm1.Repaint

para

DoEvents

Sim, isso aumentará o tempo de execução, mas caso haja milhares de e-mails, você não terá muita opção.

DICA: Além disso, você pode querer mudar

StatusBarMsg = "Processing " & x & " out of " & initialCount & " messages."

para

StatusBarMsg = "Please do not interrupt. Processing " & x & " out of " & initialCount & " messages."

Também é aconselhável informar ao seu usuário no início do processo que pode levar algum tempo e portanto ele poderá executar o processo quando tiver certeza de que não deseja trabalhar naquele pc.

Algo assim

Sub Sample()
    Dim strWarning As String
    Dim Ret

    strWarning = "This process may take sometime. It is advisable to run this " & _
    "when you don't intend to use the pc for sometime. Would you like to Continue?"

    Ret = MsgBox(strWarning, vbYesNo, "Information")

    If Ret <> vbYes Then Exit Sub

    For x = SelectedItems.Count To 1 Step -1

    '~~> Rest of the code
End Sub

HTH

Sid

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top