Tải bản đầy đủ - 0 (trang)
Hack 69. Send Access Data Through Outlook Automatically

Hack 69. Send Access Data Through Outlook Automatically

Tải bản đầy đủ - 0trang

The"Whensendingamessage"sectioncontainsacheckboxfor

"Automaticnamechecking,"asshowninFigure7-48.Checkthe

boxifyouwantOutlooktocheckaddresses,anduncheckitif

youwanttosimplysendthemessageswithoutchecking.

NowthatyouhavedeterminedhowyouwantOutlooktohandle

addresses,youarereadytobuildemailfunctionalityintoyour

application.Althoughyouwilleventuallywanttohavereports

basedonparameterizedqueriesthatgotodifferentusers,this

exampleshowshowtosendindividualreportstomultiple

recipients.



Figure7-46.Outlook'sOptionsdialog



Itshouldbenotedthattodealwiththeincreasingnumberof

problemswithviruses,Outlookpromptstheusertoallow

accesstotheaddressbookandtosendthemessages.Although

thispreventsyoufromsendingemailunattended,itiscertainly

mucheasierthandoingeverythingmanuallyeverytime.In

olderversionsofOutlook,youcansendmultipleemails

unattended.

Toaccomplishtheemailtask,createatablecalledtbl_Email



withtwotextfields:Email_Address(50characters)and

Report_Name(25characters).Youcanmakethefieldslargerif

itiswarranted.Ifyouuseautomaticnamechecking,youjust

needtoputinthedisplaynameofthepeopleyouwanttosend

themessagestointheEmail_Addressfield.Ifyouaren'tusing

automaticnamechecking,youneedtoenterthefullemail

address.Putintwoorthreerecordsforyourtest.

Inanormalapplicationenvironment,youwouldwantthistobe

drivenfromaform;however,thisexamplesimplysendsallthe

emailsthroughaprocedure.



Figure7-47.TheAdvancedE-mailOptionsdialog



Tocreatetheprocedure,gototheModulestabinAccess,and

clickNew.Onceyouareinablankmodule,gotoInsert

Procedure,makesuretheradioboxesforSubandPublicare

selected,andfillinSendOutlookEmailintheNametextbox.

Thiscreatestheshellforyourprocedure.

NowyouneedtocreateareferencetoMicrosoftOutlook.Do

thisbygoingtoTools Referencesandcheckingtheboxfor



theversionofOutlookthatyouhave.Nowyoucanreference

theOutlookobjectmodel.IfyouuseaversionofAccessother

thanAccess2003,youmightneedtochecktheboxfor

MicrosoftDataAccessObjects(mineisMicrosoftDAO3.6

ObjectLibrary).Nowyouarereadytobegincoding.



7.12.1.TheCode

ThecodeisshowninExample7-10.



Figure7-48.ChanginghowOutlookhandles

namesandemailaddresses



Example7-10.AccessVBAcodetosendemail

PublicSubSendOutlookEmail()

DimdbAsDAO.Database



DimReportRsAsDAO.Recordset

DimEmailRSAsDAO.Recordset

DimolAppAsOutlook.Application

DimolMailAsOutlook.MailItem

DimEmailCollAsCollection

DimvarEmailAsVariant

DimFileNameAsString

'Outlookonlyallowsoneinstancetobeopenatatime,

'soyoucancallitwithNewanditwillusetheinstance

'thatyoualreadyhaveopen.IsuggesthavingOutlookopen

'alreadysoyouarenotpromptedforusernameorpassword.

SetolApp=NewOutlook.Application

Setdb=CurrentDb

SetReportRs=db.OpenRecordset(_

"SelectReport_Namefromtbl_EmailGroupbyReport_Name")

ReportRs.MoveFirst



WhileNotReportRs.EOF

SetEmailColl=NewCollection

SetEmailRS=db.OpenRecordset(_

"SelectEmail_Addressfromtbl_EmailWhereReport_Name="

ReportRs.Fields(0).Value&""""&";")

EmailRS.MoveFirst

WhileNotEmailRS.EOF

EmailColl.AddEmailRS.Fields(0).Value

EmailRS.MoveNext

Wend

EmailRS.Close

SetEmailRS=Nothing

SetolMail=olApp.CreateItem(olMailItem)

olMail.subject="MonthlyReport"



ForEachvarEmailInEmailColl

olMail.Recipients.AddvarEmail

Next

olMail.Body="YourMonthlyReportisattached"

FileName="C:\Reports\"&ReportRs.Fields(0).Value&".rtf"

DoCmd.OutputToacReport,ReportRs.Fields(0).Value,_

acFormatRTF,FileName

'Ifyouhadmultipleattachments,youcouldaddthemoneat

olMail.Attachments.AddFileName,olByValue,1,"MonthlyRepor

olMail.Send

SetolMail=Nothing

SetEmailColl=Nothing

ReportRs.MoveNext

Wend



ReportRs.Close

SetReportRs=Nothing



SetolApp=Nothing

'YoucancloseOutlookwitholApp.Quit-butsinceIsuggest

'thatyoukeepitopenIamnotclosingithere

Setdb=Nothing

EndSub



Whenyourunthecode,youwillquicklybecomeannoyedatthe

numberofpromptsyoureceive.Asstatedearlier,thisismuch

betterthandoingitmanually,buttherehastobeabetterway.



ThecoderequiresseveralvariablesfortheOutlookobjectsanddata

objects;seeExample7-10fortheseitems.Thisexamplealsotakes

advantageoftheCollectionobject;however,youcanskipthatstepand

justusetherecordset.ThemainreasonthecodeusestheCollection



objectisthat,inmyproduction-automatedemailapplications,Ipass

Collectionstotheemailprocedureforthereportnamesandtheemail

addresses.ThisletsmeusethatsameprocedureinotherMicrosoft

OfficeapplicationssuchasExcelorWord,whereImightnotbeusing

recordsets.Theproceduresavesthereportsinadirectorycalled

C:\Reports;ifthisdirectorydoesn'texistonyoursystem,youcan

createthedirectory,oryoucanplacethereportsinadifferent

directory.



7.12.2.AnEasierWay

Nowthatyouarefamiliarwiththeitemstosendemailsthrough

Outlook,hereisaneasierwaytohandleit.Mostlikelythiswill

behelpfulonlyforlargejobsbecauseitrequirestwo-steps.

TheadjustedAccessprocedureinExample7-11changesthe

originalcodefromExample7-10tosavetheemailinstructions

inanADO.RecordsetXMLfile.Outlookthenprocessesthisfile.

YouwillneedtocreateareferencetoADOinboththeOutlook

andAccessVBAenvironments.

Example7-11.CreatinganXMLfilefromanADOrecordset

PublicSubCreateOutlookXML()

DimdbAsDAO.Database

DimReportRsAsDAO.Recordset

DimEmailRSAsDAO.Recordset

DimsaveRSAsADODB.Recordset

SetsaveRS=NewADODB.Recordset



saveRS.Fields.Append"Email_Address",adVarChar,50,adFldFixed

saveRS.Fields.Append"File_Name",adVarChar,50,adFldFixed

saveRS.Open

DimFileNameAsString



Setdb=CurrentDb

SetReportRs=db.OpenRecordset(_

"SelectReport_Namefromtbl_EmailGroupbyReport_Name")

ReportRs.MoveFirst

WhileNotReportRs.EOF

FileName="C:\Reports\"&ReportRs.Fields(0).Value&".rtf"



SetEmailRS=db.OpenRecordset(_

"SelectEmail_Addressfromtbl_EmailWhereReport_Name="&

ReportRs.Fields(0).Value&""""&";")

EmailRS.MoveFirst

WhileNotEmailRS.EOF

saveRS.AddNew

saveRS.Fields(0).Value=EmailRS.Fields(0).Value

saveRS.Fields(1).Value=FileName

saveRS.Update

EmailRS.MoveNext

Wend

EmailRS.Close

SetEmailRS=Nothing

DoCmd.OutputToacReport,ReportRs.Fields(0).Value,_

acFormatRTF,FileName

ReportRs.MoveNext

Wend

saveRS.Save"C:\Reports\EmailFile.xml",adPersistXML

saveRS.Close

SetsaveRS=Nothing

ReportRs.Close

SetReportRs=Nothing

Setdb=Nothing



EndSub



ThisproceduretakesadvantageofadisconnectedADO

recordset.WithADO,youcancreatearecordseton-the-fly

withoutconnectingtoadatabase.Inaddition,youmightalso

noticethatthisprocedurecreatesallthefilesOutlookwillsend

later.Ifyouwantto,youcanhaveastepthatrunsatthe

beginningoftheprocesstocreatetheXMLfilewithnorecords

andthenhavemultipleproceduresrunthatcontinuetoaddto

theXMLfiletobeprocessedbyOutlookataparticulartime.



7.12.3.MacrosinOutlook

Next,youneedtocreatetheOutlookprocedure.Tomakethis

work,youneedtoaddamacrotoyourOutlookenvironment.In

Outlook,selectTools Macros VisualBasicEditor,andclick

theThisOutlookSessionobjectintheProjectExplorer.Oncethere,

enterthecodeinExample7-12.

Example7-12.ProcessingtheADOrecordsetinOutlook



PublicSubEmailTest()

DimmiAsMailItem

DimvaritmAsVariant

DimadorsAsADODB.Recordset

Setadors=NewADODB.Recordset

adors.Open"C:\Reports\EmailFile.xml"

adors.MoveFirst

WhileNotadors.EOF

Setmi=Application.CreateItem(olMailItem)

mi.Recipients.Addadors.Fields(0).Value

mi.Subject="MonthlyReport"

mi.Body="Yourmonthlyreportisattached."

mi.Attachments.Addadors.Fields(1).Value,olByValue,1,"Monthl



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 69. Send Access Data Through Outlook Automatically

Tải bản đầy đủ ngay(0 tr)

×