Tải bản đầy đủ - 0 (trang)
Chapter 21. Sending and Receiving Workbooks

Chapter 21. Sending and Receiving Workbooks

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

21.1.SendMail

Table21-1liststhedifferentwaystosendmailwithinExcel.

Table21-1.SendingmailfromExcel

To



Use



Notes



Composeatext

emailmessage



TheFollowHyperLink

methodwiththemailto: Doesn'tsupportattachments.

protocol



Composeanemail

withanattached

workbook



TheDialogsmethodto

Usermustfillinaddressesandsubjectonthe

displaytheemaildialog

message.

box



Sendaworkbook



TheSendMailmethod



Doesn'tdisplaymessagebeforesend;shows

securitywarning.



Sendaworksheetor TheMailEnvelope

chart

property



UnlikeSendMail,thisallowsaccesstoCCand

BCClines;avoidssecuritywarning.(Requires

Outlook.)



Collectreview

comments



TheSendForReview

method



Allowsyoutolinktoasharedworkbookfor

collectingcomments.



Routeforapproval



TheRoutingSlipobject

andRoutemethod



Routestoaddressesinsequence.



I'veusedFollowHyperlinktechniqueafewtimesalreadyinthis

book.Incaseyoumissedit,here'sshortsample:



SubSendTextMail()

ThisWorkbook.FollowHyperlink"mailto:someone@microsoft.

"?Subject=Testmessage.&Body=Themessagegoeshere...

EndSub



Themailto:protocolstartstheuser'sdefaultemailclientand

createsanewmessage.It'suptotheusertosendthe

message,sotherearenorealsecurityhurdlestothisapproach.

Youcan'tattachfilesusingmailto:however.Tocreateaquick

emailwiththecurrentworkbookattached,usetheDialogs

methodasshownhere:

SubSendAsAttachment()

Application.Dialogs(xlDialogSendMail).Show

EndSub



Thatapproachcreatesanew,blankmessagewiththefile

attached.Theusermustfillintheaddressandaddthesubject

andbodyofthemessagebeforesendingthemessage.The

SendMailmethodalsosendstheworkbookasanattachment,but

itdoesn'tdisplaythemessagebeforeitissent.Thatposesa

riskbecauseyoudon'twantanyonesendingmailfromyour

systemwithoutyourknowledge.Toaddressthat,Outlook

displaysanoticeanytimeyouuseSendMail.Forexample,the

followingcodedisplaysthewarningshowninFigure21-1:



SubSendWorkbook()

'Traperrorincaseusercancelssend.

OnErrorResumeNext

'Sendthisworkbook(don'trunthisfromVBE!

'Itmaycausealockup.)

ThisWorkbook.SendMail"someone@microsoft.com","Please

OnErrorGoTo0

EndSub



Figure21-1.OutlookwarnsuserswhenExcel

sendsautomatedmail



You'llnoticethecommentswarnyounottorunSendMaildirectlyfrom

theVisualBasicEditor(aswhendebugging).ThatcanlockupExcel,

andtheonlywaytorecoveristousetheTaskManagertoclosethe

OutlookdialogboxthatappearswithanExceliconontheWindowstask

bar.



Sendingmailthiswayisn'tagreatpracticeinmyopinion.It's

muchbettertobeupfrontwithusers,showthemthemessage,

andletthemchoosewhethertosend.Todothat,usethe

MailEnvelopeproperty.Thefollowingcodecomposesamessage

containingtheactiveworksheetinExcelasshowninFigure212:

SubSendActiveSheet()

DimwsAsObject,envAsMsoEnvelope

'Gettheactivesheet.

Setws=ActiveSheet

'ShowemailheaderfromWorkbookobject.

ws.Parent.EnvelopeVisible=True



'GettheMsoEnvelopeobject

Setenv=ws.MailEnvelope

'Settheemailheaderfields.

env.Introduction="Salesinfirstquarter:"

Withenv.Item

.to="someone@yourcompany.com"

.cc="yourboss@yourcompany.com"

.subject=ws.Name

'Uncommentthistosendautomatically.

'.send

EndWith

EndSub



Withthisapproach,theusercanchoosetosendthemessageor

not,sothere'snoneedtodisplayasecuritywarning.However,

ifyouuncommenttheSendmethodintheprecedingcode,the

messageissentautomatically,sothewarninginFigure21-1

willappear.







21.2.WorkwithMailItems

IntheprecedingSendActiveSheetexample,theItemproperty

returnsaMailItemobject.ThatobjectispartoftheMicrosoft

OutlookobjectlibrarynotExcel's.TheMailItemobjectisvery

usefulinExcel,sinceitallowsyoutoattachfilesandcontrolall

aspectsofthemessage.

TousetheMailItemobject:

1. IntheVisualBasicEditor,chooseTools References.

VisualBasicdisplaystheReferencesdialogbox.

2. SelecttheMicrosoftOutlook11.0ObjectLibraryandclick

OK.

3. DeclareavariableusingtheMailItemtype.

4. GetareferencetotheMailItemobject.



Figure21-2.ComposinganemailinExcel



Thefollowingcodecreatesamailitemandattachesthecurrent

workbook:



SubSendAsMailItem()

'RequiresreferencetoMicrosoftOutlook

DimwsAsWorksheet,envAsMsoEnvelope,miAsMailItem

'Gettheactiveworksheet.

Setws=ActiveSheet

'Savetheworkbookbeforemailingasattachment.

ws.Parent.Save

'Showemailheader.

ws.Parent.EnvelopeVisible=True

'GettheMsoEnvelopeobject

Setenv=ws.MailEnvelope

'Settheemailheaderfields.

env.Introduction="Pleaserevewattachedfile."

'GettheMailItemobject.



Setmi=env.Item

'CleartheMailItemproperties.

ClearMessagemi

'SetMailItemproperties.

mi.Importance=olImportanceHigh

mi.To="someone@microsoft.com"

mi.CC="someoneelse@yourcompany.com"mi.Subject="

'Attachthisworkbook.

mi.Attachments.AddThisWorkbook.FullName

'Uncommentthistosendautomatically.

'mi.send

EndSub

SubClearMessage(miAsMailItem)

DimatAsAttachment

mi.Importance=olImportanceNormal

mi.To=""

mi.CC=""

mi.BCC=""

mi.Subject=""

ForEachatInmi.Attachments

at.Delete

Next

EndSub



TheprecedingClearMessageprocedureresetstheMailItem

propertiesbeforecreatinganewmessage.That'soneofthe

quirksoftheMailItemobject:itspropertysettingsarepreserved

andthereisnoresetmethodtoclearthem.Actually,onlysome

ofthepropertiesarepreserved;mostofthemareclearedwhen

yousavetheworkbook.However,that'sconfusing,soit'ssafer

toclearthepropertiesexplicitlyasshownbyClearMessage.

TheotherquirkoftheMailItemobjectisthatyoucangetatit

onlythroughaworksheetorchart.Thatmeansthatthebodyof



themailmessagecontainswhateverwasonthatworksheetor

chart.Oftenthat'swhatyouwant,butifyou'drathercreate

yourownmessagebody,closethemessage,thencallthe

Displaymethodasshownhere:



SubSendWorkbookAsMailItem()

'RequiresreferencetoMicrosoftOutlook

DimwsAsWorksheet,envAsMsoEnvelope,miAsMailItem

'Gettheactiveworksheet.

Setws=ActiveSheet

'Savetheworkbookbeforemailingasattachment.

ws.Parent.Save

'Showemailheader.

ws.Parent.EnvelopeVisible=True

'GettheMsoEnvelopeobject

Setenv=ws.MailEnvelope

'Settheemailheaderfields.

env.Introduction="Pleaserevewattachedfile."

'GettheMailItemobject.

Setmi=env.Item

'CleartheMailItemproperties.

ClearMessagemi

'SetMailItemproperties.

mi.Importance=olImportanceHigh

mi.To="someone@microsoft.com"

mi.CC="someoneelse@yourcompany.com"mi.Subject=A

mi.Body="Pleasereviewtheattachedworkbook."

'Attachthisworkbook.

mi.Attachments.AddThisWorkbook.FullName

'Closemessagecompositionheader(getsridofworkshe

mi.CloseolDiscard

'Openinmailmessagewindow.

mi.Display

EndSub



TheprecedingClose/DisplayTRickdisposesofthecontentfrom

theworksheetorchartandallowsyoutousetheBodyproperty

tosetthemessagebodyasshownbyFigure21-3.



Figure21-3.Sendingaworkbookasan

attachment



TheMailItemobjectrequiresthatyouuseOutlookasyouremail

application.Ifyoudon'tuseOutlook,readthefollowingsectionforan

alternateapproach.



21.3.CollectReviewComments

Anotherwaytosendtheentireworkbookasanattachmentisto

useSendForReview.Thatmethodcomposesanemailmessagewith

theworkbookasanattachment,plusitallowsyoutodisplay

themessageandthusavoidthesecuritywarning.Thefollowing

codesendstheactiveworkbookasamessageidenticaltothat

showninFigure21-3:

SubSendForReview()

ThisWorkbook.SendForReview"someone@microsoft.com",_

"Pleasereviewtheattachedworkbook",True,False

EndSub



SinceSendForReviewisintendedforcollectingreviewcomments,

themethoddisplaysadialogaskingifthefileshouldbesaved

asasharedworkbookbeforecomposingthemessage.There's

noeasywayaroundthat.Infact,sincesavingworkbooksas

sharedfilesisdifficultfromcode,you'vegottotakethesesteps

ifyouwanttosendaworkbookoutforreviewwithoutanyextra

prompts:

1. Createatemporarycopyoftheworkbook.

2. Openthatcopyandsaveitasasharedreviewcopy.

3. Getareferencetothesharedreviewcopyandsendthat

workbookforreview.

4. Closethesharedworkbookanddeletethetemporaryfile.

Thefollowingcodeillustratesthosesteps:

SubSendForReview()



Dimwb1AsWorkbook,wb2AsWorkbook,_

fnameAsString,tempAsString

'Gettheactiveworkbook.

Setwb1=ActiveWorkbook

'Createauniquetemporaryfilename

temp=wb1.Path&"\temp_"&CLng(Date)&".xls"

'Saveasatemporaryfile.

ThisWorkbook.SaveCopyAstemp

'Openthereviewcopy.

Setwb2=Workbooks.Open(temp)

'Createthenameofthefiletosend.

fname=wb1.Path&"\"&"ReviewCopyof"&_

wb1.Name

'Saveasasharedworkbook.

wb2.SaveAsfname,,,,,,xlShared,xlUserResolution

'Sendtheworkbookforreview.

ThisWorkbook.SendForReview"someone@microsoft.com",_

"Pleasereviewtheattachedworkbook",True,False

'Closethereviewcopy(returnstoActiveWorkbook).

wb2.CloseFalse

'Deletethetemporaryfile.

Killtemp

EndSub



That'scomplicated,butithastheadvantageofcreatinga

sharedreviewcopyseparatefromyourworkfile.Reviewerscan

returnchanges,whichyoucanmergeintothereviewcopy

withoutreplacingtheoriginalfile,whichhelpsprotectagainst

unwantedchanges.

Sharedworkbookscomewithsomerestrictions.Forinstance,

youcan'teditcodeinasharedworkbook.Also,shared

workbookscan'tcontainXMLmaps.UsingaSharePoint

workspaceisabettersolutionforcollaboratingonaworkbook.

SeeChapter8forinformationonsharingworkspacesthrough



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

Chapter 21. Sending and Receiving Workbooks

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

×