Proporcionar actualizaciones de estado para Macro que no responde al estado hasta que finalice hasta completar
-
09-12-2019 - |
Pregunta
Tengo una macro VBA para buscar archivos de correo electrónico.
Al buscar a través de decenas de miles de correos electrónicos, (o incluso un par de cientos en mi máquina de prueba) Muestra el estado durante unos segundos, luego ingresa a un estado que no responde mientras se ejecuta a través del resto de los correos electrónicos.
Esto ha llevado a los usuarios impacientes para cerrar la tarea prematuramente, y me gustaría rectificarlo proporcionando actualizaciones de estado.
He codificado la siguiente solución y creo que el problema radica en la forma en que funciona el garbagecollector en VBA durante el bucle.
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
Solución
Cambiar la línea
UserForm1.Repaint
a
DoEvents
Sí, esto aumentará el tiempo de ejecución, pero en caso de que haya miles de correos electrónicos, entonces no tiene mucha opción.
consejo: También es posible que desee cambiar
StatusBarMsg = "Processing " & x & " out of " & initialCount & " messages."
a
StatusBarMsg = "Please do not interrupt. Processing " & x & " out of " & initialCount & " messages."
También es recomendable informar a su usuario al comienzo del proceso que puede tomar tiempo y, por lo tanto, puede ejecutar el proceso cuando están seguros de que no quieren trabajar en esa PC?
algo como este
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