I am using the following vba code in outlook to count all the emails in a folder and subfolders. But I want to edit my code so that it only counts the unread emails.
Is there a way I can do this and if so would someone please be able to show me how?
Sub HowManyEmails()
Dim objOutlook As Object, objnSpace As Object, objFolder As MAPIFolder
Dim objFolder2 As MAPIFolder
Dim objFolder3 As MAPIFolder
Dim objFolder4 As MAPIFolder
Dim objFolder5 As MAPIFolder
Dim objFolder6 As MAPIFolder
Dim objFolder7 As MAPIFolder
Dim objFolder8 As MAPIFolder
Dim objFolder9 As MAPIFolder
Dim objFolder10 As MAPIFolder
Dim objFolder11 As MAPIFolder
Dim objFolder12 As MAPIFolder
Dim objFolder13 As MAPIFolder
Dim objFolder14 As MAPIFolder
Dim EmailCount As Integer
Set objOutlook = CreateObject("Outlook.Application")
Set objnSpace = objOutlook.GetNamespace("MAPI")
On Error Resume Next
Set objFolder = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("3PL & HAULAGE")
Set objFolder2 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("ACCOMODATION")
Set objFolder3 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("CORE FLEET & EQUIPMENT")
Set objFolder4 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("LUBRICANTS & OILS")
Set objFolder5 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("MARKETING")
Set objFolder6 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("PLANT EQUIPMENT & TOOLS")
Set objFolder7 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("PROPERTY & REFURBISHMENT")
Set objFolder8 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("SECURITY & SYSTEMS")
Set objFolder9 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("SERVICING & REPAIRS")
Set objFolder10 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("STATIONARY")
Set objFolder11 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("TESTING & CALIBRATING")
Set objFolder12 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("UTILITIES: GAS, FUEL, ELECTRICAL (ENERGY)")
Set objFolder13 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("X-HIRE CRANE HIRE")
Set objFolder14 = objnSpace.Folders("Purchasing").Folders("Inbox").Folders("Suppliers").Folders("X-HIRE PLANT EQUIPMENT")
If Err.Number <> 0 Then
Err.Clear
MsgBox "No such folder."
Exit Sub
End If
EmailCount = objFolder.Items.Count
EmailCount2 = objFolder2.Items.Count
EmailCount3 = objFolder3.Items.Count
EmailCount4 = objFolder4.Items.Count
EmailCount5 = objFolder5.Items.Count
EmailCount6 = objFolder6.Items.Count
EmailCount7 = objFolder7.Items.Count
EmailCount8 = objFolder8.Items.Count
EmailCount9 = objFolder9.Items.Count
EmailCount10 = objFolder10.Items.Count
EmailCount11 = objFolder11.Items.Count
EmailCount12 = objFolder12.Items.Count
EmailCount13 = objFolder13.Items.Count
EmailCount14 = objFolder14.Items.Count
MsgBox "New Suppliers & New Business Report Sent"
TempFilePath = "\\UKSH000-File06\Purchasing\New_Supplier_Set_Ups_&_Audits\assets\"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<p style='color:#000;font-family:calibri;font-size:16'>Dear Jason," & vbNewLine & vbNewLine & _
"<br><br>" & "This is your weekly report, for " & "<b>" & "New Suppliers & New Business Introductions" & "</b>" & ", sent to you from NewSuppliers." & vbNewLine & _
"<br>" & "Please see a breakdown of different types of suppliers and new business below:" & vbNewLine & vbNewLine & _
"<br><br><br>" & "3PL & HAULAGE SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount & "</b></font>" & vbNewLine & _
"<br>" & "ACCOMODATION SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount2 & "</b></font>" & vbNewLine & _
"<br>" & "CORE FLEET & EQUIPMENT SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount3 & "</b></font>" & vbNewLine & _
"<br>" & "LUBRICANT & OILS SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount4 & "</b></font>" & vbNewLine & _
"<br>" & "MARKETING SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount5 & "</b></font>" & vbNewLine & _
"<br>" & "PLANT EQUIPMENT & TOOLS SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount6 & "</b></font>" & vbNewLine & _
"<br>" & "PROPERTY & REFURBISHMENT SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount7 & "</b></font>" & vbNewLine & _
"<br>" & "SECURITY & SYSTEMS SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount8 & "</b></font>" & vbNewLine & _
"<br>" & "SERVICING & REPAIRS SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount9 & "</b></font>" & vbNewLine & _
"<br>" & "STATIONARY SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount10 & "</b></font>" & vbNewLine & _
"<br>" & "TESTING & CALIBRATING SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount11 & "</b></font>" & vbNewLine & _
"<br>" & "UTILITIES & ENERGY SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount12 & "</b></font>" & vbNewLine & _
"<br>" & "X-HIRE CRANE SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount13 & "</b></font>" & vbNewLine & _
"<br>" & "X-HIRE PLANT SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount14 & "</b></font>" & vbNewLine & _
"<br><br><br>" & "If you have any queries please reply to this email, NewSuppliers#Hewden.co.uk." & vbNewLine & vbNewLine & _
"<br><br>" & "Kind Regards," & "</font></p>" & vbNewLine & _
"<p style='color:#000;font-family:calibri;font-size:18'><b>Automated Purchasing Email</font></p></b>" & vbNewLine & _
"<br><br><img src='cid:cover.jpg'" & "width='800' height='64'><br>" & vbNewLine & _
"<img src='cid:subs.jpg'" & "width='274' height='51'>"
With OutMail
.SentOnBehalfOfName = "newsuppliers#hewden.co.uk"
.To = "mark.o'brien#hewden.co.uk"
.CC = ""
.BCC = ""
.Subject = "New Suppliers & New Business Introduction - Weekly Report"
.HtmlBody = strbody
.Attachments.Add TempFilePath & "cover.jpg", olByValue, 0
.Attachments.Add TempFilePath & "subs.jpg", olByValue, 0
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
Dim dateStr As String
Dim myItems As Outlook.Items
Dim dict As Object
Dim msg As String
Set dict = CreateObject("Scripting.Dictionary")
Set myItems = objFolder.Items
myItems.SetColumns ("ReceivedTime")
' Determine date of each message:
For Each myItem In myItems
dateStr = GetDate(myItem.ReceivedTime)
If Not dict.Exists(dateStr) Then
dict(dateStr) = 0
End If
dict(dateStr) = CLng(dict(dateStr)) + 1
Next myItem
' Output counts per day:
msg = ""
For Each o In dict.Keys
msg = msg & o & ": " & dict(o) & " items" & vbCrLf
Next
Dim fso As Object
Dim fo As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set fo = fso.CreateTextFile("C:\Users\x152833\outlook_log.txt")
fo.Write msg
fo.Close
Set fo = Nothing
Set fso = Nothing
Set objFolder = Nothing
Set objnSpace = Nothing
Set objOutlook = Nothing
End Sub
You can use
unreadCount = myItems.Restrict("[Unread] = true").Count
You can also try to read the PR_CONTENT_UNREAD MAPI property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x36030003") using MAPIFolder.PropertyAccessor.GetProperty (the property is not guaranteed to be present). If the property is not present, you can catch the exception and fall back to Items.Restrict, which always works, but is a lot less efficient than PR_CONTENT_UNREAD.
Take a look at the folder with OutlookSpy (I am its author - click IMAPIFolder button) to check if PR_CONTENT_UNREAD property is available in your particular case.
It turned out to be quite easy, all you have to do is iterate through the Items collection of your objfolder objects and check the UnRead property of the items like this:
For Each i In objFolder.items
If (i.UnRead) Then
EmailCount = EmailCount + 1
End If
Next
However, I highly recommend getting rid of all those variables named objFolderxy and EmailCountxy. There is a much better way to do this. Consider the following example:
Sub GetFolderStats()
Dim objOutlook As Object, objnSpace As Object, objFolder As Object
Dim d
Set d = CreateObject("Scripting.Dictionary")
Set objOutlook = CreateObject("Outlook.Application")
Set objnSpace = objOutlook.GetNamespace("MAPI")
Set objFolder = objnSpace.Folders("Mailbox - CENSORED").Folders("Inbox").Folders("Suppliers")
For Each folder In objFolder.Folders
emailcount = 0
For Each i In folder.items
If (i.UnRead) Then
emailcount = emailcount + 1
End If
Next
d.Add folder.Name, emailcount
Next
Set d = Nothing
Set objOutlook = Nothing
Set objnSpace = Nothing
Set objFolder = Nothing
End Sub
Now, you might not need the dictionary at all, just wanted to give you an example how you could iterate through the email folders instead of explicitly specifying their names.
Of course, instead of storing these data in the dictionary, you could create the html markup on-the-fly thus there would be no need to process the dictionary saving a for loop.
Hope I could help...
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 am having difficulty adding an appointment to a coworkers calendar that they shared with me. The problem appears to be in the calendar reference. My appointments keep adding to their main default calendar while I am trying to add them to a separate shared calendar named "Study Schedule". I am running office 365.
Dim olApp As Outlook.Application
Dim olappt As Outlook.AppointmentItem
Dim bAppOpened As Boolean
Dim myNamespace As Outlook.NameSpace
Dim objRecip As Outlook.Recipient
Dim strName As String
Dim myFolder As Outlook.Folder
Const olAppointmentItem = 1
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Err.Clear
Set olApp = CreateObject("Outlook.Application")
bAppOpened = False ' Outlook was not already running, started it
Else
bAppOpened = True ' Outlook was already running
End If
' On Error GoTo Error_Handler
' Get Study Schedule Folder Location
Set myNamespace = olApp.GetNamespace("MAPI")
Set objRecip = myNamespace.CreateRecipient("John Doe")
objRecip.Resolve
' I believe the problem is in the two lines of code below as I try to reference non default folder (shared from john doe)
Set myFolder = myNamespace.GetSharedDefaultFolder(objRecip, olFolderCalendar)
Set myFolder = myFolder.Folders("Study Schedule")
myFolder.Display
Set olappt = myFolder.Items.Add
'Set olappt = myNewFolder.Items.Add
With olappt
.AllDayEvent = True
.Start = ScheduledDate
.Subject = StudyName
.Body = "Study has been scheduled." & vbCr & _
vbCr & _
"Calendar Assigned: " & myFolder & vbCr & _
"Schedule Entry ID: " & ScheduleEntryID & vbCr & _
"Study Name: " & StudyName & vbCr & _
"Scheduled Date: " & ScheduledDate & vbCr & _
vbCr & _
"Principle Investigator: " & PrincipleInvestigator & vbCr & _
"Order Placed By: " & OrderPlacedBy & vbCr & _
vbCr & _
"Species: " & Spec
ies & vbCr & _
"Strain: " & Strain & vbCr & _
"Sex " & Sex & vbCr & _
"Age: " & Age & vbCr & _
"Weight: " & Weight & " Kg" & vbCr & _
"Quantity : " & Quantity & vbCr & _
vbCr & _
"Study Information: " & StudyDescription & vbCr & _
vbCr & _
"This Event was auto generated from the Scheduling Assistant and In-Vivo Database."
.Location = ""
.Display
' .Save
' .Send
End With
... Rest of Code
Any help is greatly appreciated!
It is likely the shared calendar is at the same level as the default calendar.
' For a folder at the same level as the default calendar
' navigate up then back down
Set myFolder = myNamespace.GetSharedDefaultFolder(objRecip, olFolderCalendar)
Set myFolder = myFolder.Parent.Folders("Study Schedule")
I found a work around. The code I ended up going with is posted Below. Thank you everyone for the rapid responses! I really appreciated the help.
Dim olApp As Outlook.Application
Dim olappt As Outlook.AppointmentItem
Dim bAppOpened As Boolean
Dim myNamespace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim objPane As Outlook.NavigationPane
Dim objModule As Outlook.CalendarModule
Dim CalFolder As Outlook.Folder
Const olAppointmentItem = 1
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Err.Clear
Set olApp = CreateObject("Outlook.Application")
bAppOpened = False ' Outlook was not already running, started it
Else
bAppOpened = True ' Outlook was already running
End If
' On Error GoTo Error_Handler
On Error GoTo 0
Set objPane = Outlook.Application.ActiveExplorer.NavigationPane
Set objModule = objPane.Modules.GetNavigationModule(olModuleCalendar)
With objModule.NavigationGroups
For g = 1 To .Count
Set objGroup = .Item(g)
For i = 1 To objGroup.NavigationFolders.Count
Set objNavFolder = objGroup.NavigationFolders.Item(i)
If objNavFolder = "Study Schedule" Or objNavFolder = "John Doe - Study Schedule" Then
Set CalFolder = objNavFolder.Folder
MsgBox CalFolder
End If
Next
Next
End With
Set olappt = CalFolder.Items.Add
With olappt
.Display
.AllDayEvent = True
.Start = ScheduledDate
.Subject = StudyName
.Body = "Study has been scheduled." & vbCr & _
vbCr & _
"Schedule Entry ID: " & ScheduleEntryID & vbCr & _
"Study Name: " & StudyName & vbCr & _
"Scheduled Date: " & ScheduledDate & vbCr & _
vbCr & _
"Principle Investigator: " & PrincipleInvestigator & vbCr & _
"Order Placed By: " & OrderPlacedBy & vbCr & _
vbCr & _
"Species: " & Species & vbCr & _
"Strain: " & Strain & vbCr & _
"Sex " & Sex & vbCr & _
"Age: " & Age & vbCr & _
"Weight: " & Weight & " Kg" & vbCr & _
"Quantity : " & Quantity & vbCr & _
vbCr & _
"Study Information: " & StudyDescription & vbCr & _
vbCr & _
"This Event was auto generated from the Scheduling Assistant and In-Vivo Database."
.Location = ""
.Display
' .Save
' .Send
End With
I'm working on VBA to format an email that will have different text based on the values in the CheckReturnReason column in t1stNoticeEmails table.
I'm trying to format it so that if the specific reason is only listed once in the table, the email is formatted a specific way with a table displayed inside of it, and if a reason is listed more than once, a spreadsheet is attached with the information. This is how the code currently looks, which does not include anything addressing the Excel attachment for multiple entries.
How would I include different formatting if rst2.RecordCount > 1?
Sub FirstEmail_DuplicatePayment_ReviewVBA()
Dim rst As DAO.Recordset
Dim olApp As Outlook.Application
Dim objMail As Outlook.MailItem
Dim rst2 As DAO.Recordset
Dim strTableBeg As String
Dim strTableBody As String
Dim strTableEnd As String
Dim strFntNormal As String
Dim strTableHeader As String
Dim strFntEnd As String
Dim CheckNum As String
Dim NameOfRecipient As String
Dim StrSQL1 As String
Dim NameSpaceOutlook As Outlook.Namespace
Dim sAddressText As String
Dim sAddress1 As Variant
Dim sAddress2 As Variant
Dim sAddressCity As Variant
Dim sAddressState As Variant
Dim sAddressZip As Variant
gPARAttachment = "S:\UPAY\Z_NewStructure\..."
'SEND FIRST NOTICE EMAILS'
'------------------'
Set rst2 = CurrentDb.OpenRecordset("select distinct ContactEmails from t1stNoticeEmails WHERE CheckReturnReason = 'DuplicatePayment'")
If rst2.RecordCount = 0 Then 'checks if recordset returns any records and continues if records found and exits if no records found
Exit Sub
End If
rst2.MoveFirst
'Create e-mail item
Set olApp = Outlook.Application
Set objMail = olApp.CreateItem(olMailItem)
'Do Until rst2.EOF
Set olApp = Outlook.Application
Set objMail = olApp.CreateItem(olMailItem)
'Define format for output
strTableBeg = "<table border=1 cellpadding=3 cellspacing=0>"
strTableEnd = "</table>"
strTableHeader = "<font size=3 face='Calibri'><b>" & _
"<tr bgcolor=#4DB84D>" & _
td("CheckNumber") & _
td("PayeeName") & _
td("VendorID") & _
td("DocNo / ERNo / PONo") & _
td("Amount") & _
td("CheckDate") & _
"</tr></b></font>"
strFntNormal = "<font color=black face='Calibri' size=3>"
strFntEnd = "</font>"
Set rst = CurrentDb.OpenRecordset("SELECT * FROM t1stNoticeEmails where ContactEmails='" & rst2!ContactEmails & "' AND CheckReturnReason = 'DuplicatePayment' " _
& "Order by FullName asc")
If rst.RecordCount = 0 Then
rst2.Close
Set rst2 = Nothing
Exit Sub
End If
sAddress1 = rst!OriginalCheckAddress1
sAddress2 = rst!OriginalCheckAddress2
sAddressCity = rst!OriginalCheckCity
sAddressState = rst!OriginalCheckState
sAddressZip = rst!OriginalCheckZip
sAddressText = "<Font face='Calibri'>" _
& "The following check(s) sent to " _
& sAddress1 & " " & sAddress2 & " " & sAddressCity & " " & sAddressState & " " & sAddressZip _
& " have been returned to the University by the payee. <br><br>"
rst.MoveFirst
NameOfRecipient = rst!FullName
CheckNum = rst!CheckNumber
'Build HTML Output for the DataSet
strTableBody = strTableBeg & strFntNormal & strTableHeader
Do Until rst.EOF
strTableBody = _
strTableBody & _
"<tr>" & _
"<TD nowrap>" & rst!CheckNumber & "</TD>" & _
"<TD nowrap>" & rst!FullName & "</TD>" & _
"<TD nowrap>" & rst![VendorID/UIN] & "</TD>" & _
"<TD nowrap>" & rst![DocNo / ERNo / PONo] & "</TD>" & _
"<TD align='right' nowrap>" & Format(rst!AmountDue, "currency") & "</TD>" & _
"<TD nowrap>" & rst!OriginalCheckDate & "</TD>" & _
"</tr>"
rst.MoveNext
Loop
'rst.MoveFirst
strTableBody = strTableBody & strFntEnd & strTableEnd
'rst.Close
'Set rst2 = CurrentDb.OpenRecordset("select distinct ch_email from t_TCard_CH_Email")
'rst2.MoveFirst
Call CaptureDPBodyText
With objMail
'Set body format to HTML
.To = rst2!ContactEmails
.BCC = gDPEmailBCC
.Subject = gDPEmailSubject & " - Check# " & CheckNum & " - " & NameOfRecipient
.BodyFormat = olFormatHTML
.HTMLBody = .HTMLBody
.HTMLBody = .HTMLBody & "<HTML><BODY>" & strFntNormal & sAddressText & strTableBody & " </BODY></HTML>"
.HTMLBody = .HTMLBody & gDPBodySig
.SentOnBehalfOfName = "..."
.Attachments.Add gPARAttachment
.Display
'.Send
End With
rst2.MoveNext
'Loop
rst.Close
Set rst = Nothing
rst2.Close
Set rst2 = Nothing
End Sub`
I have found that RecordCount is not reliable with Access. I use something like rst.BOF=true AND rst.EOF=true to check for no returned records.
To see if more than one record was returned use
rst.MoveNext
if rst.EOF=false then <more than one record>
right after
rst.MoveFirst
essentially checking if reading after the first record got you to the end of the data.
In Access 2010 I have tables, e.g. Employee(Pracownicy). I can update the data in the table using the subform and the update button.
Updating the data in the subform automatically generates an Outlook mail containing the data in the updated record.
I need to change font color for updated data in the mail body.
The code to update the data and generate e-mail:
Private Sub cmdUpdate2_Click()
CurrentDb.Execute "update Pracownicy" & _
" SET Identyfikator='" & Me.txtID & "'" & _
", Imie='" & Me.txtImie & "'" & _
", Nazwisko ='" & Me.txtNazwisko & "'" & _
", Wiek ='" & Me.txtWiek & "'" & _
", Data_urodzenia ='" & Me.txtData & "'" & _
", Miejsce_urodzenia ='" & Me.txtMiejsce & "'" & _
", Miejscowosc ='" & Me.txtMiejscowosc & "'" & _
", Plec ='" & Me.txtPlec & "'" & _
" where Identyfikator='" & Me.txtID & "'"
'------------------------------------SEND EMAIL----------------------
'Dim varName As Variant
'Dim strUCC As String
Dim varSubject As Variant
Dim varBody As Variant
Dim Poczta As Object
Dim MojMail As Object
On Error Resume Next
'varName = ""
varSubject = "Employer List "
varBody = "Hello" & _
"<br><br>Employer List: " & _
"<br><br><B>Identyfikator:</B> " & Me.txtID & " " & _
"<br><B>Imie:</B> " & Me.txtImie & " " & _
"<br><B>Nazwisko:</B> " & Me.txtNazwisko & " " & _
"<br><B>Wiek:</B> " & Me.txtWiek & " " & _
"<br><B>Data urodzenia:</B> " & Me.txtData & " " & _
"<br><B>Miejsce urodzenia:</B> " & Me.txtMiejsce & " " & _
"<br><B>Miejscowosc:</B> " & Me.txtMiejscowosc & " " & _
"<br><B>Plec:</B> " & Me.txtPlec & " "
Set Poczta = CreateObject("outlook.application")
Set MojMail = Poczta.createitem(0)
With MojMail
'.To =
'.BCC =
.subject = varSubject
'.ReadReceiptRequested = True
'.originatorDeliveryReportRequested = True
.htmlbody = varBody & "<br>"
.display
'.send
End With
Set Poczta = Nothing
Set MojMail = Nothing
If Err.Number <> 0 Then
MsgBox ("Atention")
End If
On Error GoTo 0
'------------------------------------------------------------------------
DoCmd.Close
MsgBox ("End Update")
End Sub
I think this becomes more of an HTML question rather than VBA. Try adding a FONT tag to the following line and see if that works for you.
"<br><br><B><font color="red">Identyfikator:</font></B> " & Me.txtID & " " & _
I have the following code to monitor a drive. Now I an getting Echo for each file creation or deletion event.
Is there and way to modify the WScript.Echo to send a mail notification?
strDrive = "c"
arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & " and TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Instead of Echoing like below:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
I want to send a mail like this:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
With mailobj
.To = toAddress
.Subject = Subject
.HTMLBody = strHTML
.Send
End With
" & VbCrLf & "End Sub"
Is it possible or is there an other way to do this..?
I don't know what server do you use, but on Windows 2003 and 2008 e.g. you can use CDO object to create a email. You might use a smart host to send your email to.
Check this link: http://www.paulsadowski.com/wsh/cdo.htm
Also you can choose any free email component to create a email and use a smtp server to send your email. Or check this side where you can use a component including many examples how to do it: http://www.chilkatsoft.com/email-activex.asp.
** UPDATED **
This Script checks and send a email as you requestted:
strDrive = "d:"
Dim arrFolders(0) : arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
WScript.Echo "setup for folder: " & strFolder & vbLf
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * " _
& "FROM __InstanceOperationEvent " _
& "WITHIN 1 " _
& "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" _
& " AND TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & vbLf _
& " Wscript.Echo objObject.TargetInstance.PartComponent" & vbLf _
& " SendMail(objObject.TargetInstance.PartComponent)" & vbLf _
& "End Sub"
'WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Function SendMail(vBody)
Dim oMail : Set oMail = CreateObject("CDO.Message")
'Name or IP of Remote SMTP Server
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "your.smtp.server"
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMail.Configuration.Fields.Update
oMail.Subject = "Email Watch Info Message"
oMail.From = "alert#yourdomain.net"
oMail.To = "target#yourdomain.net"
oMail.TextBody = vBody
oMail.Send
End Function
Correct the settings in the send mail function and your are fine.
In theory, the VBSendMail DLL should be able to do what you want.