query outlook using vba

Status
Not open for further replies.

Bruce Jackson

Member
Outlook version
Outlook 2016 32 bit
Email Account
POP3
Is it possible to search outlook using a query in a vba script .I have a 3 calendars set up where I write to outlook and insert delivery job numbers and some information pertaining to the job as appointments
I would like to clear the calendar of that job number entry once the delivery has been made
I currently use
For Each oObject In oFolder.Items ,which checks each item of outlook to see if the particular job number exists
and if it does it clears the entry
the problem with that method is as each day passes the script takes longer and longer to execute
I need some way to query outlook,to cut down on checking every single item
 
Below is the method i use to find and delete travel times from old appt. i'm not sure its any faster to use count over for each... but when i run (usually monthly), i need to delete 30 or 40 old events. (Will need to test it again one using find)

what you need to use is find or restrict - one sample is here How to print a list of recurring dates using VBA

Code:
Sub BlockedTimeDelete()
    Dim objOutlook As Outlook.Application
    Dim objNamespace As Outlook.NameSpace
    Dim objSourceFolder As Outlook.MAPIFolder
    Dim objVariant As Variant
    Dim lngMovedItems As Long
    Dim intCount As Integer
   
    Set objOutlook = Application
    Set objNamespace = objOutlook.GetNamespace("MAPI")
    Set objSourceFolder = objNamespace.GetDefaultFolder(olFolderCalendar)
    
    For intCount = objSourceFolder.Items.Count To 1 Step -1
        Set objVariant = objSourceFolder.Items.Item(intCount)
        DoEvents
        If objVariant.Subject = "Travel Time" Or objVariant.Subject = "Meeting Review Time" Then
            If objVariant.Start < Now Then
              objVariant.Delete
             
              'count the # of items moved
               lngMovedItems = lngMovedItems + 1
            End If
        End If
    Next
   
    ' Display the number of items that were moved.
    MsgBox "Moved " & lngMovedItems & " messages(s)."
End Sub
 
This is faster - i need it to delete one of two subjects and will need to work on that, but for single subjects it is faster.

Code:
Sub DeleteBlockedTime()
   
   Dim CalFolder As Outlook.MAPIFolder
   Dim CalItems As Outlook.Items
   Dim ResItems As Outlook.Items
   Dim sFilter, strSubject, strOccur As String
   Dim iNumRestricted As Integer
   Dim itm, ListAppt As Object
   Dim tStart, tEnd As Date
   ' Use the selected calendar folder
   Set CalFolder = Application.ActiveExplorer.CurrentFolder
   Set CalItems = CalFolder.Items

   ' Sort all of the appointments based on the start time
   CalItems.Sort "[Start]"
   CalItems.IncludeRecurrences = True

   ' Set an end date
    tEnd = Format(Now, "Short Date")
   
    strSubject = "Travel Time"

   'create the Restrict filter by day and recurrence
   sFilter = "[End] < '" & tEnd & "' And [Subject] = " & strSubject
Debug.Print sFilter
   Set ResItems = CalItems.Restrict(sFilter)

   iNumRestricted = 0

   'Loop through the items in the collection.
   For Each itm In ResItems
      iNumRestricted = iNumRestricted + 1
      itm.Delete
   Next
  
   Set itm = Nothing
   Set ListAppt = Nothing
   Set ResItems = Nothing
   Set CalItems = Nothing
   Set CalFolder = Nothing
  
End Sub
 
Thanks Diane
if I understand this correctly-that gets all items between dates,then loops through each item checking for the string value passed ?
where did you set your tStart in this code and how would the sfilter look with the tStart
Thanks for your help
 
This sorts the calendar by date (in a hidden list view) and then looks for events matching the filter conditions- in my case, looking for the end date and subject. If it finds it, the item is deleted.

Note that if you are deleting more than one item, it will skip some - as many as every other one - because it "loses count" when you delete items and it moves forward (if you have 4 items and delete # 1, outlook moves to #2, which was previously #3). In my tests with 8 travel and review events, it skipped one or two when i used case statements and ran the filter twice, but 4 when i put both subjects in the same filter. The first macro steps backward so the count isn't affected.

I'm only checking the end date (which is the same as the start date for one day events, which all are so it doesn't make a difference here...). if you need to check the start date, you'd basically copy the tEnd code and change it to tStart. Or since the only place that Start or End really matters is in the filter, you could just change [End] to [Start]. If you need to check both start and end, you'd add [Start] < '" & tStart & to the filter (with the proper # of " and ')
 
Thanks Diane
I am not sure about the losing count- I loop through a recordset in an access db and delete one record in outlook for each loop in the database.when I first started it took outlook maybe a few secs per record,and all up maybe 1 minute for the script to complete
now-its 10mins and rising,which is not sustainable
thanks again
I will experiment a bit-and see how I go
 
it should work fine for you if its one item per loop. I don't know if it would be much faster, but if outlook could get an array of the search terms, it might be faster to run everything in Outlook. Using an array rather than reading the access data base over and over would be faster too.
 
I could pass a string array to outlook-delimted by what ever outlook would recognise
of course to build the array would require looping through the recordset-but that happens very quickly using vba within access.
what how would I pass that to outlook to process
 
The problem isn't how fast Access does it, it's that Outlook needs to keep reading it (or Access needs to keep going back to Outlook). If you can read the db once, it eliminates one step that gets repeated many times.

This page is not a really good example because it uses an array in the macro - i'll see if i can find an example from reading a file -
Using Arrays in Outlook macros

once the array is in the variant in memory, you do roll through the array doing whatever....

For i = LBound(arrSubject) To UBound(arrSubject)

sFilter = "[End] < '" & tEnd & "' And [Subject] = " & arrSubject(i)
Debug.Print sFilter
Set ResItems = CalItems.Restrict(sFilter)

iNumRestricted = 0

'Loop through the items in the collection.
For Each itm In ResItems
iNumRestricted = iNumRestricted + 1
itm.Delete
Next

Next i
 
heres the sub I use
Public Sub DeleteScheduledJob(ByVal argSubject As String, MailName As String)

'the job number I delete is supplied in argSubject

Dim OApp As Object
Dim oNameSpace As Object
Dim oApptItem As Object
Dim oFolder As Object
Dim oMeetingoApptItem As Object
Dim oObject As Object
Dim sErrorMessage As String

On Error Resume Next
' check if Outlook is running
Set OApp = CreateObject("Outlook.Application")


On Error GoTo Err_Handler
Set oNameSpace = OApp.GetNamespace("MAPI")
Set oFolder = GetFolderPath(MailName & "\Calendar")
For Each oObject In oFolder.Items
If oObject.Class = olAppointment Then
Set oApptItem = oObject
If InStr(oApptItem.Subject, argSubject) > 0 Then
oApptItem.Delete

End If
End If
Next oObject

Set OApp = Nothing
Set oNameSpace = Nothing
Set oApptItem = Nothing
Set oFolder = Nothing
Set oObject = Nothing
Set oMeetingoApptItem = Nothing

Exit Sub

Err_Handler:
sErrorMessage = Err.Number & " " & Err.Description

End Sub

I could add another argument to the sub containing the string array built in the calling sub
just not sure what I need to do to use that array
 
this is how I could supply a comma delimted array of job numbers to delete
Public Sub DeleteScheduledJob(ByVal argSubject As String, MailName As String)

dim myarray

myarray=split(argSubject,",")
from here I am lost as to how to use the array
hope this is making sense to you
again-thanks for the help
 
on the macro - are you the only user? it might speed it up a little to use early binding to the outlook object model. late binding is easier when you are sharing it with others.



Something like this should work -

For i = LBound(myarray) To UBound(myarray)

sFilter = "[End] < '" & tEnd & "' And [Subject] = " & myarray(i)
Debug.Print sFilter
Set ResItems = CalItems.Restrict(sFilter)

iNumRestricted = 0

'Loop through the items in the collection.
For Each itm In ResItems
iNumRestricted = iNumRestricted + 1
itm.Delete
Next

Next i
 
unfortunately I need to use late binding as it has several users and I can never be sure what version of outlook they use
I will give it a try and see how I go
I got the guy who looks after outlook 365 for this company to clean up and archive outlook items
hes also set up some automatic archiving(whatever that means)-and the script is back running fast (delete 40 entries in maybe 10 secs)
I don't understand the outlook model -its methods and propertys,and what you can or cant do -so it will be trial and error for me
Regards
 
Yeah, in that case you definitely need late binding.

>> I got the guy who looks after outlook 365 for this company to clean up and archive outlook items
It sounds like the problem was due, in part, to so many items to search though.
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
T Query about one aspect of migrating .pst files from Outlook 2003 to Outlook 2013 Using Outlook 5
C Outlook local calendar & iCloud calendar syncing query Using Outlook 3
D outlook 2003/2007 macro query Using Outlook 2
I Help with Smart Folder + Query Builder on IMAP Using Outlook 0
O Filter-Query Builder-Description - what field name to use? Using Outlook 4
D Create advanced search (email) via VBA with LONG QUERY (>1024 char) Outlook VBA and Custom Forms 2
M WMI query for Get Disk IO performance in exchange Exchange Server Administration 0
B Select / activate first email item in the searched query Using Outlook 1
Q Mail account setup query Using Outlook 0
T Query About "Delay Delivery" Function Using Outlook 5
S Subject add ticket number from URL query Outlook VBA and Custom Forms 2
P Calendar permissions query Using Outlook 1
R 'Display as' email query Using Outlook 1
C 'Show as conversation' query Using Outlook 0
C Unusual Signature & Spell Check Query Using Outlook 1
A Advanced find query facilty Help please Using Outlook 2
J Rule Category Conditions Query Outlook VBA and Custom Forms 1
J Opening an existing message from a database query Outlook VBA and Custom Forms 1
H Force Outlook 2019 with GMail 2-Step to Require Login? Using Outlook 0
G Retaining Tabs in outlook body Using Outlook 2
V Setting up Outlook 2021 on new computer Using Outlook 2
G Add Map It button to Custom Contacts Form in Outlook Outlook VBA and Custom Forms 1
X Custom icon (not from Office 365) for a macro in Outlook Outlook VBA and Custom Forms 1
Victor_50 Problem - Google Workspace will stop "unsafe" access to Outlook end 2024 Using Outlook 3
C New pc, new outlook, is it possible to import auto-complete emailaddress Using Outlook 4
T Outlook 365 won't take new working password Using Outlook 0
S Create Outlook Task from Template and append Body with Email Body Outlook VBA and Custom Forms 4
P Can't add custom field to custom Outlook form, it always adds to the Folder instead Outlook VBA and Custom Forms 2
B Sync Outlook Public Folders to Contacts Using Outlook 2
D Delete Outlook emails from MS server Using Outlook 9
B Outlook tasks and PDF Using Outlook 4
D Outlook 2019 is no longer asking for password ... Using Outlook 5
Kika Melo How to mark as Junk any message not from Contacts (in Outlook.com) Using Outlook 3
L Outlook attachments from OneDrive as links Using Outlook 0
G Outlook 365 My iCloud Outlook doesn’t work after reinstalling Microsoft365 on Windows 10 PC – now I get error message on contacts and calendar Using Outlook 1
T How to Export & Import GMAIL Contacts into Outlook 2021 ? Using Outlook 4
M Synchronization and backup of Outlook from local to server. Using Outlook 8
T How to get an EVENT COLOR option in Outlook 2021 ? Using Outlook 0
K How can I delete an e-mail from Outlook Using Outlook 1
V Outlook Error The Attempted operation Failed. An Object Could Not be found Outlook VBA and Custom Forms 0
P Yahoo/IMAP folder rename by Outlook desktop 365 Using Outlook 0
A Outlook 2019 folder counter Using Outlook 0
A Relocate Search Bar in Outlook Using Outlook 2
e_a_g_l_e_p_i Need clarification on 2-Step Verification for Gmail using Outlook 2021 Using Outlook 10
L Opening People Outlook 2021 Using Outlook 2
e_a_g_l_e_p_i Outlook 2021 not letting me setup my Gmail using pop Using Outlook 1
Geldner Problem submitting SPAM using Outlook VBA Form Outlook VBA and Custom Forms 2
P VBA to add email address to Outlook 365 rule Outlook VBA and Custom Forms 0
M Outlook 2016 outlook vba to look into shared mailbox Outlook VBA and Custom Forms 0
P Can no longer sync Outlook with iPhone calendar after iPhone update to 17.1.1 Using Outlook 7

Similar threads

Back
Top