I developed a macro to save attached files from selected emails with a subject depending on the body.
I would like to make the macro select the emails instead of doing it manually.
Goal: Select emails depending on their subject and an specific date range.
Filter mails received in a specified date range which corresponds with subject "Ordenes" and come from "ordenes#ordenes.com". This must be done without reading every single email on the inbox folder as I do not have the option of moving historical ones to another folder (shared email).
Select the mails that match the previous step and then call a macro called "SaveAttachements".
I've been checking Items.Restrict, Items.Find, Explorer.Selection, Explorer.AddToSelection but I don't seem to be getting the right concept.
You can filter (select) emails with .Restrict, which allows multiple conditions.
Option Explicit
Private Sub restrict_SenderEmailAddress_Subject_DateRangeRecent()
Dim itms As Items
Dim resItms As Items
Dim itm As Object
Dim srchSenderEmailAddress As String
Dim srchSubject As String
Dim dateRangeDays As Long
Dim srchDatePeriod As String
Dim strFilterBuild As String
Dim resItmsBuild As Items
Dim strFilter As String
Dim i As Long
Set itms = Session.GetDefaultFolder(olFolderInbox).Items
'For i = 1 To itms.Count
' Debug.Print itms(i).SenderEmailAddress
'Next
srchSenderEmailAddress = "ordenes#ordenes.com"
' If you cannot get the quotes right all at once, build the filter.
strFilterBuild = "[SenderEmailAddress] = '" & srchSenderEmailAddress & "'"
Debug.Print strFilterBuild
Set resItmsBuild = itms.Restrict(strFilterBuild)
If resItmsBuild.Count = 0 Then
Debug.Print "No " & srchSenderEmailAddress & " email."
'MsgBox "No " & srchSenderEmailAddress & " email."
Exit Sub
End If
srchSubject = "Ordenes"
strFilterBuild = strFilterBuild & " And [Subject] = '" & srchSubject & "'"
Debug.Print strFilterBuild
Set resItmsBuild = itms.Restrict(strFilterBuild)
If resItmsBuild.Count = 0 Then
Debug.Print "No " & srchSenderEmailAddress & " email with subject " & srchSubject
'MsgBox "No " & srchSenderEmailAddress & " email with subject " & srchSubject
Exit Sub
End If
' adjust as needed
dateRangeDays = 1400
srchDatePeriod = Format(Date - dateRangeDays, "yyyy-mm-dd")
'Debug.Print srchDatePeriod
strFilterBuild = strFilterBuild & " And [ReceivedTime] > '" & srchDatePeriod & "'"
Debug.Print strFilterBuild
Set resItmsBuild = itms.Restrict(strFilterBuild)
resItmsBuild.sort "[ReceivedTime]", True
If resItmsBuild.Count = 0 Then
Debug.Print "No " & srchSenderEmailAddress & " email with subject " & srchSubject & " in the last " & dateRangeDays & " days."
'MsgBox "No " & srchSenderEmailAddress & " email with subject " & srchSubject & " in the last " & datePeriodDays & " days."
Exit Sub
End If
' This should match the final strFilterBuild to confirm it can be done all at once.
strFilter = "[SenderEmailAddress] = '" & srchSenderEmailAddress & "' And [Subject] = '" & srchSubject & "' And [ReceivedTime] > '" & srchDatePeriod & "'"
Debug.Print strFilter
Set resItms = itms.Restrict(strFilter)
resItms.sort "[ReceivedTime]", True
If resItms.Count = 0 Then
MsgBox "No " & srchSubject & " email on " & srchDatePeriod
End If
For i = 1 To resItms.Count
Debug.Print resItms(i).ReceivedTime & ": " & resItms(i).Subject
'SaveAttachments resItms(i)
Next
End Sub
Related
I would like to use DASL filter to:
Exclude a recipient's specific domain (e.g., #test.com)
Limit the result to one-to-one e-mail (only one recipient).
For the first point I thought about this query:
"urn:schemas:httpmail:displayto" LIKE '%#%'AND NOT "urn:schemas:httpmail:displayto" LIKE '%#test.com'
But it's not working,I still have e-mails with #test.com in the receiver list of several e-mails.
For the second point I have no idea how to limit to one recipient.
Thanks in advance.
Use the following opertor <> which means not equal in the search string:
"urn:schemas:httpmail:displayto" LIKE '%#%' AND "urn:schemas:httpmail:displayto" <> '%#test.com'
Two separate filters are easier to figure out.
Private Sub FindMail_RestrictDomainTest()
Dim olFolder As Folder
Dim strFilter As String
Dim foundItems As Items
Dim i As Long
Set olFolder = Session.GetDefaultFolder(olFolderInbox)
' You could generate two separate working filters
' Filter 1
strFilter = "#SQL=" & "urn:schemas:httpmail:displayto" & " Like '" & "%#%" & "'"
Debug.Print "strFilter: " & strFilter
Set foundItems = olFolder.Items.Restrict(strFilter)
Debug.Print "foundItems.Count: " & foundItems.count
' Filter 2
strFilter = "#SQL=" & "NOT urn:schemas:httpmail:displayto" & " Like '" & "%#test.com" & "'"
Debug.Print "strFilter: " & strFilter
' Filter ** foundItems ** not olFolder.Items
Set foundItems = foundItems.Restrict(strFilter)
Debug.Print "foundItems.Count: " & foundItems.count
For i = 1 To foundItems.count
If TypeOf foundItems(i) Is mailItem Then
With foundItems(i)
Debug.Print i & " - " & .ReceivedTime
Debug.Print " " & .subject
Debug.Print " " & .To
End With
End If
Next i
' Combined filters. There is no reason to do so.
strFilter = "#SQL=" & "urn:schemas:httpmail:displayto" & " Like '" & "%#%" & "' AND " & _
"NOT urn:schemas:httpmail:displayto" & " Like '" & "%#test.com" & "'"
Debug.Print "strFilter: " & strFilter
Set foundItems = olFolder.Items.Restrict(strFilter)
Debug.Print "foundItems.Count: " & foundItems.count
For i = 1 To foundItems.count
If TypeOf foundItems(i) Is mailItem Then
With foundItems(i)
Debug.Print i & " - " & .ReceivedTime
Debug.Print " " & .subject
Debug.Print " " & .To
End With
End If
Next i
End Sub
I have a list box that has three different categories to choose from on the form. I have vba code that is working that allows me to select more than one item in the list box which is fine. But the items I am selecting I am having troubles to get the results that I need.
For an Example; The three categories within the list box are not in the query with the actual category names. One Category I have is called "Picking" okay, I want to select "picking" and then when the button is clicked I want it to pull all Items within the query field "Item Number" that equals '0801' which represents the Category "Picking".
Note the code behind the button is a simple "On Click" Event Procedure
**The List box I am Having troubles with is called (StrAccounts)
**Picking which is the same thing as Acct in the query that I am trying filter on in in tbUpload
**I want the "Picking" Category in the List box to filter on Acct in the query where Acct = '0801'
**Placed_Orders which the Second category name within my ListBox and it is the same field in the query above "tbUpload", Acct, except I want
this Placed_Orders to get all Acct in ('1108', '1114', '1117', '1113',
'1110')
**Whatever Acct in the query tbUpload that doesn't contain the following numbers already mention above is the third category in my
list box which is "Not_Placed"
**So whenever Not_Placed in the list box is clicked and the search button is selected I want Accts in the query to pull, Accts <>
'0801','1108','1114','1117','1113','1110'
Private Sub cmdSearch_Click()
Dim Varitem As Variant
Dim StrDEPT_OBS As String
Dim StrStatus As String
Dim StrACCT As String
Dim strSQL As String
Dim StrAccounts As String
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me!List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me!List_Dept_OBS.ItemData(Varitem) & "'"
Next
'get selections from Status multiselect listbox
For Each Varitem In Me!List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me!List_Status.ItemData(Varitem) & "'"
Next
'get selections from Accts multiselect listbox
For Each Varitem In Me!List_ACCTs.ItemsSelected
StrStatus = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1)
Else: MsgBox "You must enter an OBS"
Exit Sub
End If
If Len(StrStatus) > 0 Then
StrStatus = Right(StrStatus, Len(StrStatus) - 1)
End If
If Len(StrAccounts) > 0 Then
StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStatus & ") "
End If
If Len(StrAccounts) = 0 And StrAccounts = "Picking" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If Len(StrAccounts) = 0 And StrAccounts = "Placed_Orders" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
strSQL = strSQL & "tbUpload.ACCT <> (" & [0801] & [1108] & [1114] & [1117] & [1113] & [1110] & ") " "Not_Placed"
End If
DoCmd.SetWarnings False
''DoCmd.OpenQuery ("UPLOAD")
Me![tbUpload subform].Form.RecordSource = strSQL
End Sub
If Len(StrAccounts) > 0 Then
'' StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
StrAccounts = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStat us & ") "
End If
If StrAccounts = "Lugging" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If StrAccounts = "Structure" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
End If
Consider:
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me.List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me.List_Dept_OBS.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = "[Dept_ID] IN(" & Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1) & ") AND "
Else
MsgBox "You must enter an OBS"
Exit Sub
End If
'get selections from Status multiselect listbox
For Each Varitem In Me.List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me.List_Status.ItemData(Varitem) & "'"
Next
If Len(StrStatus) > 0 Then
StrStatus = "[OPR_STAT_ID] IN(" & Right(StrStatus, Len(StrStatus) - 1) & ") AND "
End If
'get selection from Accts single select listbox and build account parameters array
Select Case Me.List_Accts
Case "Picking"
StrAccounts = "ACCT = 0801 AND "
Case "Placed_Orders"
StrAccounts = "ACCT IN(1108,1114,1117,1113,1110) AND "
Case "Not_Placed"
StrAccounts = "NOT ACCT IN(0801,1108,1114,1117,1113,1110) AND "
End Select
strSQL = StrDEPT_OBS & StrStatus & StrAccounts
If strSQL <> "" Then
strSQL = " WHERE " & Left(strSQL, Len(strSQL) - 5)
End If
Me.[tbUpload subform].Form.RecordSource = "SELECT * FROM tbUpload" & strSQL & ";"
For more info on dynamically building search criteria with VBA, review http://allenbrowne.com/ser-62.html
This code is designed to detect the columns of start and finish of a shape which is used and displayed onto the caption of the shape itself. The following code is the problematic code:
Sub Take_Baseline()
Dim forcast_weeksStart() As String
Dim forcast_weeksEnd() As String
Dim forcastDate As String
Dim shp As Shape
Dim split_text() As String
'cycle through all the shapes in the worsheet and enter the forcast date for all the projects into their respective boxes
For Each shp In ActiveSheet.Shapes
'initialize forcast date by parsing
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
forcast_weeksEnd = Split(shp.BottomRightCell.Column.Text, " ")
forcastDate = forcast_weeksStart(1) & "-" & forcast_weeksEnd(1)
temp = shp.OLEFormat.Object.Object.Caption
If InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") Then
split_text = Split(shp.OLEFormat.Object.Caption, " ")
For i = 0 To (i = 3)
shp.TextFrame.Characters.Caption = split_text(i) & vbNewLine
Next i
ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "/" & "actualDate"
' ElseIf InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") = 0 Then
'split_text = Split(shp.OLEFormat.Object.Object.Caption, " ")
' For i = 0 To (i = 2)
' shp.OLEFormat.Object.Caption = split_text(i) & vbNewLine
' Next i
'ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & "In Prog" & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "actualDate"
End If
Next shp
'For testing purposes
Sheet4.Range("A20").Value = forcast_weeksStart(1)
Sheet4.Range("A21").Value = forcast_weeksEnd(1) End Sub
The error is an
"invalid qualifier"
message which occurs on line
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
Right on the "column" word. I don't get why this is happening since the actual drop down menu has the column operation which i can select. I have tried everything from changing it to the OLEformat.Object.Caption etc etc. But nothing has worked. I am still relatively new to vba so any help will be appreciated. Thanks
I am supposed to receive an email with the subject "Testing Protocol" from "BobSmith#company.com" every day.
Is there a way to search my Outlook Inbox to determine if an email has come through with that subject and that sender for the current day? Id like a simple "Yes" or "No" to be placed in cell A1 of "Control" if it has or has not been received today.
Below is what I have tried to come up with on my own using previous questions with no luck.
Any help is greatly appreciated. EmailSubject = "Testing Protocol"
Private Sub Application_Reminder(ByVal Item As Object)
Dim EmailSubject As Range
Set EmailSubject = Sheets("Control").Range("EmailSubject")
If Item.Class = olTask Then
If InStr(Item.Subject, EmailSubject) > 0 Then
ReminderUnreceivedMail
End If
End If
End Sub
Sub ReminderUnreceivedMail()
Dim Itms As Items
Dim srchSender As String
Dim srchSubject As String
Set Itms = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
srchSender = "BobSmith#company.com"
srchSubject = EmailSubject
Set Itms = Itms.Restrict("[SenderName] = "BobSmith#company.com" And
[Subject] = EmailSubject And [SentOn] > '" & Format(Date, "yyyy-mm-dd") &
"'")
If Itms.Count = 0 Then
MsgBox "No " & srchSubject & " email on " & Format(Date, "yyyy-mm-dd")
End If
Set Itms = Nothing
End Sub
Likely wrong format for srchSender and combining a filter, for me, requires a confusing sequence of matching quotes.
Private Sub ReminderUnreceivedMail()
Dim Itms As items
Dim srchSender As String
Dim srchSubject As String
Dim strFilterBuild As String
Dim ItmsBuild As items
Dim strFilter As String
Set Itms = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).items
Dim i As Long
For i = 1 To Itms.count
Debug.Print Itms(i).senderName
Next
srchSender = "what you see in senderName from the above"
srchSubject = "EmailSubject"
' If you cannot get the quotes right all at once, build the filter.
strFilterBuild = "[SenderName] = '" & srchSender & "'"
Debug.Print strFilterBuild
Set ItmsBuild = Itms.Restrict(strFilterBuild)
If ItmsBuild.count = 0 Then
MsgBox "No " & srchSender & " email."
GoTo ExitRoutine
End If
strFilterBuild = strFilterBuild & " And [Subject] = '" & srchSubject & "'"
Debug.Print strFilterBuild
Set ItmsBuild = Itms.Restrict(strFilterBuild)
If ItmsBuild.count = 0 Then
' This should find old mail
MsgBox "No " & srchSender & " email with subject " & srchSubject
GoTo ExitRoutine
End If
strFilterBuild = strFilterBuild & " And [SentOn] > '" & Format(Date, "yyyy-mm-dd") & "'"
Debug.Print strFilterBuild
Set ItmsBuild = Itms.Restrict(strFilterBuild)
If ItmsBuild.count = 0 Then
MsgBox "No " & srchSender & " email with subject " & srchSubject & " today"
GoTo ExitRoutine
End If
' This should match the final strFilterBuild to confirm it can be done all at once.
strFilter = "[SenderName] = '" & srchSender & "' And [Subject] = '" & srchSubject & "' And [SentOn] > '" & Format(Date, "yyyy-mm-dd") & "'"
Debug.Print strFilter
Set Itms = Itms.Restrict(strFilter)
If Itms.count = 0 Then
MsgBox "No " & srchSubject & " email on " & Format(Date, "yyyy-mm-dd")
End If
ExitRoutine:
Set Itms = Nothing
End Sub
I have a macro that pulls from an Access DB and writes the recordset to the spreadsheet based upon dates that are entered into a userform. However, if I enter in "3/2/2105" and "3/5/2015" it returns all the records from 3/2-3/5 and then 3/20-3/31. I cannot think of any reason why it would do this. If anybody could point me in the right direction/make suggestions it would be greatly appreciated.
Sub pullfrommsaccess()
queryform.Show
Dim conn As Object
Dim rs As Object
Dim AccessFile As String
Dim SQL As String
Dim startdate As String
Dim enddate As String
Dim i As Integer
Sheet2.Cells.Delete
Application.ScreenUpdating = False
AccessFile = ThisWorkbook.Path & "\" & "mdidatabase.accdb"
On Error Resume Next
Set conn = CreateObject("ADODB.connection")
If Err.Number <> 0 Then
MsgBox "Connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
On Error GoTo 0
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
If tblname = "Attainments" Then
If shift1 = "1" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift1 = "1" And shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
End If
If tblname = "MDItable" Then
If shift1misses = "1" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift1misses = "1" And shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
End If
On Error Resume Next
Set rs = CreateObject("ADODB.Recordset")
If Err.Number <> 0 Then
Set rs = Nothing
Set conn = Nothing
MsgBox "Recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
On Error GoTo 0
rs.CursorLocation = 3
rs.CursorType = 1
rs.Open SQL, conn
If rs.EOF And rs.BOF Then
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Application.ScreenUpdating = True
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
For i = 0 To rs.Fields.Count - 1
Sheet2.Cells(1, i + 1) = rs.Fields(i).Name
Next i
'Copy From RecordSet to Excel and Reset
Sheet2.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "The records from " & pastdate & " and " & currentdate & " were successfully retrieved from the '" & tblname & "' table!", vbInformation, "Done"
End If
Call TrimALL
End Sub
You have a field named Date, try renaming that and reworking the code as in first instance that's a reserved word and is a bad idea for starters!
When working with dates, see Allen Browne's comments on the matter here for consistency;
http://allenbrowne.com/ser-36.html
You have your dates declared as string, but in your SQL query you're surrounding them with a ' not a #. It should read;
Date Between " & "#" & pastdate & "# " & "and" & " #" & currentdate & "#"
All of the above should sort you out, if not comment and I'll take a much closer look for you!