microsoft office object model - documentation & help · about secure deployment of managed com...
TRANSCRIPT
MicrosoftOfficeObjectModelAnswerWizard AnswerWizardFiles
AssistantBalloon
BalloonCheckboxesBalloonCheckbox
BalloonLabelsBalloonLabel
COMAddInsCOMAddIn
CommandBarButtonCommandBarCommandBarControlsCommandBarControl
CommandBarComboBoxCommandBarCommandBarControlsCommandBarControl
CommandBarPopupCommandBarCommandBarControlsCommandBarControl
CommandBars
CommandBarCommandBarControlsCommandBarControl
DocumentLibraryVersionsDocumentLibraryVersion
DocumentPropertiesDocumentProperty
FileDialogFileDialogFiltersFileDialogFilter
FileDialogSelectedItems
FileSearchFileTypesFoundFilesPropertyTestsPropertyTest
SearchFoldersScopeFolderScopeFolders
SearchScopesSearchScopeScopeFolderScopeFolders
HTMLProjectHTMLProjectItemsHTMLProjectItem
LanguageSettings
MsoEnvelope
NewFile
ODSOColumnsODSOColumn
ODSOFiltersODSOFilter
OfficeDataSourceObject
PermissionUserPermission
ScriptsScript
SharedWorkspaceSharedWorkspaceFilesSharedWorkspaceFile
SharedWorkspaceFoldersSharedWorkspaceFolder
SharedWorkspaceLinksSharedWorkspaceLink
SharedWorkspaceMembersSharedWorkspaceMember
SharedWorkspaceTasksSharedWorkspaceTask
SignatureSetSignature
SmartDocument
Sync
WebPageFontsWebPageFont
NewObjectsVisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOffice2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsobjectsaddedtotheMicrosoftOffice2003objectmodel.
Object Description
DocumentLibraryVersion Asinglesavedbackupcopyorversionofashareddocument.
DocumentLibraryVersions AcollectionofDocumentLibraryVersionobjects.
Permission Managesdocumentpermissions;also,acollectionofUserPermissionobjects.
SharedWorkspace Managesadocumentsavedinasharedworkspace.
SharedWorkspaceFile Afilesavedinasharedworkspace.SharedWorkspaceFiles AcollectionofSharedWorkspaceFileobjects.SharedWorkspaceFolder Asubfolderinasharedworkspace.
SharedWorkspaceFolders AcollectionofSharedWorkspaceFolderobjects.
SharedWorkspaceLink Alinksavedinasharedworkspace.SharedWorkspaceLinks AcollectionofSharedWorkspaceLinkobjects.SharedWorkspaceMember Auserofasharedworkspace.
SharedWorkspaceMembers AcollectionofSharedWorkspaceMemberobjects.
SharedWorkspaceTask Atasksavedinasharedworkspace.SharedWorkspaceTasks AcollectionofSharedWorkspaceTaskobjects.
SmartDocument ManagesanattachedXMLexpansionpackwhichtransformsadocumentintoasmartdocument.
Sync Managesthesynchronizationbetweenthelocalcopyandtheservercopyofashareddocument.
UserPermission Asetofpermissionsonadocumentforasingleuser.
NewProperties(AlphabeticalList)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOffice2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistspropertiesaddedtotheMicrosoftOffice2003objectmodel(sortedalphabetically).
NewProperty Object(s)AssignedTo SharedWorkspaceTaskComments DocumentLibraryVersionConnected SharedWorkspace
CreatedBySharedWorkspaceFile,SharedWorkspaceFolder,SharedWorkspaceLink,SharedWorkspaceTask
CreatedDateSharedWorkspaceFile,SharedWorkspaceFolder,SharedWorkspaceLink,SharedWorkspaceTask
DocumentAuthor PermissionDomainName SharedWorkspaceMemberDueDate SharedWorkspaceTaskEmail SharedWorkspaceMemberEnableTrustedBrowser PermissionErrorType SyncExpirationDate UserPermissionFolderName SharedWorkspaceFolderFolders SharedWorkspaceIsVersioningEnabled DocumentLibraryVersions
ItemCountExceeded
SharedWorkspaceFiles,SharedWorkspaceFolders,SharedWorkspaceLinks,SharedWorkspaceMembers,SharedWorkspaceTasks
LastRefreshed SharedWorkspaceLastSyncTime SyncLinks SharedWorkspaceMembers SharedWorkspaceModified DocumentLibraryVersion
ModifiedBy
SharedWorkspaceFile,SharedWorkspaceFolder,SharedWorkspaceLink,SharedWorkspaceTask,DocumentLibraryVersion
ModifiedDateSharedWorkspaceFile,SharedWorkspaceFolder,SharedWorkspaceLink,SharedWorkspaceTask
Notes SharedWorkspaceLinkPermission UserPermissionPermissionFromPolicy PermissionPolicyDescription PermissionPolicyName PermissionRequestPermissionURL PermissionSolutionID SmartDocumentSolutionURL SmartDocumentSourceURL SharedWorkspaceStatus SharedWorkspaceTask,SyncStoreLicenses PermissionTasks SharedWorkspaceUserId UserPermissionWorkspaceLastChangedBy Sync
NewProperties(byObject)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOffice2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistspropertiesaddedtotheMicrosoftOffice2003objectmodel(sortedbyobjectname).
Object NewPropertiesDocumentLibraryVersion Comments,Modified,ModifiedByDocumentLibraryVersions IsVersioningEnabled
Permission
DocumentAuthor,EnableTrustedBrowser,PermissionFromPolicy,RequestPermissionURL,StoreLicenses,PolicyDescription,PolicyName
SharedWorkspace Connected
SharedWorkspaceFile CreatedBy,CreatedDate,ModifiedBy,ModifiedDate
SharedWorkspaceFiles ItemCountExceeded
SharedWorkspaceFolder CreatedBy,CreatedDate,FolderName,ModifiedBy,ModifiedDate
SharedWorkspace FoldersSharedWorkspaceFolders ItemCountExceededSharedWorkspace LastRefreshed
SharedWorkspaceLink Notes,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate
SharedWorkspace LinksSharedWorkspaceLinks ItemCountExceededSharedWorkspaceMember DomainName,EmailSharedWorkspace MembersSharedWorkspaceMembers ItemCountExceededSharedWorkspace SourceURL
SharedWorkspaceTask AssignedTo,CreatedBy,CreatedDate,DueDate,ModifiedBy,ModifiedDate
SharedWorkspace TasksSharedWorkspaceTasks ItemCountExceededSharedWorkspaceTask StatusSmartDocument SolutionID,SolutionURL
Sync ErrorType,LastSyncTime,Status,WorkspaceLastChangedBy
UserPermission ExpirationDate,Permission,UserId
NewMethods(AlphabeticalList)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOffice2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsmethodsaddedtotheMicrosoftOffice2003objectmodel(sortedalphabetically).
NewMethod ObjectApplyPolicy PermissionCreateNew SharedWorkspaceDisconnect SharedWorkspaceGetUpdate SyncOpenVersion SyncPickSolution SmartDocumentPutUpdate SyncRefresh SharedWorkspaceRefreshPane SmartDocumentRemoveAll PermissionRemoveDocument SharedWorkspaceResolveConflict SyncRestore DocumentLibraryVersionUnsuspend Sync
NewMethods(byObject)VisittheOfficeDeveloperCenterontheMicrosoftDeveloperNetworkWebsiteforthelatestinformationaboutprogrammingwithOffice2003,includingproductnews,technicalarticles,downloads,andsamples.
ThefollowingtablelistsmethodsaddedtotheMicrosoftOffice2003objectmodel(sortedbyobjectname).
NewMethod ObjectDocumentLibraryVersion RestorePermission ApplyPolicy,RemoveAll
SharedWorkspace CreateNew,Disconnect,Refresh,RemoveDocument
SmartDocument PickSolution,RefreshPane
Sync GetUpdate,OpenVersion,PutUpdate,ResolveConflict,Unsuspend
SecurityNotesforMicrosoftOfficeSolutionDevelopersAboutSettingMicrosoftOffice2003SecurityinaTestingEnvironmentMicrosoftOffice2003MacroandAdd-inSecuritySettingsMatrixAboutEnabling"Trustallinstalledadd-insandtemplates"AboutModifyingtheMicrosoftWindowsRegistryAboutMakingMicrosoftWindowsApplicationProgrammingInterface(API)FunctionCallsAboutDigitalCodeSigningAboutSecureDeploymentofManagedCOMAdd-insinMicrosoftOffice2003AboutAutomatingtheVisualBasicEditorAboutPasswordsAboutMicrosoftOfficeOutlook2003SecuritySettings
AboutSettingMicrosoftOffice2003SecurityinaTestingEnvironment
ToinstallandrunanunsignedCOMadd-inorMicrosoftVisualBasicforApplications(VBA)macro,thesecuritysettingsintheSecuritydialogbox(Toolsmenu,Macrosubmenu,Securitycommand)mustbesettoMedium,withtheTrustallinstalledadd-insandtemplatescheckboxcleared.Itisstronglyrecommendedthatyoudothisonlyinatestingenvironment.Afteryouhavecompletedyourtesting,setthesecuritylevelbacktoVeryHighorHigh.
CautionBysettingthesecurityleveltoMedium,withtheTrustallinstalledadd-insandtemplatescheckboxcleared,userswillhavethechoicetoeitherenableordisableunsignedCOMadd-insandVBAmacroswhentheyareprompted.IfyoursecuritylevelissettoVeryHighorHigh,withtheTrustallinstalledadd-insandtemplatescheckboxcleared,allunsignedCOMadd-insandVBAmacroswillbedisabledautomatically.Therefore,itisstronglyrecommendedthatalluserskeeptheirsecuritylevelssettoVeryHighorHighwiththeTrustallinstalledadd-insandtemplatescheckboxcleared.
MicrosoftOffice2003MacroandAdd-inSecuritySettingsMatrix
ThefollowingtableliststheavailableMicrosoftOffice2003securitysettings,alongwiththeircorrespondingbehaviors,intheSecuritydialogbox(Macrossubmenu,Toolsmenu).
Office2003macroandadd-insecuritysettingoptions
Securitylevel
Digitallysigned?
Fromtrustedsources? Office2003will
VeryHigh Yes Yes Loadtheadd-inormacrosilently
Yes No Notloadtheadd-inormacro No N/A Notloadtheadd-inormacroHigh Yes Yes Loadtheadd-inormacrosilently
Yes No Prompttotrustthesourceandenabletheadd-inormacrotorun
No N/A Notloadtheadd-inormacroMedium Yes Yes Loadtheadd-inormacrosilently
Yes No Prompttotrustthesourceandenabletheadd-inormacrotorun
No N/A Prompttoenableordisabletheadd-inormacro
Low YesorNo YesorNo Loadtheadd-inormacrosilently
NoteTheavailabilityof,andoptionswithin,theSecuritydialogboxvarydependingonthespecificOfficeapplication.Additionally,specificOfficeapplicationssilentlyloadsignedadd-insandmacrosonlyfromspecificdirectories,alongwithregisteredCOMadd-insandsmarttagsrecognizers.
Formoreinformationonthesesettingsandontheotherissuesdiscussedinthistopic,searchfor"Officemacrosecurity"intheMicrosoftDeveloperNetwork(MSDN)Library.
AboutEnabling"Trustallinstalledadd-insandtemplates"
TheTrustallinstalledadd-insandtemplatescheckboxiscommonlymisunderstood.Bydefaultitisenabled,butMicrosoftrecommendsthatcustomerswithhighsecurityrequirementsdisableit,andthisisagood"defenseindepth"approach.
IfyouhavenoneedtorununsignedpersonalmacrosorunsignedCOMadd-ins,youshoulddisablethisoption.WhenOfficeapplicationsecuritylevelissettoVeryHighorHigh,withtheTrustallinstalledadd-insandtemplatesoptiondisabled,alladd-insandtemplatesthatarenotsignedwillautomaticallybedisabled.Iftheadd-insandtemplatesaresignedusingacertificatenotlistedintheTrustedSourceslist,auserwillbepromptedtotrustthesourceinordertoallowtheadd-inortemplatetorun.
EnablingtheTrustallinstalledadd-insandtemplatescheckboxwillallowallCOMadd-insthathavebeeninstalledintheregistry(whichrequiresadministrativeprivileges)orVBAmacrosthatarestoredinyourpersonalorworkgrouplocationstorun,regardlessofwhethertheyaresignedornot.Itshouldalsobenotedthatend-usersdonotneedadministrativeprivilegestoinstallVBAmacrostocertaintemplateandstartupfolders.ExamplesoftheselocationsinOfficeWord2003are:
\DocumentsandSettings\<username>\ApplicationData\Microsoft\Word\STARTUP\DocumentsandSettings\<username>\ApplicationData\Microsoft\Templates
WiththeTrustallinstalledadd-insandtemplatesoptionenabled,youcanbeattackedifyoudownload,register,andrunamaliciousCOMadd-inorifyourunamalicioustemplatefromsomeoneelse.
IfyoudecidetorunpersonalVBAmacrosortorunlocallyinstalledCOMadd-ins,andyoudon'twanttopurchaseadigitalcertificate,butyouwanttodisabletheTrustallinstalledadd-insandtemplatesoption,herearetheavailablealternatives:
SignyourpersonalVBAmacrosorlocallyinstalledCOMadd-insusingatestcertificatecreatedusingeitherselfcert.exeorAuthenticodetools,dependingonwhetherit'samacrooradd-in.Thisway,youcankeepyoursecuritysettingssettoVeryHighorHigh,withtheTrustallinstalledadd-insandtemplatesoptiondisabled.Formoreinformationonhowtogenerateatestcertificate,refertotheAboutDigitalCodeSigningsectionbelow.SetyourOfficeapplicationsecurityleveltoMediumwithTrustallinstalledadd-insandtemplatesdisabled.Withthesesecuritysettings,youwillbepromptedtoenableordisableaCOMadd-inorVBAmacrowhentheapplicationislaunched.It'sstronglyrecommendedthatyouusethesesettingsonlyinatestingenvironment.
AboutModifyingtheMicrosoftWindowsRegistry
ModifyingtheMicrosoftWindowsregistryinanymanner,whetherthroughtheRegistryEditororprogrammatically,alwayscarriessomedegreeofrisk.Incorrectmodificationcancauseseriousproblemsthatmayrequireyoutoreinstallyouroperatingsystem.Itisalwaysagoodpracticetobackupacomputer'sregistryfirstbeforemodifyingit.IfyouarerunningMicrosoftWindowsNT,MicrosoftWindows2000,MicrosoftWindowsXP,orMicrosoftWindowsServer2003,youshouldalsoupdateyourEmergencyRepairDisk(ERD).
Forinformationabouthowtoedittheregistry,viewthe"ChangingKeysandValues"HelptopicintheRegistryEditor(Regedit.exe)orthe"AddandDeleteInformationintheRegistry"and"EditRegistryInformation"topicsintheRegistryEditor(Regedt32.exe).
AboutMakingMicrosoftWindowsApplicationProgrammingInterface(API)FunctionCalls
BeforecallingMicrosoftWindowsAPIfunctions,youshouldunderstandhowargumentsanddatatypesarehandledbytheWindowsAPIDLLs.IncorrectlycallingWindowsAPIfunctionsmayresultininvalidpagefaultsorotherunexpectedbehaviors.FormoreinformationoncallingWindowsAPIfunctions,seethetopic"TheWindowsAPIandOtherDynamic-LinkLibraries"intheMicrosoftOffice2003DeveloperOnlineDocumentationortheMicrosoftDeveloperNetwork(MSDN)Library.
AboutDigitalCodeSigning
Manysecurity-conscioususersandadministratorssettheirMicrosoftOffice2003securitylevelstoVeryHighorHighwiththeTrustallinstalledadd-insandtemplatescheckboxcleared(locatedintheSecuritydialogbox,Macrosubmenu,Toolsmenu),whichishighlyrecommended.Withthesesettings,asignedandtrustedCOMadd-inorVBAmacrowillbeloaded,andanon-signedCOMadd-inorVBAmacrowillbedisabledautomatically.TheonlytimeauserwillbepromptedtoeitherenableordisableaCOMadd-inorVBAmacroiswhenaCOMadd-inorVBAmacroissignedbutthesoftwarepublisherisnotincludedintheTrustedSourceslist.
MicrosoftAuthenticodetechnologyallowssoftwarepublisherstodigitallysignexecutable(EXE)files,ActiveXcontrol(OCX)files,cabinet(CAB)files,anddynamic-linklibrary(DLL)files.Forastep-by-stepguideonhowtodigitallysignaCOMadd-inusingMicrosoftAuthenticodetechnology,searchfor"digitalcodesigning"intheMSDNLibrary.
AboutSecureDeploymentofManagedCOMAdd-insinMicrosoftOffice2003
TocomplywithOffice2003security,managedCOMadd-ins(COMadd-instargetingthecommonlanguageruntime)mustbedigitallysigned,andusers'securitysettingsshouldbesettotheirhighestlevels.Additionally,youwillneedtoincorporateintoyourmanagedCOMadd-inprojectasmallunmanagedproxycalledashiminordertoavoidunexpectedsecuritywarnings.Fordetails,searchfor"deploymentmanagedadd-ins"intheMSDNLibrary.
AboutAutomatingtheVisualBasicEditor
InOffice2003,whencallingthefeaturesoftheMicrosoftVisualBasicforApplicationsExtensibilityobjectmodel,youmayreceiveanerrormessagethatprogrammaticaccesstotheVisualBasicprojectisnottrusted.Topreventthismessagefromappearing,pointtoMacroontheToolsmenu,andthenclickSecurity.OntheTrustedSourcestab,checktheTrustaccesstoVisualBasicProjectbox.Bycheckingthisbox,macrosinanydocumentsthatyouopencanaccessthecoreMicrosoftVisualBasicobjects,methods,andproperties,whichrepresentsapossiblesecurityhazard.ThedefaultbehaviorinOffice2003istonotallowmacrostoprogrammaticallyaccesstheVisualBasicobjectmodel.TherecommendedbehavioristochecktheTrustaccesstoVisualBasicProjectboxonlyforthedurationofamacrothataccessestheVisualBasicobjectmodel.TheTrustaccesstoVisualBasicProjectboxshouldbeuncheckedafterthemacrohasfinishedrunning.
AboutPasswords
Avoidusinghard-codedpasswordsinyourapplications.Ifapasswordisrequiredinaprocedure,requestthepasswordfromtheuser,storeitinavariable,andthenusethevariableinyourcode.
Alwaysusestrongpasswords.Strongpasswordsshouldcontain:
Bothlowercaseanduppercasecharacters.Numbers.Symbols(suchas#,$,%,and^).Atleasteightcharacters.
Strongpasswordsshouldnotcontainpatterns,themes,orwordsfoundinadictionary.
Examplesofstrongpasswordsinclude:
$tR0n9p@$sG80dn[s$M4!
NoteYoushouldchangeyourpasswordfrequently;forexample,everyonetothreemonths.
AboutMicrosoftOfficeOutlook2003SecuritySettings
COMAdd-insUsingDefaultSecurity
InMicrosoftOfficeOutlook2003,allCOMadd-insthatrunonacomputerwhichisnotconfiguredtoobtainsecuritysettingsfromaMicrosoftExchangeServerareconsideredtrustedbydefault.Thisimpliesthattheadd-insthatrunonclientsthatarenotExchangeclientsandtheadd-insthatusedefaultsecurityinExchangeenvironmentsaretrustedautomatically.AsinOutlook2002,OfficeOutlook2003trustsonlythemainApplicationobjectthatispassedtotheOnConnectioneventoftheadd-in.
COMAdd-insUsingSecuritySettingsfromanExchangeServer
TherehasbeennochangeinthewayOfficeOutlook2003trustsCOMadd-insinanExchangeenvironmentwhenthesecuritysettingsareobtainedfromtheExchangeserver.Anadd-inwillbeconsideredtrustedonlyifit’sregisteredintheSecuritySettingsfolder.Again,asinOutlook2002,OfficeOutlook2003trustsonlythemainApplicationobjectthatispassedtotheOnConnectioneventoftheadd-in.
ImprovementstoOutlookObjectModelGuardandtheImpact
OfficeOutlook2003inheritstheOutlook2002objectmodelguardbehaviorand,inaddition,blockscodethatattemptstoaccesstheBodyandHTMLBodypropertiesofvariousOutlookitems.Thisallowsuserstoverifythattheprogramoradd-inaccessingtheBodyandHTMLBodypropertiesoftheseitemsistrustworthy,beforetheyallowaccesstothecontentsoftheitems.AlthoughthischangeforcesthedisplayofsecuritywarningsinexistingCOMadd-insthataccesstheBodyorHTMLBodypropertiesofitems,thiswillhelppreventmaliciouscodefromrunningunknowntotheuser.
Youcanavoidthedisplayofsecuritywarningsbyderivingallobjects,properties,andmethodsfromtheApplicationobjectpassedtotheOnConnectionprocedureoftheadd-in.OfficeOutlook2003trustsonlythe
ApplicationobjectpassedtotheOnConnectionprocedureoftheadd-in.IfyoucreateanewApplicationobject--forexample,byusingtheCreateObjectmethod--thatobjectandanyofitssubordinateobjects,properties,andmethodswillnotbetrustedandtheblockedpropertiesandmethodswillraisesecuritywarnings.
NewObjectModelBlocksinOfficeOutlook2003
ThefollowingaretheadditionalpropertiesthathavebeenblockedinOfficeOutlook2003:
TheIMAddresspropertyofaContactItemobject.TheHTMLBodypropertyofaMailItemobject.TheBodypropertyofthefollowingobjects:ContactItem,MailItem,PostItem,AppointmentItem,TaskItem,TaskRequestItem,TaskRequestAcceptItem,TaskRequestDeclineItem,TaskRequestUpdateItem,DistListItem,JournalItem,MeetingItem,ReportItem,RemoteItem,NoteItem,orDocumentItem.
Also,ifyouuseathird-partyadd-ins,customsolutions,orotherprogramsthatintegratewithOfficeOutlook2003,youmayreceiveoneormoreofthefollowingwarnings:
"Aprogramistryingtoautomaticallysende-mailonyourbehalf.Doyouwanttoallowthis?Ifyouunexpectedlyreceivethismessage,itmaybecausedbyavirus,andyoushouldchooseNo.""Aprogramistryingtoaccesse-mailaddressesyouhavestoredinOutlook.Doyouwanttoallowthis?Ifyouunexpectedlyreceivethismessage,itmaybecausedbyavirus,andyoushouldchooseNo."
ThesewarningmessagesarecommonlyassociatedwithsoftwarethatisdesignedtosynchronizeOutlookdatawithhandheldcomputers,butmayoccurwithanytypeofadd-inorcustomsolution.
AnswerWizardFilesCollectionObjectAnswerWizard AnswerWizardFiles
Someofthecontentinthistopicmaynotbeapplicabletosomelanguages.
AcollectionofreferencestoAnswerWizardfiles.TheAnswerWizardFilescollectioncontainsalloftheAnswerWizardfiles(withthefilenameextension.AW)availabletotheactiveMicrosoftOfficeapplication.
UsingtheAnswerWizardFilesCollection
UsetheFilespropertytogetthecollectionofAnswerWizardfilereferences.TheFilespropertyreturnsacollectionofstringsthatreferto.AWfiles.ThefollowingexamplereturnstheAnswerWizardFilescollectionanddisplaysthefilecountinamessagebox.
DimcustomAnswerWizardFilesAsAnswerWizardFiles
SetcustomAnswerWizardFiles=Application.AnswerWizard.Files
MsgBoxcustomAnswerWizardFiles.Count
UsetheAddmethodtomakeadditionalfilesavailabletothecurrentAnswerWizard.ThefollowingexampleaddsthefileCustom_1.awtothelistofAnswerWizardfilesintheactiveOfficeapplication.
DimcustomAnswerWizardAsAnswerWizard
SetcustomAnswerWizard=Application.AnswerWizard
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
UsetheItempropertytogetthenameofanexistingAnswerWizardfilereference.ThefollowingexampledisplaysamessageboxcontainingthenameofthefilereferredtobyItem(1).
MsgBoxcustomAnswerWizard.Files.Item(1)
BalloonCheckBoxesCollectionObjectBalloonCheckboxes
AcollectionofBalloonCheckBoxobjectsthatrepresentallthecheckboxesintheOfficeAssistantballoon.
UsingtheBalloonCheckBoxesCollection
UsetheCheckBoxespropertytoreturntheBalloonCheckBoxescollection.
UseCheckBoxes(index),whereindexisanumberfrom1through5,toreturnasingleBalloonCheckBoxobject.Youcanspecifyuptofivecheckboxes(andfivelabels)perballoon;eachcheckboxappearswhenavalueisassignedtoitsTextproperty.Ifyouspecifymorethanfivecheckboxes,arun-timeerroroccurs.
Thefollowingexamplecreatesaballoonwithaheading,text,andthreeregionchoices.WhentheuserselectsoneormorecheckboxesandthenclicksOK,thespecifiedprocedureorproceduresarecalled.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectyourregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
.Show
If.CheckBoxes(1).CheckedThen
runregion1
EndIf
If.CheckBoxes(2).CheckedThen
runregion2
EndIf
If.CheckBoxes(3).CheckedThen
runregion3
EndIf
EndWith
YoucannotaddcheckboxestoorremovecheckboxesfromtheBalloonCheckBoxescollectionaftertheballoonhasbeendisplayed.
Remarks
Ballooncheckboxesdisplaytheuser'schoicesuntiltheuserdismissestheballoon.YoucanuseballoonlabelsinconjunctionwiththeSelectmethodtoreturnanumbercorrespondingtotheuser'schoiceofcheckboxesassoonastheuserclicksthebuttonbesidethelabel.TopassvaluestotheSelectmethodbasedontheuser'schoice,youmusthavetheballoontypesettomsoBalloonTypeButtons.
BalloonLabelsCollectionObjectBalloonLabels BalloonLabel
AcollectionofBalloonLabelobjectsthatrepresentallthelabelsintheOfficeAssistantballoon.
UsingtheBalloonLabelsCollection
UsetheLabelspropertytoreturntheBalloonLabelscollection.
UseLabels(index),whereindexisanumberfrom1through5,toreturnaBalloonLabelobject.Youcanspecifyuptofivelabels(andfivecheckboxes)perballoon;eachlabelappearswhenavalueisassisgnedtoitsTextproperty.Ifyouspecifymorethanfivelabels,arun-timeerroroccurs.
Thefollowingexamplecreatesaballooncontainingthreechoices.ThevariablereturnValueissettothereturnvalueoftheShowmethod,whichwillbe1,2,or3,correspondingtothelabeltheuserclicks.TheexamplereturnsthevalueofthevariablereturnValue,whichyoucaneitherpasstoanotherprocedureoruseinaSelectCasestatement.
Setb=Assistant.NewBalloon
Withb
.Heading="Thisismyheading"
.Text="Selectoneofthesethings:"
.Labels(1).Text="ChoiceOne"
.Labels(2).Text="ChoiceTwo"
.Labels(3).Text="ChoiceThree"
returnValue=.Show
EndWith
Remarks
Ballooncheckboxesdisplaytheuser'schoicesuntiltheuserdismissestheballoon.Youcanuseballoonlabelstoreturnanumbercorrespondingtotheuser'schoiceintheSelectmethodassoonastheuserclicksthebuttonbesidethelabel.TopassvaluestotheSelectmethodbasedontheuser'schoice,youmusthavetheballoontypesettomsoBalloonTypeButtons.
COMAddInsCollectionObjectCOMAddIns COMAddIn
AcollectionofCOMAddInobjectsthatprovideinformationaboutaCOMadd-inregisteredintheWindowsregistry.
UsingtheCOMAddInsCollection
UsetheCOMAddInspropertyoftheApplicationobjecttoreturntheCOMAddInscollectionforaMicrosoftOfficehostapplication.ThiscollectioncontainsalloftheCOMadd-insthatareavailabletoagivenOfficehostapplication,andtheCountpropertyoftheCOMAddinscollectionreturnsthenumberofavailableCOMadd-ins,asinthefollowingexample.
MsgBoxApplication.COMAddIns.Count
UsetheUpdatemethodoftheCOMAddinscollectiontorefreshthelistofCOMadd-insfromtheWindowsregistry,asinthefollowingexample.
Application.COMAddIns.Update
UseCOMAddIns.Item(index),whereindexiseitheranordinalvaluethatreturnstheCOMadd-inatthatpositionintheCOMAddInscollection,oraStringvaluethatrepresentstheProgIDofthespecifiedCOMadd-in.ThefollowingexampledisplaysaCOMadd-in’sdescriptiontextandProgID("msodraa9.ShapeSelect")inamessagebox.
MsgBoxApplication.COMAddIns.Item("msodraa9.ShapeSelect").Description
ShowAll
CommandBarControlsCollectionObjectMultipleobjects CommandBarControls
Multipleobjects
AcollectionofCommandBarControlobjectsthatrepresentthecommandbarcontrolsonacommandbar.
UsingtheCommandBarControlsCollection
UsetheControlspropertytoreturntheCommandBarControlscollection.Thefollowingexamplechangesthecaptionofeverycontrolonthetoolbarnamed"Standard"tothecurrentvalueoftheIdpropertyforthatcontrol.
ForEachctlInCommandBars("Standard").Controls
ctl.Caption=CStr(ctl.Id)
Nextctl
UsetheAddmethodtoaddanewcommandbarcontroltotheCommandBarControlscollection.Thisexampleaddsanew,blankbuttontothecommandbarnamed"Custom."
SetmyBlankBtn=CommandBars("Custom").Controls.Add
UseControls(index),whereindexisthecaptionorindexnumberofacontrol,toreturnaCommandBarControl,CommandBarButton,CommandBarComboBox,orCommandBarPopupobject.Thefollowingexamplecopiesthefirstcontrolfromthecommandbarnamed"Standard"tothecommandbarnamed"Custom."
SetmyCustomBar=CommandBars("Custom")
SetmyControl=CommandBars("Standard").Controls(1)
myControl.CopyBar:=myCustomBar,Before:=1
ShowAll
CommandBarsCollectionObjectCommandBars Multipleobjects
AcollectionofCommandBarobjectsthatrepresentthecommandbarsinthecontainerapplication.
UsingtheCommandBarsCollection
UsetheCommandBarspropertytoreturntheCommandBarscollection.ThefollowingexampledisplaysintheImmediatewindowboththenameandlocalnameofeachmenubarandtoolbar,anditdisplaysavaluethatindicateswhetherthemenubarortoolbarisvisible.
ForEachcbarinCommandBars
Debug.Printcbar.Name,cbar.NameLocal,cbar.Visible
Next
UsetheAddmethodtoaddanewcommandbartothecollection.Thefollowingexamplecreatesacustomtoolbarnamed"Custom1"anddisplaysitasafloatingtoolbar.
Setcbar1=CommandBars.Add(Name:="Custom1",Position:=msoBarFloating)
cbar1.Visible=True
UseCommandBars(index),whereindexisthenameorindexnumberofacommandbar,toreturnasingleCommandBarobject.Thefollowingexampledocksthetoolbarnamed"Custom1"atthebottomoftheapplicationwindow.
CommandBars("Custom1").Position=msoBarBottom
NoteYoucanusethenameorindexnumbertospecifyamenubarortoolbarinthelistofavailablemenubarsandtoolbarsinthecontainerapplication.However,youmustusethenametospecifyamenu,shortcutmenu,orsubmenu(allofwhicharerepresentedbyCommandBarobjects).
Iftwoormorecustommenusorsubmenushavethesamename,CommandBars(index)returnsthefirstone.Toensurethatyoureturnthecorrectmenuorsubmenu,locatethepop-upcontrolthatdisplaysthatmenu.ThenapplytheCommandBarpropertytothepop-upcontroltoreturnthecommandbarthatrepresentsthatmenu.
DocumentLibraryVersionsCollectionDocumentLibraryVersions DocumentLibraryVersion
TheDocumentLibraryVersionspropertyoftheMicrosoftOfficeWord2003Document,theMicrosoftOfficeExcel2003Workbook,andtheMicrosoftOfficePowerPoint2003PresentationobjectsreturnsaDocumentLibraryVersionsobject.TheDocumentLibraryVersionsobjectrepresentsacollectionofDocumentLibraryVersionobjects.
UsingtheDocumentLibraryVersionsCollection
UsetheDocumentLibraryVersionsobjectwithdocumentsstoredinaWindowsSharePointServicesdocumentlibraryontheservertodeterminewhetherversioningisenabledfortheactivedocumentand,ifversioningisenabled,tomanagethedocument'scollectionofDocumentLibraryVersionobjects.
EachDocumentLibraryVersionobjectrepresentsonesavedversionoftheactivedocument.Whenversioningisenabled,anewversioniscreatedontheserverwhentheactionslistedbelowoccur;additionalversionsarenotcreatedeachtimetheusersaveschangestotheopendocument.
CheckInSave-Anewversioniscreatedontheserverwhentheuserfirstsavesthedocumentafteropeningit.Additionalchangessavedwhilethedocumentisopenapplytothesameversion.RestoreUpload
TheDocumentLibraryVersionsobjectmodelisavailablewhetherversioningisenabledordisabledontheactivedocument.TheDocumentLibraryVersionspropertyoftheDocument,WorkbookandPresentationobjectsdoesnotreturnNothingwhentheactivedocumentisnotstoredinadocumentlibraryorversioningisnotenabled.UsetheIsVersioningEnabledpropertytodeterminewhetherthedocumentlibraryisconfiguredtosaveabackupcopy,orversion,eachtimethedocumentiseditedonthewebsite.
Example
Thefollowingexamplecheckstoseewhetherversioningisenabledfortheactivedocumentand,ifso,displaysinformationabouteachsavedversion.
DimdlvVersionsAsOffice.DocumentLibraryVersions
DimdlvVersionAsOffice.DocumentLibraryVersion
DimstrVersionInfoAsString
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
strVersionInfo="Thisdocumenthas"&_
dlvVersions.Count&"versions:"&vbCrLf
ForEachdlvVersionIndlvVersions
strVersionInfo=strVersionInfo&_
"-Version#:"&dlvVersion.Index&vbCrLf&_
"-Modifiedby:"&dlvVersion.ModifiedBy&vbCrLf&_
"-Modifiedon:"&dlvVersion.Modified&vbCrLf&_
"-Comments:"&dlvVersion.Comments&vbCrLf
Next
Else
strVersionInfo="Versioningnotenabledforthisdocument."
EndIf
MsgBoxstrVersionInfo,vbInformation+vbOKOnly,"VersionInformation"
SetdlvVersion=Nothing
SetdlvVersions=Nothing
DocumentPropertiesCollectionObjectAcollectionofDocumentPropertyobjects.EachDocumentPropertyobjectrepresentsabuilt-inorcustompropertyofacontainerdocument.
UsingtheDocumentPropertiesCollection
UsetheAddmethodtocreateanewcustompropertyandaddittotheDocumentPropertiescollection.YoucannotusetheAddmethodtocreateabuilt-indocumentproperty.
UseBuiltinDocumentProperties(index),whereindexistheindexnumberofthebuilt-indocumentproperty,toreturnasingleDocumentPropertyobjectthatrepresentsaspecificbuilt-indocumentproperty.UseCustomDocumentProperties(index),whereindexisthenumberofthecustomdocumentproperty,toreturnaDocumentPropertyobjectthatrepresentsaspecificcustomdocumentproperty.
FileDialogFiltersCollectionFileDialog FileDialogFilters
FileDialogFilter
AcollectionofFileDialogFilterobjectsthatrepresentthetypesoffilesthatcanbeselectedinafiledialogboxthatisdisplayedusingtheFileDialogobject.
UsingtheFileDialogFilterscollection
UsetheFilterspropertyoftheFileDialogobjecttoreturnaFileDialogFilterscollection.ThefollowingcodereturnstheFileDialogFilterscollectionfortheFileOpendialogbox.
Application.FileDialog(msoFileDialogOpen).Filters
UsetheAddmethodtoaddFileDialogFilterobjectstotheFileDialogFilterscollection.ThefollowingexampleusestheClearmethodtoclearthecollectionandthenaddsfilterstothecollection.TheClearmethodcompletelyemptiesthecollection;however,ifyoudon'taddanyfilterstothecollectionafteryouclearit,the"Allfiles(*.*)"filterisaddedautomatically.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'ChangethecontentsoftheFilesofTypelist.
'EmptythelistbyclearingtheFileDialogFilterscollection.
.Filters.Clear
'Addafilterthatincludesallfiles.
.Filters.Add"Allfiles","*.*"
'AddafilterthatincludesGIFandJPEGimagesandmakeitthefirstiteminthelist.
.Filters.Add"Images","*.gif;*.jpg;*.jpeg",1
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Theuserpressedtheactionbutton.
If.Show=-1Then
'StepthrougheachStringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Pathname:"&vrtSelectedItem
NextvrtSelectedItem
'TheuserpressedCancel.
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
WhenchangingtheFileDialogFilterscollection,rememberthateachapplicationcanonlyinstantiateasingleFileDialogobject.ThismeansthattheFileDialogFilterscollectionwillresettoitsdefaultfilterswheneveryoucalltheFileDialogmethodwithanewdialogboxtype.
ThefollowingexampleiteratesthroughthedefaultfiltersoftheSaveAsdialogboxanddisplaysthedescriptionofeachfilterthatincludesaMicrosoftExcelfile.
SubMain()
'DeclareavariableasaFileDialogFilterscollection.
DimfdfsAsFileDialogFilters
'DeclareavariableasaFileDialogFilterobject.
DimfdfAsFileDialogFilter
'SettheFileDialogFilterscollectionvariableto
'theFileDialogFilterscollectionoftheSaveAsdialogbox.
Setfdfs=Application.FileDialog(msoFileDialogSaveAs).Filters
'Iteratethroughthedescriptionandextensionsofeach
'defaultfilterintheSaveAsdialogbox.
ForEachfdfInfdfs
'Displaythedescriptionoffiltersthatinclude
'MicrosoftExcelfiles
IfInStr(1,fdf.Extensions,"xls",vbTextCompare)>0Then
MsgBox"Descriptionoffilter:"&fdf.Description
EndIf
Nextfdf
EndSub
NoteArun-timeerrorwilloccuriftheFilterspropertyisusedinconjunctionwiththeClear,Add,orDeletemethodswhenappliedtoaSaveAsFileDiaogobject.Forexample,Application.FileDialog(msoFileDialogSaveAs).Filters.Clearwillresultinarun-timeerror.
FileDialogSelectedItemsCollectionFileDialog FileDialogSelectedItems
AcollectionofStringvaluesthatcorrespondtothepathsofthefilesorfoldersthatauserhasselectedfromafiledialogboxdisplayedthroughtheFileDialogobject.
UsingtheFileDialogSelectedItemscollection
UsetheSelectedItemspropertywiththeFileDialogobjecttoreturnaFileDialogSelectedItemscollection.ThefollowingexampledisplaysaFilePickerdialogboxanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Allowtheselectionofmultiplefile.
.AllowMultiSelect=True
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Theuserpressedtheactionbutton.
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'TheuserpressedCancel.
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
FileTypesCollectionFileSearch FileTypes
AcollectionofvaluesofthetypemsoFileTypethatdeterminewhichtypesoffilesarereturnedbytheExecutemethodoftheFileSearchobject.
UsingtheFileTypescollection
UsetheFileTypespropertywiththeFileSearchobjecttoreturnaFileTypescollection;forexample:
Setft=Application.FileSearch.FileTypes
NoteTheFileTypepropertyoftheFileSearchobjectclearstheFileTypescollectionandsetsthefirstiteminthecollectiontothefiletypedefinedbytheFileTypeproperty.
ThereisonlyoneFileTypescollectionforallsearchessoit'simportanttocleartheFileTypescollectionbeforeexecutingasearchunlessyouwishtosearchforfiletypesfromprevioussearches.TheeasiestwaytoclearthecollectionistosettheFileTypepropertytothefirstfiletypeforwhichyouwanttosearch.YoucanalsoremoveindividualtypesusingtheRemovemethod.Todeterminethefiletypeofeachiteminthecollection,usetheItemmethodtoreturnthemsoFileTypevalue.
ThefollowingexamplesearchesforallHTMLandMicrosoftExcelfilesontheC:\drive.
SubSearchForFiles()
'Declareavariabletoactasagenericcounter
DimlngCountAsLong
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject
WithApplication.FileSearch
'Clearalltheparametersoftheprevioussearches.
'Thismethoddoesn'tcleartheLookInpropertyor
'theSearchFolderscollection.
.NewSearch
'SettingtheFileTypepropertyclearsthe
'FileTypescollectionandsetsthefirst
'iteminthecollectiontothefiletype
'definedbytheFileTypeproperty.
.FileType=msoFileTypeWebPages
'AddaseconditemtotheFileTypescollection
.FileTypes.AddmsoFileTypeExcelWorkbooks
'DisplaythenumberofFileTypesinthecollection.
MsgBox"Youareabouttosearchfor"&.FileTypes.Count&_
"filetypes."
'SetupthesearchtolookinallsubfoldersontheC:\drive.
.LookIn="C:\"
.SearchSubFolders=True
'Executethesearchandtesttoseeifanyfiles
'werefound.
If.Execute<>0Then
'Displaythenumberoffilesfound.
MsgBox"Filesfound:"&.FoundFiles.Count
'Loopthroughthelistoffoundfilesand
'displaythepathofeachoneinamessagebox.
ForlngCount=1To.FoundFiles.Count
IfMsgBox(.FoundFiles.Item(lngCount),vbOKCancel,_
"Foundfiles")=vbCancelThen
'Breakoutoftheloop
lngCount=.FoundFiles.Count
EndIf
NextlngCount
Else
MsgBox"Nofilesfound."
EndIf
EndWith
EndSub
ThefollowingexampleloopsthroughtheFileTypescollectionandremovesanyfiletypesthataren'tMicrosoftWordorMicrosoftExcelfiles(ingeneral,it'ssimplertocleartheFileTypescollectionandstartfromscratch).
SubRemoveFileTypeFromCollection()
'Defineanintegertouseasacounter
'wheniteratingthroughtheFileTypescollection.
DimintFileIndexAsInteger
'UseaWith...EndWithblocktoreferencetheFileSearchobject.
WithApplication.FileSearch
'LoopthroughalloftheitemsintheFileTypescollection.
intFileIndex=1
DoWhileintFileIndex<=.FileTypes.Count
SelectCase.FileTypes.Item(intFileIndex)
CasemsoFileTypeWordDocuments,msoFileTypeExcelWorkbooks
CaseElse
'Ifthefiletypeisn'taMicrosoftWordor
'MicrosoftExcelfile,removeit.
.FileTypes.RemoveintFileIndex
'Decrementthecountersothatnofiletypesaremissed.
intFileIndex=intFileIndex-1
EndSelect
'Incrementthecountertotestthenextfiletype.
intFileIndex=intFileIndex+1
Loop
EndWith
EndSub
FoundFilesObjectFileSearch FoundFiles
Representsthelistoffilesreturnedfromafilesearch.
UsingtheFoundFilesObject
UsetheFoundFilespropertytoreturntheFoundFilesobject.Thisexamplestepsthroughthelistoffilesthatarefoundanddisplaysthepathandfilenameofeachfile.UseFoundFiles(index),whereindexistheindexnumber,toreturnthepathandfilenameofaspecificfilefoundduringthesearch.
WithApplication.FileSearch
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
NextI
EndWith
UsetheExecutemethodtobeginthefilesearchandupdatetheFoundFilesobject.ThefollowingexamplesearchestheMyDocumentsfolderforallfileswhosenamesbeginwith"Cmd"anddisplaysthenameandlocationofeachfilethat'sfound.Theexamplealsosortsthereturnedfilesinascendingalphabeticorderbyfilename.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.FileName="cmd*"
If.Execute(SortBy:=msoSortbyFileName,_
SortOrder:=msoSortOrderAscending)>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
HTMLProjectItemsCollectionHTMLProject HTMLProjectItems
HTMLProjectItem
AcollectionofHTMLProjectItemobjectsthatrepresenttheHTMLprojectitemscontainedintheHTMLProjectobject.
UsingtheHTMLProjectItemsCollection
UsetheHTMLProjectItemspropertyoftheHTMLProjectobjecttoreturntheHTMLProjectItemscollection.UsetheCountpropertyoftheHTMLProjectItemscollectiontoreturnthenumberofprojectitemsintheHTMLprojectforthespecifieddocument.UsetheItemmethodoftheHTMLProjectItemscollectiontoreturnanindividualprojectitem.ThefollowingexamplereturnsthenameofthefirstprojectitemintheHTMLProjectItemscollectionfortheactivedocument.
MsgBox"Thefirstitemis"&_
ActiveDocument.HTMLProject.HTMLProjectItems(1).Name
ODSOColumnsObjectODSOColumns ODSOColumn
AcollectionofODSOColumnobjectsthatrepresentthedatafieldsinamailmergedatasource.
UsingtheODSOColumnsobject
UsetheColumnspropertytoreturntheODSOColumnscollection.Thefollowingexampledisplaysthefieldnamesinthedatasourceattachedtotheactivepublication.
SubShowFieldNames()
DimappOfficeAsOfficeDataSourceObject
DimintCountAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Columns
ForintCount=1To.Count
MsgBox"ColumnName:"&.Item(intCount).Name
Next
EndWith
EndSub
UseColumns(index),whereindexisthedatafieldnameortheindexnumber,toreturnasingleODSOColumnobject.Theindexnumberrepresentsthepositionofthedatafieldinthemailmergedatasource.ThisexampleretrievesthenameofthefirstfieldandvalueofthefirstrecordoftheFirstNamefieldinthedatasourceattachedtotheactivepublication.
SubGetDataFromSource()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Columns
MsgBox"FieldName:"&.Columns(1).Name&_
"Value:"&.Columns("FirstName").Value
EndWith
EndSub
ODSOFiltersObjectODSOFilters ODSOFilter
Representsallthefilterstoapplytothedatasourceattachedtothemailmergepublication.TheODSOFiltersobjectiscomprisedofODSOFilterobjects.
UsingtheODSOFiltersobject
UsetheAddmethodoftheODSOFiltersobjecttoaddanewfiltercriteriontothequery.Thisexampleaddsanewlinetothequerystringandthenappliesthecombinedfiltertothedatasource.
SubSetQueryCriterion()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
.AddColumn:="Region",_
Comparison:=msoFilterComparisonIsBlank,_
Conjunction:=msoFilterConjunctionAnd
.ApplyFilter
EndWith
EndSub
UsetheItemmethodtoaccessanindividualfiltercriterion.Thisexampleloopsthroughallthefiltercriterionandifitfindsonewithavalueof"Region",changesittoremovefromthemailmergeallrecordsthatarenotequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
PropertyTestsCollectionObjectFileSearch PropertyTests
PropertyTest
AcollectionofPropertyTestobjectsthatrepresentallthesearchcriteriaofafilesearch.SearchcriteriaarelistedintheAdvancedFinddialogbox(Filemenu,Opencommand,AdvancedFindbutton).
UsingthePropertyTestsCollection
UsethePropertyTestspropertytoreturnthePropertyTestscollection.Thefollowingexampledisplaysthenumberofadvanced-findsearchcriteriathatwillbeusedforonefilesearch.
Application.FileSearch.PropertyTests.Count
UsetheAddmethodtoaddanewPropertyTestobjecttothePropertyTestscollection.Thefollowingexampleaddstwopropertyteststothesearchcriteria.Thefirstcriterionspecifiesthatthefilesthatarefoundcanbeofanyfiletype,andthesecondcriterionspecifiesthatthesefilesmusthavebeenmodifiedbetweenJanuary1,1996,andJune30,1996.Theexampledisplaysthenumberoffilesfoundanddisplaysthenameofeachfileinamessagebox.
Setfs=Application.FileSearch
fs.NewSearch
Withfs.PropertyTests
.AddName:="FilesofType",_
Condition:=msoConditionFileTypeAllFiles,_
Connector:=msoConnectorOr
.AddName:="LastModified",_
Condition:=msoConditionAnytimeBetween,_
Value:="1/1/96",SecondValue:="6/1/96",_
Connector:=msoConnectorAnd
EndWith
Iffs.Execute()>0Then
MsgBox"Therewere"&fs.FoundFiles.Count&_
"file(s)found."
Fori=1Tofs.FoundFiles.Count
MsgBoxfs.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
UsePropertyTests(index),whereindexistheindexnumber,toreturnasinglePropertyTestobject.ThefollowingexampledisplaysallthesearchcriteriaforthefirstpropertytestinthePropertyTestscollection.
WithApplication.FileSearch.PropertyTests(1)
myString="Thisisthesearchcriteria:"_
&"Thenameis:"&.Name&".Theconditionis:"_
&.Condition
If.Value<>""Then
myString=myString&".Thevalueis:"&.Value
If.SecondValue<>""Then
myString=myString_
&".Thesecondvalueis:"_
&.SecondValue&",andtheconnectoris"_
&.Connector
EndIf
EndIf
MsgBoxmyString
EndWith
ScopeFoldersCollectionScopeFolder ScopeFolders
ScopeFolderScopeFolders
AcollectionofScopeFolderobjects.OnlyScopeFolderobjectscontainScopeFolderscollections.EachScopeFolderscollectioncontainstheScopeFolderobjectsthatcorrespondtothesubfoldersoftheparentScopeFolderobject.
UsingtheScopeFolderscollection
UsetheScopeFolderspropertyoftheScopeFolderobjecttoreturnaScopeFolderscollection.
DimsfsasScopeFolders
Setsfs=Application.FileSearch.SearchScopes.Item(1).ScopeFolder.ScopeFolders
Youcan'taddorremoveScopeFolderobjectsfromaScopeFolderscollection.
ScriptsCollectionObjectScripts Script
AcollectionofScriptobjectsthatrepresentthecollectionofHTMLscriptsinthespecifieddocument.
UsingtheScriptsCollection
TheScriptscollectioncontainsalloftheScriptobjectsinagivendocument,insourceorder(theorderinwhichScriptobjectswereaddedtothesourcefile).Sourceorderisn’taffectedbythelocation(headerorbodytext)ofthescriptinthedocument.TheScriptscollectioncanbeaccessedbyusingtheScriptspropertyoftheappropriateobject(forexample,theDocumentobjectinMicrosoftWord).
YoucanuseScriptobjectstoaccessascriptortoaddascripttoaMicrosoftWorddocument,aMicrosoftExcelworksheet,oraMicrosoftPowerPointslide.YoucanalsousetheScriptscollectiontoaccessanyHTMLpageorscriptthat’sopenedinaMicrosoftOfficeapplication.
NoteMicrosoftAccessdoesn’tusethissharedOfficecomponent.
AddingaScript
WhenyouaddaScriptobjecttotheScriptscollection,aShapeobjectoftypemsoScriptAnchorisautomaticallyaddedtothedocument.OnanExcelworksheetoraPowerPointslide,theshapeisaddedtotheShapescollection;inaWordDocument,theshapeisaddedtotheInlineShapescollection.YouaddaScripttoadocumentbyusingtheAddmethod.ThefollowingexampleaddsasimplescripttotheactiveWorddocument.
myScript=ActiveDocument.Scripts.Add(_
,msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"ScriptOne",,_
"MsgBox""ThisisScriptOne.""")
ToaccessaparticularitemintheScriptscollection,usetheItemmethod,andsupplyeithertheIDattributeofthe<SCRIPT>tagortheindexnumberthatindicatesthepositionofthescriptinthecollection.TheIDmustbeuniquewithinthedocument.InthecaseofduplicateIDattributes,thefirstscriptfoundthathasthatIDisreturned.ThefollowingexampledisplaysamessageboxindicatingthelanguageofthefirstscriptfoundthatusestheID"ScriptOne".
MsgBox(ActiveDocument.Scripts.Item("ScriptOne").Language)
UsetheCountpropertytodeterminethenumberofScriptobjectsinthespecifieddocument.Thefollowingexampledisplaysthenumberofscriptsintheactivedocument.
IfActiveDocument.Scripts.Count=0Then
MsgBox("Thereareno"&_
"scriptsinthisdocument.")
EndIf
IfActiveDocument.Scripts.Count=1Then
MsgBox("Thereis"&_
ActiveDocument.Scripts.Count&_
"scriptinthisdocument.")
EndIf
IfActiveDocument.Scripts.Count>1Then
MsgBox("Thereare"&_
ActiveDocument.Scripts.Count&_
"scriptsinthisdocument.")
EndIf
UsetheDeletemethodtoremoveascriptfromtheScriptscollection,asinthefollowingexample.
ActiveDocument.Scripts("ScriptOne").Delete
SearchFoldersCollectionFileSearch SearchFolders
ScopeFolderScopeFolders
AcollectionofScopeFolderobjectsthatdetermineswhichfoldersaresearchedwhentheExecutemethodoftheFileSearchobjectiscalled.
UsingtheSearchFolderscollection
UsetheSearchFolderspropertywiththeFileSearchobjecttoreturntheSearchFolderscollection;forexample:
Setsfs=Application.FileSearch.SearchFolders
ForeachapplicationthereisonlyasingleSearchFolderscollection.Thecontentsofthecollectionremainsafterthecodethatcallsithasfinishedexecuting.Consequently,itisimportanttoclearthecollectionunlessyouwanttoincludefoldersfromprevioussearchesinyoursearch.
YoucanusetheAddmethodoftheSearchFolderscollectiontoaddaScopeFolderobjecttotheSearchFolderscollection,however,itisusuallysimplertousetheAddToSearchFoldersmethodoftheScopeFolderthatyouwanttoadd,asthereisonlyoneSearchFolderscollectionforallsearches.
TheSearchFolderscollectioncanbeseenasacomplimenttotheLookInpropertyoftheFileSearchobject.Bothspecifythefolderstosearchandbothareusedwhenthesearchisexecuted.However,ifyouonlywanttousetheLookInproperty,youshouldmakesurethattheSearchFolderscollectionisempty.Conversely,ifyouonlywanttousetheSearchFolderscollection,settheLookInpropertytothepathofthefirstmemberoftheSearchFolderscollectionbeforeyoucalltheExecutemethod.
Thefollowingexamplesearcheseveryfoldernamed"1033"onthelocalmachineforallHTMLandMicrosoftExcelfiles.TheexamplemakesuseoftheSearchFolderscollection,SearchScopescollection,andScopeFolderscollection.
Thisexampleconsistsoftworoutines.TheSearchEveryFolderroutineistheroutinethatyoushouldrun.TheOutputPathsroutineisseparatefromthemainroutinebecauseitcallsitselfrecursivelyinordertotraversetheentiredirectorystructureofthelocalmachine.
SubSearchEveryFolder()
'Declarevariablesthatreferencea
'SearchScopeandaScopeFolderobject.
DimssAsSearchScope
DimsfAsScopeFolder
'Declareavariabletoactasagenericcounter.
DimlngCountAsLong
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'Clearalltheparametersoftheprevioussearches.
'Thismethoddoesn'tcleartheLookInpropertyor
'theSearchFolderscollection.
.NewSearch
'Specifythetypeoffileforwhichtosearch.
'UsetheFileTypepropertytospecifythefirsttype
'andthenaddadditionaltypestotheFileTypescollection.
.FileType=msoFileTypeWebPages
.FileTypes.AddmsoFileTypeExcelWorkbooks
'CleartheSearchFoldercollectionby
'loopingthrougheachScopeFolderobject
'andremovingit.
ForlngCount=1To.SearchFolders.Count
.SearchFolders.RemovelngCount
NextlngCount
'LoopthroughtheSearchScopescollectiontofind
'thescopeinwhichyouwanttosearch.Inthis
'casethescopeisthelocalmachine.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
'LoopthrougheachScopeFolderin
'theScopeFolderscollectionofthe
'SearchScopeobject.
ForEachsfInss.ScopeFolder.ScopeFolders
'Callafunctionthatloopsthroughall
'ofthesubfoldersoftherootScopeFolder.
'Thisfunctionaddsanyfoldersnamed"1033"tothe
'SearchFolderscollection.
CallOutputPaths(sf.ScopeFolders,"1033")
Nextsf
CaseElse
EndSelect
Nextss
'TesttoseeifanyScopeFolderscollectionswereaddedto
'theSearchFolderscollection.
If.SearchFolders.Count>0Then
'SettheLookInpropertytothepathof
'thefirstScopeFolderobjectintheSearchFolders
'collection.Thisisheresothatanyprevious
'settingoftheLookInpropertydoesn'taffect
'thesearch.
.LookIn=.SearchFolders.Item(1).Path
'Executethesearchandtesttoseeifanyfiles
'werefound.
If.Execute<>0Then
'Displaythenumberoffilesfound.
MsgBox"Filesfound:"&.FoundFiles.Count
'Loopthroughthelistoffoundfilesand
'displaythepathofeachoneinamessagebox.
ForlngCount=1To.FoundFiles.Count
IfMsgBox(.FoundFiles.Item(lngCount),vbOKCancel,_
"Foundfiles")=vbCancelThen
'Breakoutoftheloop
lngCount=.FoundFiles.Count
EndIf
NextlngCount
EndIf
EndIf
EndWith
EndSub
'ThissubroutineloopsthroughalloftheScopeFolderscollections
'inagivenScopeFolderscollection.Itaddsanyfolder
'thathasthesamenameasthevalueofstrFolder
'totheSearchFolderscollection.
SubOutputPaths(ByValsfsAsScopeFolders,_
ByRefstrFolderAsString)
'DeclareavariableasaScopeFolderobject
DimsfAsScopeFolder
'LoopthrougheachScopeFolderobjectinthe
'ScopeFolderscollection.
ForEachsfInsfs
'TesttoseeifthefoldernameoftheScopeFolder
'matchesthevalueofstrFolder.UseLCasetoensure
'thatcasedoesnotaffectthematch.
IfLCase(sf.Name)=LCase(strFolder)Then
'AddtheScopeFoldertotheSearchFolderscollection.
sf.AddToSearchFolders
EndIf
'IncludeaDoEventscallbecausethereisthepotentialforthis
'looptolastalongtime.TheDoEventscallallowsthisprocessto
'continuehandlingevents.
DoEvents
'TesttoseeiftheScopeFolderscollectioninthe
'currentScopeFolderisempty.Ifitisn'tempty,then
'thatmeansthatthecurrentScopeFolderobjectcontainssubfolders.
Ifsf.ScopeFolders.Count>0Then
'Thissubroutinerecursivelycallsitselfsothat
'itcanaddthesubfoldersofthecurrentScopeFolderobject
'totheSearchFolderscollection.
CallOutputPaths(sf.ScopeFolders,strFolder)
EndIf
Nextsf
EndSub
SearchScopesCollectionFileSearch SearchScopes
SearchScopeScopeFolder
AcollectionofSearchScopeobjects.
UsingtheSearchScopescollection
UsetheSearchScopespropertyoftheFileSearchobjecttoreturnaSearchScopescollection;forexample:
DimsssAsSearchScopes
Setsss=Application.FileSearch.SearchScopes
Youcan'taddorremoveSearchScopeobjectsfromtheSearchScopescollection.
SharedWorkspaceFilesCollectionSharedWorkspace SharedWorkspaceFiles
SharedWorkspaceFile
AcollectionoftheSharedWorkspaceFileobjectsinthecurrentsharedworkspace.
UsingtheSharedWorkspaceFilesCollection
UsetheFilespropertyoftheSharedWorkspaceobjecttoreturnaSharedWorkspaceFilescollection.
DimswsFilesAsOffice.SharedWorkspaceFiles
SetswsFiles=ActiveWorkbook.SharedWorkspace.Files
MsgBox"Thereare"&swsFiles.Count&_
"file(s)
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsFiles=Nothing
SharedWorkspaceFoldersCollectionSharedWorkspace SharedWorkspaceFolders
SharedWorkspaceFolder
AcollectionoftheSharedWorkspaceFolderobjectsinthecurrentsharedworkspace.
UsingtheSharedWorkspaceFoldersCollection
UsetheFolderspropertyoftheSharedWorkspaceobjecttoreturnaSharedWorkspaceFolderscollection.
DimswsFoldersAsOffice.SharedWorkspaceFolders
SetswsFolders=ActiveWorkbook.SharedWorkspace.Folders
MsgBox"Thereare"&swsFolders.Count&_
"folder(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsFolders=Nothing
SharedWorkspaceLinksCollectionSharedWorkspace SharedWorkspaceLinks
SharedWorkspaceLink
AcollectionoftheSharedWorkspaceLinkobjectsinthecurrentsharedworkspace.
UsingtheSharedWorkspaceLinksCollection
UsetheLinkspropertyoftheSharedWorkspaceobjecttoreturnaSharedWorkspaceLinkscollection.
DimswsLinksAsOffice.SharedWorkspaceLinks
SetswsLinks=ActiveWorkbook.SharedWorkspace.Links
MsgBox"Thereare"&swsLinks.Count&_
"link(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsLinks=Nothing
SharedWorkspaceMembersCollectionSharedWorkspace SharedWorkspaceMembers
SharedWorkspaceMember
AcollectionoftheSharedWorkspaceMemberobjectsinthecurrentsharedworkspace.
UsingtheSharedWorkspaceMembersCollection
UsetheMemberspropertyoftheSharedWorkspaceobjecttoreturnaSharedWorkspaceMemberscollection.
DimswsMembersAsOffice.SharedWorkspaceMembers
SetswsMembers=ActiveWorkbook.SharedWorkspace.Members
MsgBox"Thereare"&swsMembers.Count&_
"member(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsMembers=Nothing
SharedWorkspaceTasksCollectionSharedWorkspace SharedWorkspaceTasks
SharedWorkspaceTask
AcollectionoftheSharedWorkspaceTaskobjectsinthecurrentsharedworkspace.
UsingtheSharedWorkspaceTasksCollection
UsetheTaskspropertyoftheSharedWorkspaceobjecttoreturnaSharedWorkspaceTaskscollection.
DimswsTasksAsOffice.SharedWorkspaceTasks
SetswsTasks=ActiveWorkbook.SharedWorkspace.Tasks
MsgBox"Thereare"&swsTasks.Count&_
"task(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsTasks=Nothing
SignatureSetCollectionSignatureSet Signature
AcollectionofSignatureobjectsthatcorrespondtothedigitalsignaturesattachedtoadocument.
UsingtheSignatureSetcollection
UsetheSignaturespropertyoftheDocumentobjecttoreturnaSignatureSetcollection;forexample:
Setsigs=ActiveDocument.Signatures
NoteChangesthatyoumaketotheSignatureSetcollectionofadocumentwillnotpersistunlessyoucalltheCommitmethod.
YoucanaddaSignatureobjecttoaSignatureSetcollectionusingtheAddmethodandyoucanreturnanexistingmemberusingtheItemmethod.ToremoveaSignaturefromaSignatureSetcollection,usetheDeletemethodoftheSignatureobject.
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommittingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
ShowAll
WebPageFontsCollectionObjectWebPageFonts WebPageFont
AcollectionofWebPageFontobjectsthatdescribetheproportionalfont,proportionalfontsize,fixed-widthfont,andfixed-widthfontsizeusedwhendocumentsaresavedasWebpages.YoucanspecifyadifferentsetofWebpagefontpropertiesforeachavailablecharacterset.
UsingtheWebPageFontsCollection
TheWebPageFontscollectioncontainsoneWebPageFontobjectforeachcharacterset.
Thefollowingcharactersetsaresupported.msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
ThefollowingexampleusestheItempropertytosetmyFonttotheWebPageFontobjectfortheEnglish/WesternEuropean/OtherLatinScriptcharactersetinthecurrentapplication.
DimmyFontAsWebPageFont
SetmyFont=_
Application.DefaultWebOptions.Fonts.Item_
(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)
AnswerWizardObjectAnswerWizard AnswerWizardFiles
Someofthecontentinthistopicmaynotbeapplicabletosomelanguages.
RepresentstheAnswerWizardinaMicrosoftOfficeapplication.There’sonlyoneAnswerWizardperapplication,andallchangestotheAnswerWizardortheAnswerWizardFilescollectionaffecttheactiveOfficeapplicationimmediately.
UsingtheAnswerWizardObject
UsetheClearFileListmethodtoremoveallentriesfromthelistoffilesavailabletothecurrentAnswerWizard.UsingthismethodensuresthatthedefaultfilesavailabletotheOfficehostapplicationarenolongeraccessiblethroughtheAnswerWizard,suchaswhenyou’rereplacingtheAnswerWizardfileswithcustom.AWfiles.ThefollowingexampleclearsthefilelistforthedefaultAnswerWizardandthenaddstwofilestothecustomAnswerWizard.
customAnswerWizard.ClearFileList
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
customAnswerWizard.Files.Add("c:\awfiles\custom_2.aw")
UsetheResetFileListmethodtorestorethelistoffilesforthecurrentAnswerWizardtothedefaultlistoffilesfortheOfficehostapplication.YoucanalsoestablishacustomdefaultfilelistintheWindowsregistrybyaddingthenamesofthecustomfilestotheappropriateregistrykey;thefilesspecifiedinthatregistrykeywillthenberestoredwhenResetFileListiscalled.ThisexampleresetsthefilelistforthecurrentAnswerWizard.
customAnswerWizard.ResetFileList
UsetheFilespropertytogetthecollectionofAnswerWizardfilereferences.TheFilespropertyreturnsacollectionofstringsthatreferto.AWfiles.ThefollowingexamplereturnstheAnswerWizardFilescollectionanddisplaysthe
filecountinamessagebox.
DimcustomAnswerWizardFilesAsAnswerWizardFiles
SetcustomAnswerWizardFiles=Application.AnswerWizard.Files
MsgBoxcustomAnswerWizardFiles.Count
AssistantObjectAssistant Balloon
Someofthecontentinthistopicmaynotbeapplicabletosomelanguages.
RepresentstheMicrosoftOfficeAssistant.
UsingtheAssistantObject
UsetheAssistantpropertytoreturntheAssistantobject.Thereisn'tacollectionfortheAssistantobject;onlyoneAssistantobjectcanbeactiveatatime.UsetheVisiblepropertytodisplaytheAssistant,andusetheOnpropertytoenabletheAssistant.
Remarks
ThedefaultAssistantisRocky.ToselectadifferentAssistantprogrammatically,usetheFileNameproperty.
ThefollowingexampledisplaysandanimatestheAssistant.
WithAssistant
.Visible=True
.Animation=msoAnimationGreeting
EndWith
BalloonObjectAssistant Balloon
RepresentstheballoonwheretheOfficeAssistantdisplaysinformation.Aballooncancontaincontrolssuchascheckboxesandlabels.
UsingtheBalloonObject
UsetheNewBalloonpropertytoreturnaBalloonobject.Thereisn'tacollectionfortheBalloonobject;onlyoneballooncanbevisibleatatime.However,it'spossibletodefineseveralballoonsanddisplayanyoneofthemwhenneeded.Formoreinformation,see"DefiningandReusingBalloons"laterinthistopic.
UsetheShowmethodtomakethespecifiedballoonvisible.UsetheCallbackpropertytorunproceduresbasedonselectionsfrommodelessballoons(balloonsthatremainvisiblewhileauserworksintheapplication).UsetheClosemethodtoclosemodelessballoons.
Thefollowingexamplecreatesaballoonthatcontainstipsforsavingentereddata.
WithAssistant.NewBalloon
.BalloonType=msoBalloonTypeBullets
.Icon=msoIconTip
.Button=msoButtonSetOk
.Heading="TipsforSavingInformation."
.Labels(1).Text="Saveyourworkoften."
.Labels(2).Text="Installasurgeprotector."
.Labels(3).Text="Exityourapplicationproperly."
.Show
EndWith
DefiningandReusingBalloons
Youcanreuseballoonobjectsyou'vealreadycreatedbyassigningtheobjecttoavariableanddisplayingthevariablewhenyouneedit.Thisexampledefinesballoon1andballoon2separatelysothattheycanbereused.
Setballoon1=Assistant.NewBalloon
balloon1.Heading="Firstballoon"
Setballoon2=Assistant.NewBalloon
balloon2.Heading="Secondballoon"
balloon1.Show
balloon2.Show
balloon1.Heading="Firstballoon,newheading"
balloon1.Show
Alternatively,insteadofusingseparatevariables,youcanplacetheballoonobjectintoanarray.
BalloonCheckBoxObjectBalloonCheckbox
RepresentsacheckboxintheOfficeAssistantballoon.TheBalloonCheckBoxobjectisamemberoftheBalloonCheckBoxescollection.
UsingtheBalloonCheckBoxObject
UseCheckBoxes(index),whereindexisanumberfrom1through5,toreturnasingleBalloonCheckBoxobject.Therecanbeuptofivecheckboxesinoneballoon;eachcheckboxappearswhenavalueisassignedtoitsTextproperty.
Thefollowingexamplecreatesaballoonwithaheading,text,andthreeregionchoices.TheuserselectsoneormorecheckboxesandclicksOK.Theexamplecallsthespecifiedprocedureorprocedures.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectyourregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
.Show
If.CheckBoxes(1).CheckedThen
runregion1
EndIf
If.CheckBoxes(2).CheckedThen
runregion2
EndIf
If.CheckBoxes(3).CheckedThen
runregion3
EndIf
EndWith
Remarks
Ballooncheckboxesdisplaytheuser'schoicesuntiltheuserdismissestheballoon.Youcanuseballoonlabelstoreturnanumbercorrespondingtotheuser'schoiceintheSelectmethodassoonastheuserclicksthebuttonbesidethelabel.TopassvaluestotheSelectmethodbasedontheuser'schoice,youmusthavetheballoontypesettomsoBalloonTypeButtons.
BalloonLabelObjectBalloonLabels BalloonLabel
RepresentsalabelintheOfficeAssistantballoon.TheBalloonLabelobjectisamemberoftheBalloonLabelscollection.
UsingtheBalloonLabelObject
UseLabels(index),whereindexisanumberfrom1through5,toreturnaBalloonLabelobject.Therecanbeuptofivelabelsononeballoon;eachlabelappearswhenavalueisassisgnedtoitsTextproperty.
Thefollowingexamplecreatesaballoonthataskstheusertoclickthelabelcorrespondingtohisorherage.
WithAssistant.NewBalloon
.Heading="CheckYourAgeGroup."
.Labels(1).Text="Under30."
.Labels(2).Text="30to50."
.Labels(3).Text="Over50."
.Text="Whichofthefollowing"_
&.Labels.Count&"choicesapplytoyou?"
.Show
EndWith
Remarks
Ballooncheckboxesdisplaytheuser'schoicesuntilheorshedismissestheballoon.Youcanuseballoonlabelstoreturnanumbercorrespondingtotheuser'schoiceintheSelectmethodassoonastheuserclicksthebuttonbesidethelabel.TopassvaluestotheSelectmethodbasedontheuser'schoice,youmusthavetheballoontypebesettomsoBalloonTypeButtons.
COMAddInObjectCOMAddIns COMAddIn
RepresentsaCOMadd-inintheMicrosoftOfficehostapplication.TheCOMAddInobjectisamemberoftheCOMAddInscollection.
UsingtheCOMAddInObject
UseCOMAddIns.Item(index),whereindexiseitheranordinalvaluethatreturnstheCOMadd-inatthatpositionintheCOMAddInscollection,oraStringvaluethatrepresentstheProgIDofthespecifiedCOMadd-in.ThefollowingexampledisplaysaCOMadd-in’sdescriptiontextinamessagebox.
MsgBoxApplication.COMAddIns.Item("msodraa9.ShapeSelect").Description
UsetheProgIDpropertyoftheCOMAddinobjecttoreturntheprogrammaticidentifierforaCOMadd-in,andusetheGuidpropertytoreturnthegloballyuniqueidentifier(GUID)fortheadd-in.ThefollowingexampledisplaystheProgIDandGUIDforCOMadd-inoneinamessagebox.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
UsetheConnectpropertytosetorreturnthestateoftheconnectiontoaspecifiedCOMadd-in.ThefollowingexampledisplaysamessageboxthatindicateswhetherCOMadd-inoneisregisteredandcurrentlyconnected.
IfApplication.COMAddIns(1).ConnectThen
MsgBox"Theadd-inisconnected."
Else
MsgBox"Theadd-inisnotconnected."
EndIf
ShowAll
CommandBarObjectMultipleobjects CommandBar
CommandBarControls
Representsacommandbarinthecontainerapplication.TheCommandBarobjectisamemberoftheCommandBarscollection.
UsingtheCommandBarObject
UseCommandBars(index),whereindexisthenameorindexnumberofacommandbar,toreturnasingleCommandBarobject.Thefollowingexamplestepsthroughthecollectionofcommandbarstofindthecommandbarnamed"Forms."Ifitfindsthiscommandbar,theexamplemakesitvisibleandprotectsitsdockingstate.Inthisexample,thevariablecbrepresentsaCommandBarobject.
foundFlag=False
ForEachcbInCommandBars
Ifcb.Name="Forms"Then
cb.Protection=msoBarNoChangeDock
cb.Visible=True
foundFlag=True
EndIf
Nextcb
IfNotfoundFlagThen
MsgBox"ThecollectiondoesnotcontainaFormscommandbar."
EndIf
Youcanuseanameorindexnumbertospecifyamenubarortoolbarinthelistofavailablemenubarsandtoolbarsinthecontainerapplication.However,youmustuseanametospecifyamenu,shortcutmenu,orsubmenu(allofwhicharerepresentedbyCommandBarobjects).ThisexampleaddsanewmenuitemtothebottomoftheToolsmenu.Whenclicked,thenewmenuitemrunstheprocedurenamed"qtrReport."
SetnewItem=CommandBars("Tools").Controls.Add(Type:=msoControlButton)
WithnewItem
.BeginGroup=True
.Caption="MakeReport"
.FaceID=0
.OnAction="qtrReport"
EndWith
Iftwoormorecustommenusorsubmenushavethesamename,CommandBars(index)returnsthefirstone.Toensurethatyoureturnthecorrectmenuorsubmenu,locatethepop-upcontrolthatdisplaysthatmenu.ThenapplytheCommandBarpropertytothepop-upcontroltoreturnthecommandbarthatrepresentsthatmenu.
Assumingthatthethirdcontrolonthetoolbarnamed"CustomTools"isapop-upcontrol,thisexampleaddstheSavecommandtothebottomofthatmenu.
SetviewMenu=CommandBars("CustomTools").Controls(3)
viewMenu.Controls.AddID:=3'IDofSavecommandis3
ShowAll
CommandBarButtonObjectCommandBarButton CommandBar
Representsabuttoncontrolonacommandbar.
UsingtheCommandBarButtonObject
UseControls(index),whereindexistheindexnumberofthecontrol,toreturnaCommandBarButtonobject.(TheTypepropertyofthecontrolmustbemsoControlButton.)
Assumingthatthesecondcontrolonthecommandbarnamed"Custom"isabutton,thefollowingexamplechangesthestyleofthatbutton.
Setc=CommandBars("Custom").Controls(2)
Withc
If.Type=msoControlButtonThen
If.Style=msoButtonIconThen
.Style=msoButtonIconAndCaption
Else
.Style=msoButtonIcon
EndIf
EndIf
EndWith
YoucanalsousetheFindControlmethodtoreturnaCommandBarButtonobject.
ShowAll
CommandBarComboBoxObjectCommandBarComboBox CommandBar
Representsacomboboxcontrolonacommandbar.
UsingtheCommandBarComboBoxObject
UseControls(index),whereindexistheindexnumberofthecontrol,toreturnaCommandBarComboBoxobject.(TheTypepropertyofthecontrolmustbemsoControlEdit,msoControlDropdown,msoControlComboBox,msoControlButtonDropdown,msoControlSplitDropdown,msoControlOCXDropdown,msoControlGraphicCombo,ormsoControlGraphicDropdown.)
Thefollowingexampleaddstwoitemstothesecondcontrolonthecommandbarnamed"Custom,"andthenitadjuststhesizeofthecontrol.
Setcombo=CommandBars("Custom").Controls(2)
Withcombo
.AddItem"FirstItem",1
.AddItem"SecondItem",2
.DropDownLines=3
.DropDownWidth=75
.ListIndex=0
EndWith
YoucanalsousetheFindControlmethodtoreturnaCommandBarComboBoxobject.ThefollowingexamplesearchesallcommandbarsforavisibleCommandBarComboBoxobjectwhosetagis"sheetassignments."
SetmyControl=CommandBars.FindControl_
(Type:=msoControlComboBox,Tag:="sheetassignments",Visible:=True)
ShowAll
CommandBarControlObjectMultipleobjects CommandBarControl
CommandBar
Representsacommandbarcontrol.TheCommandBarControlobjectisamemberoftheCommandBarControlscollection.ThepropertiesandmethodsoftheCommandBarControlobjectareallsharedbytheCommandBarButton,CommandBarComboBox,andCommandBarPopupobjects.
NoteWhenwritingVisualBasiccodetoworkwithcustomcommandbarcontrols,youusetheCommandBarButton,CommandBarComboBox,andCommandBarPopupobjects.Whenwritingcodetoworkwithbuilt-incontrolsinthecontainerapplicationthatcannotberepresentedbyoneofthosethreeobjects,youusetheCommandBarControlobject.
UsingtheCommandBarControlObject
UseControls(index),whereindexistheindexnumberofacontrol,toreturnaCommandBarControlobject.(TheTypepropertyofthecontrolmustbemsoControlLabel,msoControlExpandingGrid,msoControlSplitExpandingGrid,msoControlGrid,ormsoControlGauge.)
NoteVariablesdeclaredasCommandBarControlcanbeassignedCommandBarButton,CommandBarComboBox,andCommandBarPopupvalues.
YoucanalsousetheFindControlmethodtoreturnaCommandBarControlobject.ThefollowingexamplesearchesforacontroloftypemsoControlGauge;ifitfindsone,itdisplaystheindexnumberofthecontrolandthenameofthecommandbarthatcontainsit.Inthisexample,thevariablelblrepresentsaCommandBarControlobject.
Setlbl=CommandBars.FindControl(Type:=msoControlGauge)
IflblIsNothingThen
MsgBox"AcontroloftypemsoControlGaugewasnotfound."
Else
MsgBox"Control"&lbl.Index&"oncommandbar"_
&lbl.Parent.Name&"istypemsoControlGauge"
EndIf
ShowAll
CommandBarPopupObjectCommandBarPopup Multipleobjects
Representsapop-upcontrolonacommandbar.
UsingtheCommandBarPopupObject
UseControls(index),whereindexisthenumberofthecontrol,toreturnaCommandBarPopupobject.(TheTypepropertyofthecontrolmustbemsoControlPopup,msoControlGraphicPopup,msoControlButtonPopup,msoControlSplitButtonPopup,ormsoControlSplitButtonMRUPopup.)
YoucanalsousetheFindControlmethodtoreturnaCommandBarPopupobject.ThefollowingexamplesearchesallcommandbarsforaCommandBarPopupobjectwhosetagis"Graphics."
SetmyControl=Application.CommandBars.FindControl_
(Type:=msoControlPopup,Tag:="Graphics")
Remarks
Everypop-upcontrolcontainsaCommandBarobject.Toreturnthecommandbarfromapop-upcontrol,applytheCommandBarpropertytotheCommandBarPopupobject.
DocumentLibraryVersionObjectDocumentLibraryVersions DocumentLibraryVersion
TheDocumentLibraryVersionobjectrepresentsasinglesavedversionofashareddocumentwhichhasversioningenabledandwhichisstoredinadocumentlibraryontheserver.EachDocumentLibraryVersionobjectisamemberoftheactivedocument'sDocumentLibraryVersionscollection.
UsingtheDocumentLibraryVersionObject
EachDocumentLibraryVersionobjectrepresentsonesavedversionoftheactivedocument.Whenversioningisenabled,anewversioniscreatedontheserverwhentheactionslistedbelowoccur;additionalversionsarenotcreatedeachtimetheusersaveschangestotheopendocument.
CheckInSave-Anewversioniscreatedontheserverwhentheuserfirstsavesthedocumentafteropeningit.Additionalchangessavedwhilethedocumentisopenapplytothesameversion.RestoreUpload
UsetheModified,ModifiedBy,andCommentspropertiestoreturninformationaboutasavedversionofashareddocument.
UsetheOpenmethodtoopenapreviousversion,ortheRestoremethodtorestoreapreviousversioninplaceofthecurrentversion.UsetheDeletemethodtodeleteaversion.
Example
Thefollowingexampledisplaysthepropertiesofeachsavedversionoftheactivedocument.
DimdlvVersionsAsOffice.DocumentLibraryVersions
DimdlvVersionAsOffice.DocumentLibraryVersion
DimstrVersionInfoAsString
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
strVersionInfo="Thisdocumenthas"&_
dlvVersions.Count&"versions:"&vbCrLf
ForEachdlvVersionIndlvVersions
strVersionInfo=strVersionInfo&_
"-Version#:"&dlvVersion.Index&vbCrLf&_
"-Modifiedby:"&dlvVersion.ModifiedBy&vbCrLf&_
"-Modifiedon:"&dlvVersion.Modified&vbCrLf&_
"-Comments:"&dlvVersion.Comments&vbCrLf
Next
Else
strVersionInfo="Versioningnotenabledforthisdocument."
EndIf
MsgBoxstrVersionInfo,vbInformation+vbOKOnly,"VersionInformation"
SetdlvVersion=Nothing
SetdlvVersions=Nothing
DocumentPropertyObjectRepresentsacustomorbuilt-indocumentpropertyofacontainerdocument.TheDocumentPropertyobjectisamemberoftheDocumentPropertiescollection.
UsingtheDocumentPropertyObject
UseBuiltinDocumentProperties(index),whereindexisthenameorindexnumberofthebuilt-indocumentproperty,toreturnasingleDocumentPropertyobjectthatrepresentsaspecificbuilt-indocumentproperty.UseCustomDocumentProperties(index),whereindexisthenameorindexnumberofthecustomdocumentproperty,toreturnaDocumentPropertyobjectthatrepresentsaspecificcustomdocumentproperty.
Thefollowinglistcontainsthenamesofalltheavailablebuilt-indocumentproperties:
Title
Subject
Author
Keywords
Comments
Template
LastAuthor
RevisionNumber
ApplicationName
LastPrintDate
CreationDate
LastSaveTime
TotalEditingTime
NumberofPages
NumberofWords
NumberofCharacters
Security
Category
Format
Manager
Company
NumberofBytes
NumberofLines
NumberofParagraphs
NumberofSlides
NumberofNotes
NumberofHiddenSlides
NumberofMultimediaClips
Containerapplicationsdon'tnecessarilydefineavalueforeverybuilt-indocumentproperty.Ifagivenapplicationdoesn'tdefineavalueforoneofthebuilt-indocumentproperties,returningtheValuepropertyforthatdocumentpropertycausesanerror.
FileDialogObjectFileDialog Multipleobjects
ProvidesfiledialogboxfunctionalitysimilartothefunctionalityofthestandardOpenandSavedialogboxesfoundinMicrosoftOfficeapplications.Withthesedialogboxes,usersofyoursolutionscaneasilyspecifythefilesandfoldersthatyoursolutionshoulduse.
UsingtheFileDialogobject
UsetheFileDialogpropertytoreturnaFileDialogobject.TheFileDialogpropertyislocatedineachindividualOfficeapplication'sApplicationobject.Thepropertytakesasingleargument,DialogType,thatdeterminesthetypeofFileDialogobjectthatthepropertyreturns.TherearefourtypesofFileDialogobject:
Opendialogbox-letsusersselectoneormorefilesthatyoucanthenopeninthehostapplicationusingtheExecutemethod.SaveAsdialogbox-letsusersselectasinglefilethatyoucanthensavethecurrentfileasusingtheExecutemethod.FilePickerdialogbox-letsusersselectoneormorefiles.ThefilepathsthattheuserselectsarecapturedintheFileDialogSelectedItemscollection.FolderPickerdialogbox-letsusersselectapath.ThepaththattheuserselectsiscapturedintheFileDialogSelectedItemscollection.
EachhostapplicationcanonlyinstantiateasingleinstanceoftheFileDialogobject.Therefore,manyofthepropertiesoftheFileDialogobjectpersistevenwhenyoucreatemultipleFileDialogobjects.Therefore,makesurethatyou'vesetallofthepropertiesappropriatelyforyourpurposebeforeyoudisplaythedialogbox.
InordertodisplayafiledialogboxusingtheFileDialogobject,youmustusetheShowmethod.Onceadialogboxisdisplayed,nocodewillexecuteuntiltheuserdismissesthedialogbox.ThefollowingexamplecreatesanddisplaysaFilePickerdialogboxandthendisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Theuserpressedtheactionbutton.
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Thepathis:"&vrtSelectedItem
NextvrtSelectedItem
'TheuserpressedCancel.
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
FileDialogFilterObjectFileDialogFilters FileDialogFilter
RepresentsafilefilterinafiledialogboxdisplayedthroughtheFileDialogobject.Eachfilefilterdetermineswhichfilesaredisplayedinthefiledialogbox.
UsingtheFileDialogFilterobject
UsetheItemmethodwiththeFileDialogFilterscollectiontoreturnaFileDialogFilterobject.UsetheAddmethodtoaddaFileDialogFilterobjecttotheFileDialogFilterscollection.YoucanreturntheextensionsthataFileDialogFilterobjectusestofilterfileswiththeExtensionspropertyandyoucanreturnthedescriptionofthefilterwiththeDescriptionproperty;however,bothofthesepropertiesareread-only.IfyouwanttosettheextensionordescriptionyoumustusetheAddmethod.
ThefollowingexampleiteratesthroughthedefaultfiltersoftheSaveAsdialogboxanddisplaysthedescriptionofeachfilterthatincludesaMicrosoftExcelfile.
SubMain()
'DeclareavariableasaFileDialogFilterscollection.
DimfdfsAsFileDialogFilters
'DeclareavariableasaFileDialogFilterobject.
DimfdfAsFileDialogFilter
'SettheFileDialogFilterscollectionvariableto
'theFileDialogFilterscollectionoftheSaveAsdialogbox.
Setfdfs=Application.FileDialog(msoFileDialogSaveAs).Filters
'Iteratethroughthedescriptionandextensionsofeach
'defaultfilterintheSaveAsdialogbox.
ForEachfdfInfdfs
'Displaythedescriptionoffiltersthatinclude
'MicrosoftExcelfiles.
IfInStr(1,fdf.Extensions,"xls",vbTextCompare)>0Then
MsgBox"Descriptionoffilter:"&fdf.Description
EndIf
Nextfdf
EndSub
FileSearchObjectFileSearch Multipleobjects
RepresentsthefunctionalityoftheOpendialogbox(Filemenu).
UsingtheFileSearchObject
UsetheFileSearchpropertytoreturntheFileSearchobject.Thefollowingexamplesearchesforfilesanddisplaysthenumberoffilesfoundandthenameofeachfile.
WithApplication.FileSearch
If.Execute()>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
UsetheNewSearchmethodtoresetthesearchcriteriatothedefaultsettings.Allpropertyvaluesareretainedaftereachsearchisrun,andbyusingtheNewSearchmethodyoucanselectivelysetpropertiesforthenextfilesearchwithoutmanuallyresettingpreviouspropertyvalues.Thefollowingexampleresetsthesearchcriteriatothedefaultsettingsbeforebeginninganewsearch.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.FileName="Run"
.MatchTextExactly=True
.FileType=msoFileTypeAllFiles
EndWith
HTMLProjectObjectHTMLProject HTMLProjectItems
Representsatop-levelprojectbranch,asintheProjectExplorerintheMicrosoftScriptEditor.
UsingtheHTMLProjectObject
UsetheOpenmethodoftheHTMLProjectobjecttoopenanHTMLprojectintheMicrosoftScriptEditor.TheprojectisopenedinsourceviewortextviewfortheactiveMicrosoftWorddocument,Excelworkbook,orPowerPointpresentation.ThefollowingexampleopensanHTMLprojectintheactiveWorddocumentinsourceview.
ActiveDocument.HTMLProject.Open(msoHTMLProjectOpenSourceView)
UsetheHTMLProjectItemspropertytoreturnthecollectionofHTMLProjectItemobjectsintheHTMLproject.UsetheRefreshDocumentmethodtorefreshtheHTMLdocumentinthehostapplication.UsetheRefreshProjectmethodtorefreshtheprojectintheMicrosoftScriptEditor.UsetheStatemethodtodeterminewhethertheHTMLprojectneedstoberefreshed.
HTMLProjectItemObjectHTMLProjectItems HTMLProjectItem
Representsanindividualprojectitemthat’saprojectitembranchintheProjectExplorerintheMicrosoftScriptEditor.TheHTMLProjectItemobjectisamemberoftheHTMLProjectItemscollection.
UsingtheHTMLProjectItemObject
UseHTMLProjectItems(index),whereindexisthenameorindexnumberofaprojectitem,toreturnasingleHTMLProjectItemobject.UsetheNamepropertytoreturnthedisplaynameoftheprojectitem.ThefollowingexamplereturnsthenameofthefirstprojectitemintheHTMLProjectItemscollectionfortheactivedocument.
MsgBox"Thefirstitemis"&_
ActiveDocument.HTMLProject.HTMLProjectItems(1).Name
UsetheOpenmethodtoopenaprojectiteminsourceviewortextview,andusetheIsOpenpropertytodeterminewhethertheprojectitemiscurrentlyopen.Thefollowingexampleopenstheprojectitemnamed“ItemOne”(intheactivedocument)inthedefaultviewandthendisplaysamessageboxstatingwhethertheitemwasopenedsuccessfully.
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne").Open
IfActiveDocument.HTMLProject._
HTMLProjectItems("ItemOne").IsOpenThen
MsgBox"Openedprojectitem"&ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne").Name
EndIf
UsetheSaveCopyAsmethodtosavetheprojectitemusinganewfilename.ThefollowingexamplesavesacopyofItemOneas“NewItem”.
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne")_
.Open(msoHTMLProjectOpenTextView)
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne")_
.SaveCopyAs("C:\NewItem.txt")
AssumingthatthetextfileC:\NewText.txtexists,thefollowingexampleusestheLoadFromFilepropertytosetthetextofItemOnetothetextcontainedinthefile.ThefollowingexampleusestheTextpropertytodisplaythenewtextinamessagebox.
MsgBoxActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").Text
ActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").LoadFromFile("C:\NewText.txt")
MsgBoxActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").Text
ShowAll
LanguageSettingsObjectLanguageSettings
ReturnsinformationaboutthelanguagesettingsinaMicrosoftOfficeapplication.
UsingtheLanguageSettingsObject
UseApplication.LanguageSettings.LanguageID(MsoAppLanguageID),whereMsoAppLanguageIDisaconstantusedtoreturnlocaleidentifier(LCID)informationtothespecifiedapplication.
MsoAppLanguageIDcanbeoneoftheseMsoAppLanguageIDconstants.msoLanguageIDExeModemsoLanguageIDHelpmsoLanguageIDInstallmsoLanguageIDUImsoLanguageIDUIPrevious
Thefollowingexamplereturnstheinstalllanguage,userinterfacelanguage,andHelplanguageLCIDsinamessagebox.
MsgBox"ThefollowinglocaleIDsareregistered"&_
"forthisapplication:InstallLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDInstall)&_
"UserInterfaceLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDUI)&_
"HelpLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDHelp)
UseApplication.LanguageSettings.LanguagePreferredForEditingtodeterminewhichLCIDsareregisteredaspreferrededitinglanguagesfortheapplication,asinthefollowingexample.
IfApplication.LanguageSettings._
LanguagePreferredForEditing(msoLanguageIDEnglishUS)Then
MsgBox"U.S.Englishisoneofthechoseneditinglanguagess."
EndIf
MsoEnvelopeObjectMsoEnvelope
ProvidesaccesstofunctionalitythatletsyousenddocumentsasemailsdirectlyfromMicrosoftOfficeapplications.
UsingtheMsoEnvelopeobject
UsetheMailEnvelopepropertyoftheDocumentobject,ChartobjectorWorksheetobject(dependingontheapplicationyouareusing)toreturnaMsoEnvelopeobject.
ThefollowingexamplesendstheactiveMicrosoftWorddocumentasane-mailtothee-mailaddressthatyoupasstothesubroutine.
SubSendMail(ByValstrRecipientAsString)
'UseaWith...EndWithblocktoreferencetheMsoEnvelopeobject.
WithApplication.ActiveDocument.MailEnvelope
'Addsomeintroductorytextbeforethebodyofthee-mail.
.Introduction="Pleasereadthisandsendmeyourcomments."
'ReturnaMicrosoftOutlookMailItemobjectthat
'youcanusetosendthedocument.
With.Item
'Allofthemailitemsettingsaresavedwiththedocument.
'WhenyouaddarecipienttotheRecipientscollection
'orchangeotherproperties,thesesettingswillpersist.
.Recipients.AddstrRecipient
.Subject="Hereisthedocument."
'Thebodyofthismessagewillbe
'thecontentoftheactivedocument.
.Send
EndWith
EndWith
EndSub
NewFileObjectNewFile
TheNewFileobjectrepresentsitemslistedontheNewItemtaskpaneavailableinseveralMicrosoftOfficeapplications.ThefollowingtableshowsthepropertytousetoaccesstheNewFileobjectineachoftheapplications.
Application PropertyMicrosoftAccess NewFileTaskPaneMicrosoftExcel NewWorkbookMicrosoftFrontPage NewPageOrWebMicrosoftPowerPoint NewPresentationMicrosoftWord NewDocument
NoteTheexamplesbelowareforWord,butyoucanchangetheNewDocumentpropertyforanyofthepropertieslistedaboveandusethecodeinthecorrespondingapplication.
UsingtheNewFileobject
UsetheAddmethodtoaddanewitemtotheNewItemtaskpane.ThefollowingexampleaddsanitemtoWord'sNewDocumenttaskpane.
SubAddNewDocToTaskPane()
Application.NewDocument.AddFileName:="C:\NewDocument.doc",_
Section:=msoNew,DisplayName:="NewDocument"
CommandBars("TaskPane").Visible=True
EndSub
UsetheRemovemethodtoremoveanitemfromtheNewItemtaskpane.ThefollowingexampleremovesthedocumentaddedintheaboveexamplefromWord'sNewDocumenttaskpane.
SubRemoveDocFromTaskPane()
Application.NewDocument.RemoveFileName:="C:\NewDocument.doc",_
Section:=msoNew,DisplayName:="NewDocument"
CommandBars("TaskPane").Visible=True
EndSub
ODSOColumnObjectODSOColumns ODSOColumn
Representsafieldinadatasource.TheODSOColumnobjectisamemberoftheODSOColumnscollection.TheODSOColumnscollectionincludesallthedatafieldsinamailmergedatasource(forexample,Name,Address,andCity).
UsingtheODSOColumnobject
UseColumns(index),whereindexisthedatafieldnameorindexnumber,toreturnasingleODSOColumnobject.Theindexnumberrepresentsthepositionofthedatafieldinthemailmergedatasource.Thisexampleretrievesthenameandvalueofthefirstfieldofthefirstrecordinthedatasourceattachedtotheactivepublication.
SubGetDataFromSource()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Columns
MsgBox"FieldName:"&.Item(1).Name&vbLf&_
"Value:"&.Item(1).Value
EndWith
EndSub
Remarks
YoucannotaddfieldstotheODSOColumnscollection.AlldatafieldsinadatasourceareautomaticallyincludedintheODSOColumnscollection.
ODSOFilterObjectODSOFilters ODSOFilter
Representsafiltertobeappliedtoanattachedmailmergedatasource.TheODSOFilterobjectisamemberoftheODSOFiltersobject.
UsingtheODSOFilterobject
Eachfilterisalineinaquerystring.UsetheColumn,Comparison,CompareTo,andConjunctionpropertiestoreturnorsetthedatasourcequerycriterion.ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
UsetheAddmethodoftheODSOFiltersobjecttoaddanewfiltercriteriontothequery.Thisexampleaddsanewlinetothequerystringandthenappliesthecombinedfiltertothedatasource.
SubSetQueryCriterion()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
.AddColumn:="Region",_
Comparison:=msoFilterComparisonIsBlank,_
Conjunction:=msoFilterConjunctionAnd
.ApplyFilter
EndWith
EndSub
OfficeDataSourceObjectObjectOfficeDataSourceObject
Representsthemailmergedatasourceinamailmergeoperation.
UsingtheOfficeDataSourceObjectobject
ToworkwiththeOfficeDataSourceObjectobject,dimensionavariableasanOfficeDataSourceObjectobject.Youcanthenworkwiththedifferentpropertiesandmethodsassociatedwiththeobject.UsetheSetSortOrdermethodtospecifyhowtosorttherecordsinadatasource.ThefollowingexamplesortsthedatasourcefirstaccordingtoZIPcodeindescendingorder,thenonlastnameandfirstnameinascendingorder.
SubSetDataSortOrder()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
appOffice.SetSortOrderSortField1:="ZipCode",_
SortAscending1:=False,SortField2:="LastName",_
SortField3:="FirstName"
EndSub
UsetheColumn,Comparison,CompareTo,andConjunctionpropertiestoreturnorsetthedatasourcequerycriterion.ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
PermissionObjectPermission UserPermission
ThePermissionpropertyoftheMicrosoftOfficeWord2003Documentobject,theMicrosoftOfficeExcel2003Workbookobject,andtheMicrosoftOfficePowerPoint2003PresentationobjectreturnsaPermissionobject.
UsingthePermissionObject
UsethePermissionobjecttorestrictpermissionstotheactivedocumentandtoreturnorsetspecificpermissionssettings.
UsetheEnabledpropertytodeterminewhetherpermissionsarerestrictedontheactivedocument.UsetheCountpropertytoreturnthenumberofuserswithpermissions,andtheRemoveAllmethodtoresetallexistingpermissions.
TheDocumentAuthor,EnableTrustedBrowser,RequestPermissionURL,andStoreLicensespropertiesprovideadditionalinformationaboutpermissionssettings.
ThePermissionobjectgivesaccesstoacollectionofUserPermissionobjects.UsetheUserPermissionobjecttoassociatespecificsetsofrightswithindividualusers.Whilesomepermissionsgrantedthroughtheuserinterface(suchasmsoPermissionPrint)applytoallusers,youcanusetheUserPermissionobjecttoassignthemonaper-userbasiswithper-userexpirationdates.
MicrosoftOfficeInformationRightsManagementsupportstheuseofadministrativepermissionpolicieswhichlistusersandgroupsandtheirdocumentpermissions.UsetheApplyPolicymethodtoapplyapermissionpolicy,andthePermissionFromPolicy,PolicyName,andPolicyDescriptionpropertiestoreturnpolicyinformation.
ThePermissionobjectmodelisavailablewhetherpermissionsarerestrictedontheactivedocumentornot.ThePermissionpropertyoftheDocument,WorkbookandPresentationobjectsdoesnotreturnNothingwhentheactivedocumentdoesnothaverestrictedpermissions.UsetheEnabledpropertytodeterminewhetheradocumenthasrestrictedpermissions.
UseofthePermissionobjectraisesanerrorwhentheWindowsRightsManagementclientisnotinstalled.
Example
Thefollowingexamplereturnsinformationaboutthepermissionssettingsontheactivedocument.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
strIRMInfo=strIRMInfo&"Viewintrustedbrowser:"&_
irmPermission.EnableTrustedBrowser&vbCrLf&_
"Documentauthor:"&irmPermission.DocumentAuthor&vbCrLf&_
"Userswithpermissions:"&irmPermission.Count&vbCrLf&_
"Cachelicenses:"&irmPermission.StoreLicenses&vbCrLf&_
"RequestpermissionURL:"&irmPermission.RequestPermissionURL&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."&vbCrLf&_
"Defaultpolicyname:"&irmPermission.PolicyName&vbCrLf&_
"Defaultpolicydescription:"&irmPermission.PolicyDescription
EndIf
Else
strIRMInfo="PermissionsareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
PropertyTestObjectFileSearch PropertyTests
PropertyTest
Representsasinglefilesearchcriterion.SearchcriteriaarelistedintheAdvancedFinddialogbox(Filemenu,Opencommand,AdvancedFindbutton).ThePropertyTestobjectisamemberofthePropertyTestscollection.
UsingthePropertyTestObject
UsePropertyTests(index),whereindexistheindexnumber,toreturnasinglePropertyTestobject.ThefollowingexampledisplaysallthesearchcriteriaforthefirstpropertytestinthePropertyTestscollection.
WithApplication.FileSearch.PropertyTests(1)
myString="Thisisthesearchcriteria:"_
&"Thenameis:"&.Name&".Theconditionis:"_
&.Condition
If.Value<>""Then
myString=myString&".Thevalueis:"&.Value
If.SecondValue<>""Then
myString=myString_
&".Thesecondvalueis:"_
&.SecondValue&",andtheconnectoris"_
&.Connector
EndIf
EndIf
MsgBoxmyString
EndWith
ScopeFolderObjectMultipleobjects ScopeFolder
ScopeFolders
Correspondstoasearchablefolder.ScopeFolderobjectsareintendedforusewiththeSearchFolderscollection.TheSearchFolderscollectiondefinesthefoldersthataresearchedwhenusingtheFileSearchobject.WhenyouwanttosearchspecificfoldersyoucanusethemethodsandpropertiesoftheSearchScopeobjectandScopeFolderscollectiontoretrieveScopeFolderobjectsandaddthemtotheSearchFolderscollection.
UsingtheScopeFolderobject
UsetheScopeFolderpropertyoftheSearchScopeobjecttoreturntherootScopeFolderobjectofasearchscope;forexample:
Setsf=Application.FileSearch.SearchScopes.Item(1).ScopeFolder
UsetheItemmethodoftheScopeFolderscollectiontoreturnasubfolderofarootScopeFolderobject;forexample:
Setsf=Application.FileSearch.SearchScopes.Item(1).ScopeFolder.ScopeFolders.Item(1)
UsetheItemmethodoftheSearchFolderscollectiontoreturnafolderthatwillbesearchedthenexttimetheExecutemethodoftheFileSearchobjectiscalled;forexample:
Setsf=Application.FileSearch.SearchFolders.Item(1)
IneachScopeFolderobjectthereisaScopeFolderscollectionthatcontainsthesubfoldersoftheparentScopeFolderobject.Youcantraversetheentirefolderstructureofasearchscope(forexample,alllocaldrives)byloopingthroughtheseScopeFolderscollectionsandreturningallofthelower-levelScopeFolderobjects.AScopeFolderobjectwithnosubfolderscontainsanemptyScopeFolderscollection.
ForanexamplethatdemonstrateshowtoloopthroughalloftheScopeFolderobjectsinasearchscope,seetheSearchFolderscollectiontopic.
YoucanusetheAddmethodoftheSearchFolderscollectiontoaddaScopeFolderobjecttotheSearchFolderscollection,however,itisusuallysimplertousetheAddToSearchFoldersmethodoftheScopeFolderthatyouwanttoadd,asthereisonlyoneSearchFolderscollectionforallsearches.
ForanexamplethatdemonstrateshowtoaddaScopeFoldertotheSearchFolderscollection,seetheSearchFolderscollectiontopic.
ThefollowingexampledisplaystherootpathofeachdirectoryinMyComputer.
Toretrievethisinformation,theexamplefirstgetstheScopeFolderobjectattherootofMyComputer.ThepathofthisScopeFolderobjectwillalwaysbe"*".AswithallScopeFolderobjects,therootobjectcontainsaScopeFolderscollection.ThisexampleloopsthroughthisScopeFolderscollectionanddisplaysthepathofeachScopeFolderobjectinit.ThepathsoftheseScopeFolderobjectswillbe"A:\","C:\",etc.
SubDisplayRootScopeFolders()
'Declarevariablesthatreferencea
'SearchScopeandaScopeFolderobject.
DimssAsSearchScope
DimsfAsScopeFolder
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection
'anddisplayalloftherootScopeFolderscollectionsin
'theMyComputerscope.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
'LoopthrougheachScopeFolderobjectin
'theScopeFolderscollectionofthe
'SearchScopeobjectanddisplaythepath.
ForEachsfInss.ScopeFolder.ScopeFolders
MsgBox"ScopeFolderobject'spath:"&sf.Path
Nextsf
CaseElse
EndSelect
Next
EndWith
EndSub
ScriptObjectScripts Script
RepresentsablockofHTMLscriptinaMicrosoftWorddocument,onaMicrosoftExcelspreadsheet,oronaMicrosoftPowerPointslide.TheScriptobjectisamemberoftheScriptscollection.
UsingtheScriptObject
UseScripts.Item(index),whereindexisthename,ID,orindexnumberofascript,toreturnasingleScriptobject.EachScriptobjectisidentifiedbytheIdproperty,whichprovidesaconvenientnameyoucanusetoaccessthescript.ThefollowingexampleaddsasinglescripttotheScriptscollectionfortheactivedocumentanddisplaystheIDofthescriptatindexvalue1.
myScript=ActiveDocument.Scripts.Add(_
,msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"ScriptOne",,_
"MsgBox(""ThisisScriptOne."")")
MsgBox(ActiveDocument.Scripts(1).Id)
YoucanspecifythescriptinglanguageusedinthescriptbychangingtheLanguageproperty.ThefollowingexamplechangesthescriptinglanguageofscriptonetoActiveServerPages(ASP).
ActiveDocument.Scripts.Item("ScriptOne")_
.Language=msoScriptLanguageASP
YoucancheckthelocationofthescriptanchorshapewithinanHTMLdocumentbyusingtheLocationproperty.ThefollowingexamplecheckstodeterminewhetherScriptOneisinthebodyoftheactiveHTMLdocument.
IfActiveDocument.Scripts("ScriptOne").Location=_
msoScriptLocationInBodyThen
MsgBox("ScriptisintheHTMLdocumentbody.")
Else
MsgBox("Scriptislocatedintheheader.")
EndIf
Youcancheckorsetattributesaddedtothe<SCRIPT>tag(withtheexceptionoftheLANGUAGEandIDattributes)byusingtheExtendedproperty.Thefollowingexamplechecksforadditionalattributesinscriptoneintheactivedocument.
IfActiveDocument.Scripts(1).Extended=""Then
MsgBox("Noadditionalattributesarepresent"&_
"inScript"&
ActiveDocument.Scripts(1).Id)
YoucancheckorsetthescripttextassociatedwithagivenscriptbyusingtheScriptTextproperty.Thefollowingexampledisplaysamessageboxcontainingthescripttextassociatedwithscriptoneintheactivedocument.
MsgBox(ActiveDocument.Scripts("ScriptOne").ScriptText)
SearchScopeObjectFileSearch SearchScopes
SearchScopeScopeFolder
CorrespondstoatypeoffoldertreethatcanbesearchedbyusingtheFileSearchobject.Forexample,thelocaldrivesonthiscomputerrepresentasinglesearchscope.NetworkfoldersandMicrosoftOutlookfoldersarealsoseparatesearchscopesthatmaybeavailable.EachSearchScopeobjectcontainsasingleScopeFolderobjectthatcorrespondstotherootfolderofthesearchscope.
UsingtheSearchScopeobject
UsetheItemmethodoftheSearchScopescollectiontoreturnaSearchScopeobject;forexample:
DimssAsSearchScope
Setss=Application.FileSearch.SearchScopes.Item(1)
Ultimately,theSearchScopeobjectisintendedtoprovideaccesstoScopeFolderobjectsthatcanbeaddedtotheSearchFolderscollection.Foranexamplethatdemonstrateshowthisisaccomplished,seetheSearchFolderscollectiontopic.
SeetheScopeFolderobjecttopictoseeasimpleexampleofhowtoreturnaScopeFolderobjectfromaSearchScopeobject.
ThefollowingexampledisplaysallofthecurrentlyavailableSearchScopeobjects.
SubDisplayAvailableScopes()
'Declareavariablethatreferencesa
'SearchScopeobject.
DimssAsSearchScope
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
MsgBox"MyComputerisanavailablesearchscope."
CasemsoSearchInMyNetworkPlaces
MsgBox"MyNetworkPlacesisanavailablesearchscope."
CasemsoSearchInOutlook
MsgBox"Outlookisanavailablesearchscope."
CasemsoSearchInCustom
MsgBox"Acustomsearchscopeisavailable."
CaseElse
MsgBox"Can'tdeterminesearchscope."
EndSelect
Nextss
EndWith
EndSub
SharedWorkspaceObjectSharedWorkspace Multipleobjects
TheSharedWorkspacepropertyofaMicrosoftOfficeWord2003Documentobject,MicrosoftOfficeExcel2003Workbookobject,andMicrosoftOfficePowerPoint2003PresentationobjectreturnsaSharedWorkspaceobjectwhichallowsthedevelopertoaddtheactivedocumenttoaMicrosoftWindowsSharePointServicesdocumentworkspaceontheserverandtomanageotherobjectsinthesharedworkspace.
UsingtheSharedWorkspaceObject
UsetheSharedWorkspaceobjecttoaddtheactiveWord,ExcelorPowerPointdocumenttoaWindowsSharePointServicesdocumentworkspaceontheserverinordertotakeadvantageoftheworkspace'scollaborationfeatures,ortodisconnectorremovethedocumentfromtheworkspace.UsetheSharedWorkspaceobject'scollectionstomanagefiles,folders,links,membersandtasksassociatedwiththeshareddocument.
TheSharedWorkspaceobjectmodelisavailablewhetherornotadocumentisstoredinaworkspace.TheSharedWorkspacepropertyoftheDocument,WorkbookandPresentationobjectsdoesnotreturnNothingwhenthedocumentisnotshared.UsetheConnectedpropertyoftheSharedWorkspaceobjecttodeterminewhethertheactivedocumentisinfactsavedinandconnectedtoasharedworkspace.
Usersrequireappropriatepermissionstousetheobjects,propertiesandmethodsintheSharedWorkspaceobjecthierarchy.
UsetheSharedWorkspaceFilescollection,accessedthroughtheFilespropertyoftheSharedWorkspaceobject,tomanagedocumentsandfilessavedinasharedworkspace.
UsetheSharedWorkspaceFolderscollection,accessedthroughtheFolderspropertyoftheSharedWorkspaceobject,tomanagesubfolderswithinthemaindocumentlibraryfolderofasharedworkspace.
UsetheSharedWorkspaceLinkscollection,accessedthroughtheLinkspropertyoftheSharedWorkspaceobject,tomanagelinkstoadditionaldocumentsandinformationofinteresttothememberswhoarecollaboratingonthedocument(s)inthesharedworkspace.
UsetheSharedWorkspaceMemberscollection,accessedthroughtheMemberspropertyoftheSharedWorkspaceobject,tomanageuserswhohaverightstoparticipateinasharedworkspaceandtocollaborateontheshareddocument(s)savedintheworkspace.
UsetheSharedWorkspaceTaskscollection,accessedthroughtheTasksproperty
oftheSharedWorkspaceobject,tomanagetasksassignedtothememberswhoarecollaboratingonthedocument(s)inthesharedworkspace.
UsetheCreateNewmethodtocreateanewdocumentworkspaceandtoaddtheactivedocumenttotheworkspace.UsetheNameandURLpropertiestoreturninformationabouttheworkspace.
TheSharedWorkspaceobjectusesalocalcacheofobjectsandpropertiesfromtheserver.Thedevelopermayneedtoupdatethiscachebeforeperformingcertainoperations,ortosavecachedpropertychangesbacktotheserver.UsetheRefreshmethodoftheSharedWorkspaceobjecttorefreshthelocalcachefromtheserver,andtheLastRefreshedpropertytodeterminewhentherefreshoperationlasttookplace.UsetheSavemethodoftheSharedWorkspaceLinkandSharedWorkspaceTaskobjectsaftermodifyingtheirpropertieslocally,inordertouploadthechangestotheserver.
UsetheDisconnectmethodtodisconnectthelocalcopyoftheactivedocumentfromthesharedworkspace,whileleavingthesharedcopyintactintheworkspace.UsetheRemoveDocumentmethodtoremovetheshareddocumentfromthesharedworkspaceentirely.
Usersrequireappropriatepermissionstousetheobjects,propertiesandmethodsintheSharedWorkspaceobjecthierarchy.UsetheRoleargumentwhenaddingmemberstotheSharedWorkspaceMemberscollectiontospecifythesetofpermissionsspecifictoeachworkspacemember.
Thefollowingexampledisplaysthepropertiesofthesharedworkspacetowhichtheactivedocumentisconnected.
DimswsWorkspaceAsOffice.SharedWorkspace
DimstrSWSInfoAsString
SetswsWorkspace=ActiveWorkbook.SharedWorkspace
strSWSInfo=swsWorkspace.Name&vbCrLf&_
"-URL:"&swsWorkspace.URL&vbCrLf&_
"Thesharedworkspacecontains"&vbCrLf&_
"-Files:"&swsWorkspace.Files.Count&vbCrLf&_
"-Folders:"&swsWorkspace.Folders.Count&vbCrLf&_
"-Links:"&swsWorkspace.Links.Count&vbCrLf&_
"-Members:"&swsWorkspace.Members.Count&vbCrLf&_
"-Tasks:"&swsWorkspace.Tasks.Count&vbCrLf
MsgBoxstrSWSInfo,vbInformation+vbOKOnly,_
"SharedWorkspaceInformation"
SetswsWorkspace=Nothing
WhenusingtheSharedWorkspaceobjectmodel,itispossibletocreateconditionswheretheSharedWorkspaceobjectcacheisnotsynchronizedwiththeuserinterfacedisplayedintheSharedWorkspacepaneoftheactivedocument.Forexample,iftheCreateNewmethodprogrammaticallyaddstheactivedocumenttoanewworkspacewhiletheSharedWorkspacepaneisopen,theSharedWorkspacepanewillcontinuetodisplaytheCreatebutton.Incircumstanceslikethese,iftheusermakesaselectionintheSharedWorkspacepanethatisnolongervalid,anerrorisraisedandarefreshoperationiscarriedouttosynchronizethedisplaywiththecurrentdocumentstateandsharedworkspacedata.
TheDocument,WorkbookandPresentationobjectsalsohaveaSyncpropertywhichreturnsaSyncobject.UsetheSyncobjectanditspropertiesandmethodstomanagethesynchronizationofthelocalandtheservercopiesoftheshareddocument.
SharedWorkspaceFileObjectSharedWorkspace SharedWorkspaceFiles
SharedWorkspaceFile
TheSharedWorkspaceFileobjectrepresentsafilesavedinashareddocumentworkspace.MemberoftheSharedWorkspaceFilescollection.
UsingtheSharedWorkspaceFileObject
UsetheSharedWorkspaceFileobjecttomanagedocumentsandfilessavedinasharedworkspace.
AlthoughtheSharedWorkspaceFileobjecthasaURLpropertythatreturnsthefile'scompletepathandfilename,itdoesnothaveaFileNameproperty.Useasimplefunctiontoextractthefilenamefromthefile'sURLasinthefollowingexample.AnadditionalsupportingfunctiondecodesescapedspacecharactersintheURL.
PrivateFunctionFilenameFromURL(FileURLAsString)AsString
DimintLastSeparatorAsInteger
FileURL=URLDecode(FileURL)
intLastSeparator=InStrRev(FileURL,"/")
FilenameFromURL=Right(FileURL,Len(FileURL)-intLastSeparator)
EndFunction
PrivateFunctionURLDecode(URLtoDecodeAsString)AsString
URLDecode=Replace(URLtoDecode,"%20","")
EndFunction
UsetheItem(Index)methodoftheSharedWorkspaceFilescollectiontoreturnaspecificSharedWorkspaceFileobject.
UsetheCreatedBy,CreatedDate,ModifiedBy,andModifiedDatepropertiestoreturninformationaboutthehistoryofeachfile.
Thefollowingexamplereturnsthenumberoffilesinthesharedworkspaceandinformationabouteachfile,usingthesupportingfunctionsshownabove.
DimswsFileAsOffice.SharedWorkspaceFile
DimstrFileInfoAsString
strFileInfo="Thesharedworkspacecontains"&_
ActiveWorkbook.SharedWorkspace.Files.Count&"File(s)."&vbCrLf
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
strFileInfo=strFileInfo&FilenameFromURL(swsFile.URL)&vbCrLf&_
"-URL:"&swsFile.URL&vbCrLf&_
"-Createdby:"&swsFile.CreatedBy&vbCrLf&_
"-Createdon:"&swsFile.CreatedDate&vbCrLf&_
"-Modifiedby:"&swsFile.ModifiedBy&vbCrLf&_
"-Modifiedon:"&swsFile.ModifiedDate&vbCrLf
Next
MsgBoxstrFileInfo,vbInformation+vbOKOnly,_
"FilesinSharedWorkspace"
SetswsFile=Nothing
SharedWorkspaceFolderObjectSharedWorkspace SharedWorkspaceFolders
SharedWorkspaceFolder
TheSharedWorkspaceFolderobjectrepresentsafolderinashareddocumentworkspace.MemberoftheSharedWorkspaceFolderscollection.
UsingtheSharedWorkspaceFolderObject
UsetheSharedWorkspaceFolderobjecttomanagesubfolderswithinthemaindocumentlibraryfolderofasharedworkspace.
TheCountpropertyoftheSharedWorkspaceFolderscollectiondoesnotincludetheworkspace'smainfolderandreturns0(zero)ifnosubfoldershavebeencreated.
TheSharedWorkspaceFolderobjectdoesnotexposetheCreatedBy,CreatedDate,ModifiedBy,andModifiedDatepropertiesavailableontheSharedWorkspaceFile,SharedWorkspaceLink,andSharedWorkspaceTaskobjects.
UsetheItem(Index)methodoftheSharedWorkspaceFolderscollectiontoreturnaspecificSharedWorkspaceFolderobject.
UsetheFolderNamepropertytoreturnthenameofthesharedworkspacefolder.ThefollowingexamplereturnsthenameofthefirstsubfolderintheSharedWorkspaceFolderscollectionintheformatparentfoldername/foldername.
DimswsFolderAsSharedWorkspaceFolder
SetswsFolder=ActiveWorkbook.SharedWorkspace.Folders(1)
MsgBoxswsFolder.FolderName,vbInformation+vbOKOnly,"FolderName"
SetswsFolder=Nothing
SharedWorkspaceLinkObjectSharedWorkspace SharedWorkspaceLinks
SharedWorkspaceLink
TheSharedWorkspaceLinkobjectrepresentsaURLlinksavedinashareddocumentworkspace.MemberoftheSharedWorkspaceLinkscollection.
UsingtheSharedWorkspaceLinkObject
UsetheSharedWorkspaceLinkobjecttomanagelinkstoadditionaldocumentsandinformationofinteresttothememberswhoarecollaboratingonthedocument(s)inthesharedworkspace.
UsetheItem(Index)methodoftheSharedWorkspaceLinkscollectiontoreturnaspecificSharedWorkspaceLinkobject.
UsetheDescriptionpropertytosetthelinkdescriptionthatwillappearontheLinkstaboftheSharedWorkspacepaneandontheworkspacewebpage.UsetheUrlpropertytosetthedestinationaddressofthelink.UsetheNotespropertytosupplyadditionalinformationaboutthelink.
UsetheSavemethodtouploadchangestotheserverafteryoumodifypropertiesoftheSharedWorkspaceLinkobject.
UsetheCreatedBy,CreatedDate,ModifiedBy,andModifiedDatepropertiestoreturninformationaboutthehistoryofeachlink.
ThefollowingexamplemodifiesthefirstlinkinthesharedworkspacetopointtotheMicrosoftDeveloperNetworkhomepage,thenuploadsthechangestotheserver.
DimswsLinkAsOffice.SharedWorkspaceLink
SetswsLink=ActiveWorkbook.SharedWorkspace.Links(1)
WithswsLink
.Description="MSDNHomePage"
.URL="http://msdn.microsoft.com/"
.Notes="Myfavoritesitefordevelopers!"
.Save
EndWith
SetswsLink=Nothing
SharedWorkspaceMemberObjectSharedWorkspace SharedWorkspaceMembers
SharedWorkspaceMember
TheSharedWorkspaceMemberobjectrepresentsauserwhohasrightsinashareddocumentworkspace.MemberoftheSharedWorkspaceMemberscollection.
UsingtheSharedWorkspaceMemberObject
UsetheSharedWorkspaceMemberobjecttomanageuserswhohaverightstoparticipateinasharedworkspaceandtocollaborateontheshareddocument(s)savedintheworkspace.
TheRolespecifiedwhentheuserisaddedasamemberoftheworkspace(forexample,"Reader"or"Contributor")determinesthatuser'srightsintheworkspaceandcannotbeaccessedormodifiedlaterthroughpropertiesoftheSharedWorkspaceMemberobject.
UsetheItem(Index)methodoftheSharedWorkspaceMemberscollectiontoreturnaspecificSharedWorkspaceMemberobject.
UsetheSharedWorkspaceMemberobject's3distinctnamepropertiestoretrieveidentifyinginformationaboutthemember.
theNamepropertyreturnsthemembersdisplaynameorfriendlyname;theEmailpropertyreturnsthemember'semailaddress;and,theDomainNamepropertyreturnsthemember'sdomainandusernameintheformatdomain\user.
Thefollowingexampledisplaysthenumberofmembersintheactivedocument'ssharedworkspace,alongwiththeirnames,domainusernames,andemailaddresses.
DimswsMemberAsOffice.SharedWorkspaceMember
DimstrMemberInfoAsString
strMemberInfo="Thesharedworkspacecontains"&_
ActiveWorkbook.SharedWorkspace.Members.Count&"member(s)."&vbCrLf
IfActiveWorkbook.SharedWorkspace.Members.Count>0Then
ForEachswsMemberInActiveWorkbook.SharedWorkspace.Members
strMemberInfo=strMemberInfo&swsMember.Name&vbCrLf&_
"-"&swsMember.DomainName&vbCrLf&_
"-"&swsMember.Email&vbCrLf
Next
EndIf
MsgBoxstrMemberInfo,vbInformation+vbOKOnly,_
"MembersinSharedWorkspace"
SetswsMember=Nothing
SharedWorkspaceTaskObjectSharedWorkspace SharedWorkspaceTasks
SharedWorkspaceTask
TheSharedWorkspaceTaskobjectrepresentsataskinashareddocumentworkspace.MemberoftheSharedWorkspaceTaskscollection.
UsingtheSharedWorkspaceTaskObject
UsetheSharedWorkspaceTaskobjecttomanagetasksassignedtothememberswhoarecollaboratingonthedocument(s)inthesharedworkspace.
UsetheItem(Index)methodoftheSharedWorkspaceTaskscollectiontoreturnaspecificSharedWorkspaceTaskobject.
UsetheTitlepropertytosetthetextofthetaskthatwillappearontheTaskstaboftheSharedWorkspacetaskpaneandonthesharedworkspaceWebpage.UsetheDescriptionpropertytosupplyadditionalinformationaboutthetask.
AssignthetasktoamemberoftheworkspaceusingtheAssignedTopropertyandthemember'sdomainusername.SpecifyaduedateforthetaskusingtheDueDateproperty.
UsetheenumerationsfortaskPriorityandStatustoindicatetherelativeimportanceofthetaskandtoupdatethetask'sstatus.
UsetheSavemethodtouploadchangestotheserverafteryoumodifypropertiesoftheSharedWorkspaceTaskobject.
UsetheCreatedBy,CreatedDate,ModifiedBy,andModifiedDatepropertiestoreturninformationaboutthehistoryofeachtask.
Thefollowingexamplereturnsthenumberoftasksinthesharedworkspaceandinformationabouteachtask.
DimswsTaskAsOffice.SharedWorkspaceTask
DimstrTaskInfoAsString
strTaskInfo="Thesharedworkspacecontains"&_
ActiveWorkbook.SharedWorkspace.Tasks.Count&"Task(s)."&vbCrLf
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
strTaskInfo=strTaskInfo&swsTask.Title&vbCrLf&_
"-Description:"&swsTask.Description&vbCrLf&_
"-Assignedto:"&swsTask.AssignedTo&vbCrLf&_
"-Duedate:"&swsTask.DueDate&vbCrLf&_
"-Priority:"&swsTask.Priority&vbCrLf&_
"-Status:"&swsTask.Status&vbCrLf
Next
MsgBoxstrTaskInfo,vbInformation+vbOKOnly,_
"TasksinSharedWorkspace"
SetswsTask=Nothing
SignatureObjectSignatureSet Signature
Correspondstoadigitalsignaturethatisattachedtoadocument.SignatureobjectsarecontainedintheSignatureSetcollectionoftheDocumentobject.
UsingtheSignatureobject
YoucanaddaSignatureobjecttoaSignatureSetcollectionusingtheAddmethodandyoucanreturnanexistingmemberusingtheItemmethod.ToremoveaSignaturefromaSignatureSetcollection,usetheDeletemethodoftheSignatureobject.
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
SmartDocumentObjectSmartDocument
TheSmartDocumentpropertyoftheMicrosoftOfficeWord2003DocumentobjectandtheMicrosoftOfficeExcel2003WorkbookobjectreturnsaSmartDocumentobject.
UsingtheSmartDocumentObject
UsetheSmartDocumentobjecttomanagetheXMLexpansionpackattachedtotheactivedocument.
UsetheSmartDocumentobject'sSolutionIDandtheSolutionUrlpropertiestoretrieveinformationabouttheXMLexpansionpackattachedtotheactivedocumentorworkbook.UsethePickSolutionmethodtoallowtheusertoselectanavailableXMLexpansionpackfromalisttoattachtotheactivedocumentorworkbook.UsetheRefreshPanemethodtorefreshthesmartdocument'sDocumentActionstaskpane.
TheSmartDocumentobjectmodelisavailablewhetherornotadocumenthasanXMLexpansionpackattached.TheSmartDocumentpropertyoftheDocumentorWorkbookobjectsdoesnotreturnNothingwhentheactivedocumenthasnoXMLexpansionpackattached.ExaminetheSolutionIDpropertytodeterminewhethertheactivedocumenthasanXMLexpansionpackattached.
ShowAll
SyncObjectSync
TheSyncpropertyoftheMicrosoftOfficeWord2003Documentobject,theMicrosoftOfficeExcel2003Workbookobject,andtheMicrosoftOfficePowerPoint2003PresentationobjectreturnsaSyncobject.
UsingtheSyncObject
UsetheSyncobjecttomanagethesynchronizationofthelocalandservercopiesofashareddocumentstoredinaWindowsSharePointServicesdocumentworkspace.TheStatuspropertyreturnsimportantinformationaboutthecurrentstateofsynchronization.UsetheGetUpdatemethodtorefreshthesyncstatus.UsetheLastSyncTime,ErrorType,andWorkspaceLastChangedBypropertiestoreturnadditionalinformation.
SeetheStatusPropertyforadditionalinformationonthedifferencesandconflictsthatcanexistbetweenthelocalandservercopiesofshareddocuments.
UsethePutUpdatemethodtosavelocalchangestotheserver.Closeandre-openthedocumenttoretrievethelatestversionfromtheserverwhennolocalchangeshavebeenmade.UsetheResolveConflictmethodtoresolvedifferencesbetweenthelocalandtheservercopies,ortheOpenVersionmethodtoopenadifferentversionalongsidethecurrentlyopenlocalversionofthedocument.
TheGetUpdate,PutUpdate,andResolveConflictmethodsoftheSyncobjectdonotreturnstatuscodesbecausetheycompletetheirtasksasynchronously.TheSyncobjectprovidesimportantstatusinformationthroughasingleevent,whichthedevelopercanaccessthroughthefollowingapplication-specificevents:
inWord,throughtheSynceventoftheDocumentobjectortheDocumentSynceventoftheApplicationobject;inExcel,throughtheSynceventoftheWorkbookobjectortheWorkbookSynceventoftheApplicationobject;inPowerPoint,throughthePresentationSynceventoftheApplicationobject.
TheSynceventdescribedabovereturnsanmsoSyncEventTypevalue.
MsoSyncEventTypecanbeoneofthefollowingmsoSyncEventTypeconstants.msoSyncEventDownloadInitiated(0)msoSyncEventDownloadSucceeded(1)msoSyncEventDownloadFailed(2)msoSyncEventUploadInitiated(3)
msoSyncEventUploadSucceeded(4)msoSyncEventUploadFailed(5)msoSyncEventDownloadNoChange(6)msoSyncEventOffline(7)
TheSyncobjectmodelisavailablewhethersharingandsynchronizationareenabledordisabledontheactivedocument.TheSyncpropertyoftheDocument,WorkbookandPresentationobjectsdoesnotreturnNothingwhentheactivedocumentisnotsharedorsynchronizationisnotenabled.UsetheStatuspropertytodeterminewhetherthedocumentissharedandwhethersynchronizationisenabled.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterusingthemethodsoftheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Inmanycircumstances,thebestwaytoresolveanerrorconditionistocalltheGetUpdatemethod.Forexample,ifacalltoPutUpdateresultsinanerrorcondition,thenacalltoGetUpdatewillresetthestatustomsoSyncStatusLocalChanges.
Example
ThefollowingexampledemonstratesvariousmethodsoftheSyncobjectbasedonthestatusoftheactivedocument.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status>msoSyncStatusNoSharedWorkspaceThen
SelectCaseobjSync.Status
CasemsoSyncStatusConflict
objSync.ResolveConflictmsoSyncConflictMerge
ActiveDocument.Save
objSync.ResolveConflictmsoSyncConflictClientWins
strStatus="Conflictresolvedbymergingchanges."
CasemsoSyncStatusError
strStatus="Lasterrortype:"&objSync.ErrorType
CasemsoSyncStatusLatest
strStatus="Documentcopiesalreadyinsync."
CasemsoSyncStatusLocalChanges
objSync.PutUpdate
strStatus="Localchangessavedtoserver."
CasemsoSyncStatusNewerAvailable
objSync.GetUpdate
strStatus="Localcopyupdatedfromserver."
CasemsoSyncStatusSuspended
objSync.Unsuspend
strStatus="Synchronizationresumed."
EndSelect
Else
strStatus="Notasharedworkspacedocument."
EndIf
MsgBoxstrStatus,vbInformation+vbOKOnly,"SyncInformation"
SetobjSync=Nothing
UserPermissionObjectPermission UserPermission
TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.Representsamemberoftheactivedocument'sPermissioncollection.
UsingtheUserPermissionObject
UsetheAddmethodofthePermissionobjecttograntspecificpermissionsontheactivedocumenttoanewuser,withanoptionalexpirationdate.UsetheRemovemethodoftheUserPermissionobjecttoremoveauserandtheuser'spermissions.
Whilesomepermissionsgrantedthroughtheuserinterface(suchasmsoPermissionPrint)applytoallusers,youcanusetheUserPermissionobjecttoassignthemonaper-userbasiswithper-userexpirationdates.
Example
Thefollowingexampledetermineswhethertheactivedocumenthasrestrictedpermissions,thenlistsusersandtheirassignedpermissionsbyreturningtheUserID,Permission,andExpirationDatepropertiesofeachUserPermissioninthedocument'sPermissioncollection.
DimirmPermissionAsOffice.Permission
DimirmUserPermAsOffice.UserPermission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
ForEachirmUserPermInirmPermission
strIRMInfo=strIRMInfo&irmUserPerm.UserId&vbCrLf&_
"-Permissions:"&irmUserPerm.Permission&vbCrLf&_
"-ExpirationDate:"&irmUserPerm.ExpirationDate&vbCrLf
Next
MsgBoxstrIRMInfo,_
vbInformation+vbOKOnly,"IRMInformation"
Else
MsgBox"Thisdocumentisnotrestricted.",_
vbInformation+vbOKOnly,"IRMInformation"
EndIf
SetirmUserPerm=Nothing
SetirmPermission=Nothing
ShowAll
WebPageFontObjectWebPageFonts WebPageFont
RepresentsthedefaultfontusedwhendocumentsaresavedasWebpagesforaparticularcharacterset.
UsingtheWebPageFontObject
UsetheWebPageFontobjecttodescribetheproportionalfont,proportionalfontsize,fixed-widthfont,andfixed-widthfontsizeforanyavailablecharacterset.
Thefollowingcharactersetsaresupported.msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
ThefollowingexamplesetstheproportionalfontandproportionalfontsizefortheWebPageFontobjectmyFont.
WithmyFont
ProportionalFont=Verdana
ProportionalFontSize=14
ShowAll
ActivateWizardMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ResumesorsuspendsOfficeAssistantHelpduringacustomwizard.
NoteYoushouldusethismethodonlywiththeStartWizardmethod.
expression.ActivateWizard(WizardID,Act,Animation)
expressionRequired.AnexpressionthatreturnsanAssistantobject.
WizardIDRequiredLong.ThenumberreturnedbytheStartWizardmethod.
ActRequiredMsoWizardActType.SpecifiesthechangetotheOfficeAssistantHelpsession.
MsoWizardActTypecanbeoneoftheseMsoWizardActTypeconstants.msoWizardActActivemsoWizardActInactivemsoWizardActResumemsoWizardActSuspend
AnimationOptionalVariant.TheanimationtheOfficeAssistantperformswhenitissuspendedorresumed.
Example
ThisexamplesuspendsthewizardsessionthatwasstartedwiththeStartWizardmethod.ThevariablelHelpForWizwassettothereturnvalueoftheStartWizardmethod.
Assistant.ActivateWizardWizardID:=lHelpForWiz,_
Act:=msoWizardActSuspend,Animation:=msoAnimationGoodbye
ShowAll
AddMethodAddmethodasitappliestotheAnswerWizardFilesobject.
Createsanewreference(aStringvalue)toanAnswerWizardfileandaddsittotheAnswerWizardFilescollection.
expression.Add(FileName)
expressionRequired.AnexpressionthatreturnsanAnswerWizardFilescollection.
FileNameRequiredString.ThefullyqualifiedpathtothespecifiedAnswerWizardfile.
AddmethodasitappliestotheCommandBarsobject.
Createsanewcommandbarandaddsittothecollectionofcommandbars.ReturnsaCommandBarobject.
expression.Add(Name,Position,MenuBar,Temporary)
expressionRequired.AnexpressionthatreturnsaCommandBarsobject.
NameOptionalVariant.Thenameofthenewcommandbar.Ifthisargumentisomitted,adefaultnameisassignedtothecommandbar(suchasCustom1).
PositionOptionalVariant.Thepositionortypeofthenewcommandbar.CanbeoneoftheMsoBarPositionconstantslistedinthefollowingtable.
Constant DescriptionmsoBarLeft,msoBarTop,msoBarRight,msoBarBottom
Indicatestheleft,top,right,andbottomcoordinatesofthenewcommandbar
msoBarFloating Indicatesthatthenewcommandbarwon'tbedockedIndicatesthatthenewcommandbarwillbe
msoBarPopup ashortcutmenu
msoBarMenuBar Macintoshonly
MenuBarOptionalVariant.Truetoreplacetheactivemenubarwiththenewcommandbar.ThedefaultvalueisFalse.
TemporaryOptionalVariant.Truetomakethenewcommandbartemporary.Temporarycommandbarsaredeletedwhenthecontainerapplicationisclosed.ThedefaultvalueisFalse.
AddmethodasitappliestotheCommandBarControlsobject.
CreatesanewCommandBarControlobjectandaddsittothecollectionofcontrolsonthespecifiedcommandbar.
expression.Add(Type,Id,Parameter,Before,Temporary)
expressionRequired.AnexpressionthatreturnsaCommandBarControlsobject.
TypeOptionalVariant.Thetypeofcontroltobeaddedtothespecifiedcommandbar.CanbeoneofthefollowingMsoControlTypeconstants:msoControlButton,msoControlEdit,msoControlDropdown,msoControlComboBox,ormsoControlPopup.
IdOptionalVariant.Anintegerthatspecifiesabuilt-incontrol.Ifthevalueofthisargumentis1,orifthisargumentisomitted,ablankcustomcontrolofthespecifiedtypewillbeaddedtothecommandbar.
ParameterOptionalVariant.Forbuilt-incontrols,thisargumentisusedbythecontainerapplicationtorunthecommand.Forcustomcontrols,youcanusethisargumenttosendinformationtoVisualBasicprocedures,oryoucanuseittostoreinformationaboutthecontrol(similartoasecondTagpropertyvalue).
BeforeOptionalVariant.Anumberthatindicatesthepositionofthenewcontrolonthecommandbar.Thenewcontrolwillbeinsertedbeforethecontrolatthisposition.Ifthisargumentisomitted,thecontrolisaddedattheendofthespecifiedcommandbar.
TemporaryOptionalVariant.Truetomakethenewcontroltemporary.Temporarycontrolsareautomaticallydeletedwhenthecontainerapplicationisclosed.ThedefaultvalueisFalse.
AddmethodasitappliestotheDocumentPropertiesobject.
Createsanewcustomdocumentproperty.YoucanonlyaddanewdocumentpropertytothecustomDocumentPropertiescollection.
expression.Add(Name,LinkToContent,Type,Value,LinkSource)
expressionRequired.ThecustomDocumentPropertiesobject.
NameRequiredString.Thenameoftheproperty.
LinkToContentRequiredBoolean.Specifieswhetherthepropertyislinkedtothecontentsofthecontainerdocument.IfthisargumentisTrue,theLinkSourceargumentisrequired;ifit'sFalse,thevalueargumentisrequired.
TypeOptionalVariant.Thedatatypeoftheproperty.CanbeoneofthefollowingMsoDocPropertiesconstants:msoPropertyTypeBoolean,msoPropertyTypeDate,msoPropertyTypeFloat,msoPropertyTypeNumber,ormsoPropertyTypeString.
ValueOptionalVariant.Thevalueoftheproperty,ifit'snotlinkedtothecontentsofthecontainerdocument.Thevalueisconvertedtomatchthedatatypespecifiedbythetypeargument,ifitcan'tbeconverted,anerroroccurs.IfLinkToContentisTrue,theValueargumentisignoredandthenewdocumentpropertyisassignedadefaultvalueuntilthelinkedpropertyvaluesareupdatedbythecontainerapplication(usuallywhenthedocumentissaved).
LinkSourceOptionalVariant.IgnoredifLinkToContentisFalse.Thesourceofthelinkedproperty.Thecontainerapplicationdetermineswhattypesofsourcelinkingyoucanuse.
Remarks
IfyouaddacustomdocumentpropertytotheDocumentPropertiescollectionthat’slinkedtoagivenvalueinaMicrosoftOfficedocument,youmustsavethedocumenttoseethechangetotheDocumentPropertyobject.
AddmethodasitappliestotheFileDialogFiltersobject.
AddsanewfilefiltertothelistoffiltersintheFilesoftypedropdownlistboxintheFiledialogbox.ReturnsaFileDialogFilterobjectthatrepresentsthenewlyaddedfilefilter.
expression.Add(Description,Extensions,Position)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
DescriptionRequiredString.Thetextrepresentingthedescriptionofthefileextensionyouwanttoaddtothelistoffilters.
ExtensionsRequiredString.Thetextrepresentingthefileextensionyouwanttoaddtothelistoffilters.Morethanoneextensionmaybespecifiedandeachmustbeseparatedbyasemi-colon(;).Forexample,theExtensionsargumentcanbeassignedtothestring:"*.txt;*.htm".NoteParenthesesdonotneedtobeaddedaroundtheextensions.Officewillautomaticallyaddparenthesesaroundtheextensionsstringwhenthedescriptionandextensionsstringsareconcatenatedintoonefilefilteritem.
PositionOptionalVariant.Anumberthatindicatesthepositionofthenewcontrolinthefilterlist.Thenewfilterwillbeinsertedbeforethefilteratthisposition.Ifthisargumentisomitted,thefilterisaddedattheendofthelist.
Remarks
Eachfilterinalistismadeupoftwoparts:thefileextension(e.g..txt)andthetextdescriptionofthefileextension(e.g.TextFiles).Together,thefilefilterwouldappearintheFilesoftypedropdownlistboxas:TextFiles(*.txt).
Notethatwhenafilterisaddedtothelist,thedefaultfiltersarenotremoved.
FiltersareonlydisplayedwhentheWindowsoptionischecked.
IfPositionisinvalid,anoutofrangeruntimeerrorisdisplayed.IftheDescriptionandExtensionsvalueareinvalid,aruntimeerror(parse)isdisplayed.
Folderpickerdialogsdonothavefilters,therefore,filtermethodsdonotapplytothefolderpicker.
AddmethodasitappliestotheFileTypesobject.
Addsanewfiletypetoafilesearch.
expression.Add(FileType)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
FileTypeRequiredMsoFileType.Specifiesthetypeoffileforwhichtosearch.
MsoFileTypecanbeoneoftheseMsoFileTypeconstants.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeCustommsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFiles
msoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItemmsoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPagesmsoFileTypeWordDocuments
AddmethodasitappliestothePropertyTestsobject.
AddsaPropertyTestobjecttothePropertyTestscollection.
expression.Add(Name,Condition,Value,SecondValue,Connector)
expressionRequired.AnexpressionthatreturnsaPropertyTestsobject.
NameRequiredString.Thenameofthepropertycriterion.ThenamecorrespondstoavalueinthePropertyboxintheFinddialogbox,whichyouopenfromtheToolsmenuintheapplication'sOpendialogbox(Filemenu).
ConditionRequiredMsoCondition.Theconditionofthesearchcriteria.
MsoConditioncanbeoneoftheseMsoConditionconstants.msoConditionAnyNumberBetweenmsoConditionAnytimemsoConditionAnytimeBetweenmsoConditionAtLeast
msoConditionAtMostmsoConditionBeginsWithmsoConditionDoesNotEqualmsoConditionEndsWithmsoConditionEqualsmsoConditionEqualsCompletedmsoConditionEqualsDeferredmsoConditionEqualsHighmsoConditionEqualsInProgressmsoConditionEqualsLowmsoConditionEqualsNormalmsoConditionEqualsNotStartedmsoConditionEqualsWaitingForSomeoneElsemsoConditionFileTypeAllFilesmsoConditionFileTypeBindersmsoConditionFileTypeCalendarItemmsoConditionFileTypeContactItemmsoConditionFileTypeDatabasesmsoConditionFileTypeDataConnectionFilesmsoConditionFileTypeDesignerFilesmsoConditionFileTypeDocumentImagingFilesmsoConditionFileTypeExcelWorkbooksmsoConditionFileTypeJournalItemmsoConditionFileTypeMailItemmsoConditionFileTypeNoteItemmsoConditionFileTypeOfficeFilesmsoConditionFileTypeOutlookItemsmsoConditionFileTypePhotoDrawFilesmsoConditionFileTypePowerPointPresentationsmsoConditionFileTypeProjectFilesmsoConditionFileTypePublisherFilesmsoConditionFileTypeTaskItemmsoConditionFileTypeTemplates
msoConditionFileTypeVisioFilesmsoConditionFileTypeWebPagesmsoConditionFileTypeWordDocumentsmsoConditionFreeTextmsoConditionIncludesmsoConditionIncludesFormsOfmsoConditionIncludesNearEachOthermsoConditionIncludesPhrasemsoConditionInTheLastmsoConditionInTheNextmsoConditionIsExactlymsoConditionIsNomsoConditionIsNotmsoConditionIsYesmsoConditionLastMonthmsoConditionLastWeekmsoConditionLessThanmsoConditionMoreThanmsoConditionNextMonthmsoConditionNextWeekmsoConditionNotEqualToCompletedmsoConditionNotEqualToDeferredmsoConditionNotEqualToHighmsoConditionNotEqualToInProgressmsoConditionNotEqualToLowmsoConditionNotEqualToNormalmsoConditionNotEqualToNotStartedmsoConditionNotEqualToWaitingForSomeoneElsemsoConditionOnmsoConditionOnOrAftermsoConditionOnOrBeforemsoConditionThisMonthmsoConditionThisWeek
msoConditionTodaymsoConditionTomorrowmsoConditionYesterday
ValueOptionalVariant.Thevalueofthesearchcriterion.
SecondValueOptionalVariant.Anuppervalueforthesearchrange.YoucanusethisargumentonlyifConditionismsoConditionAnyTimeBetweenormsoConditionAnyNumberBetween.
ConnectorOptionalMsoConnector.Specifiesthewaytwosearchcriteriaarecombined.
MsoConnectorcanbeoneoftheseMsoConnectorconstants.msoConnectorAnddefaultmsoConnectorOr
AddmethodasitappliestotheNewFileobject.
AddsanewitemtotheNewItemtaskpane.ReturnsaBoolean.Trueiftheitemwassuccessfullyadded.
expression.Add(FileName,Section,DisplayName,Action)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
FileNameRequiredString.Thenameofthefiletoaddtothelistoffilesonthetaskpane.
SectionOptionalVariant.Thesectiontowhichtoaddthefile.CanbeanymsoFileNewSectionconstant.
DisplayNameOptionalVariant.Thetexttodisplayinthetaskpane.
ActionOptionalVariant.Theactiontotakewhenauserclicksontheitem.CanbeanymsoFileNewActionconstant.
AddmethodasitappliestotheODSOFiltersobject.
AddsanewfiltertotheODSOFilterscollection.
expression.Add(Column,Comparison,Conjunction,bstrCompareTo,DeferUpdate)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
ColumnRequiredString.Thenameofthetableinthedatasource.
ComparisonRequiredMsoFilterComparison.Howthedatainthetableisfiltered.
MsoFilterComparisoncanbeoneoftheseMsoFilterComparisonconstants.msoFilterComparisonContainsmsoFilterComparisonEqualmsoFilterComparisonGreaterThanmsoFilterComparisonGreaterThanEqualmsoFilterComparisonIsBlankmsoFilterComparisonIsNotBlankmsoFilterComparisonLessThanmsoFilterComparisonLessThanEqualmsoFilterComparisonNotContainsmsoFilterComparisonNotEqual
ConjunctionRequiredMsoFilterConjunction.DetermineshowthisfilterrelatestootherfiltersintheODSOFiltersobject.
MsoFilterConjunctioncanbeoneoftheseMsoFilterConjunctionconstants.msoFilterConjunctionAndmsoFilterConjunctionOr
bstrCompareToOptionalString.IftheComparisonargumentissomethingotherthanmsoFilterComparisonIsBlankormsoFilterComparisonIsNotBlank,astringtowhichthedatainthetableiscompared.
DeferUpdateOptionalBoolean.DefaultisFalse.
AddmethodasitappliestothePermissionobject.
Createsanewsetofpermissionsontheactivedocumentforthespecifieduser.ReturnsaUserPermissionobject.
expression.Add(UserID,Permission,ExpirationDate)
expressionRequired.AnexpressionthatreturnsaPermissionobject.
UserIDRequiredString.Theemailaddress([email protected])oftheusertowhompermissionsontheactivedocumentarebeinggranted.
PermissionOptionalmsoPermission.Thepermissionsontheactivedocumentthatarebeinggrantedtothespecifieduser.
MsoPermissioncanbeoneoracombinationoftheseMsoPermissionconstants.msoPermissionChangemsoPermissionEditmsoPermissionExtractmsoPermissionFullControlmsoPermissionObjModelmsoPermissionPrintmsoPermissionReadmsoPermissionSavemsoPermissionView
ExpirationDateOptionalDate.Theexpirationdateforthepermissionsthatarebeinggranted.
AddmethodasitappliestotheScriptsobject.
AddsaScriptobjecttotheScriptscollectionofoneofthefollowingobjects:aDocumentorRangeobjectinMicrosoftWord;aWorksheetorChartobjectinMicrosoftExcel;oraSlide,SlideRange,slideMaster,ortitleMasterobjectinMicrosoftPowerPoint.ReturnsaScriptobject.
expression.Add(Anchor,Location,Language,Id,Extended,ScriptText)
expressionRequired.TheScriptscollection.
AnchorOptionalRange(MicrosoftExcelonly).TheAnchorargumentacceptsanExcelRangeobject,whichspecifiestheplacementofthescriptanchoronanExcelWorksheet.YoucannotinsertscriptanchorsintoExcelcharts.
LocationOptionalMsoScriptLocation.Specifiesthelocationofthescriptanchorinadocument.Ifyou’vespecifiedtheAnchorargument,theLocationargumentisn’tused;thelocationoftheAnchorargumentdeterminesthelocationofthescriptanchor.
MsoScriptLocationcanbeoneoftheseMsoScriptLocationconstants.msoScriptLocationInBodydefaultmsoScriptLocationInHead
LanguageOptionalMsoScriptLanguage.Specifiesthescriptlanguage.
MsoScriptLanguagecanbeoneoftheseMsoScriptLanguageconstants.msoScriptLanguageASPmsoScriptLanguageJavamsoScriptLanguageOthermsoScriptLanguageVisualBasicdefault
IdOptionalString.TheIDofthe<SCRIPT>taginHTML.TheIdargumentspecifiesanSGMLidentifierusedfornamingelements.Valididentifiersincludeanystringthatbeginswithaletterandiscomposedofalphanumericcharacters;thestringcanalsoincludetheunderscorecharacter(_).TheIDmustbeuniquewithintheHTMLdocument.ThisparameterisexportedastheIDattributeinthe<SCRIPT>tag.
ExtendedOptionalString.Specifiesattributesthataretobeaddedtothe<SCRIPT>tag(LANGUAGEandIDattributesareexportedthroughtheLanguageandIdparametersandshouldnotbeexportedthroughtheExtendedparameter).Thedefaultistheemptystring.Attributesareseparatedbyspaces,thesameasinHTML.TheMicrosoftOfficehostapplicationdoesn’tprovideanymeansofcheckingthesyntaxofpassedattributes.
ScriptTextOptionalString.Specifiesthetextcontainedinablockofscript.Thedefaultistheemptystring.TheMicrosoftOfficehostapplicationdoesn’tcheckthesyntaxofthescript.
Remarks
Ashapeassociatedwithascriptblockisn’texportedorprintedasashapeinHTML;onlythescriptblockgetsexported.
YoucannotusetheAddmethodtoaddascriptanchortoaPowerPointsliderangethatcontainsmorethanoneslide.
AddmethodasitappliestotheSearchFoldersobject.
Addsasearchfoldertoafilesearch.
expression.Add(ScopeFolder)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
ScopeFolderRequiredScopeFolderobject.Thefoldertoaddtothesearch.
AddmethodasitappliestotheSignatureSetobject.
ReturnsaSignatureobjectthatrepresentsanewe-mailsignature.
expression.Add
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
AddmethodasitappliestotheSharedWorkspaceFilesobject.
Addsafiletothedocumentlibraryinasharedworkspace.ReturnsaSharedWorkspaceFileobject.
expression.Add(FileName,ParentFolder,OverwriteIfFileAlreadyExists,KeepInSync)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFilesobject.
FileNameRequiredString.Thepathandfilenameofthefiletobeaddedto
thecurrentsharedworkspace.
ParentFolderOptionalSharedWorkspaceFolder.Thesubfolderinwhichtoplacethefile,ifnotthemaindocumentlibraryfolderwithinthesharedworkspace.Addthefiletothemaindocumentlibraryfolderbyleavingthisoptionalargumentempty.
OverwriteIfFileAlreadyExistsOptionalBoolean.Truetooverwriteanexistingfilebythesamename.DefaultisFalse.
KeepInSyncOptionalBoolean.Truetokeepthelocalcopyofthedocumentsynchronizedwiththecopyinthesharedworkspace.DefaultisFalse.
AddmethodasitappliestotheSharedWorkspaceFoldersobject.
Addsafoldertothedocumentlibraryinasharedworkspace.ReturnsaSharedWorkspaceFolderobject.
expression.Add(FolderName,ParentFolder)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFoldersobject.
FolderNameRequiredString.Thenameofthefoldertobeaddedtothecurrentsharedworkspace.
ParentFolderOptionalSharedWorkspaceFolder.Thesubfolderinwhichtoplacethenewfolder,ifnotthemaindocumentlibraryfolderwithinthesharedworkspace.Addthefoldertothemaindocumentlibraryfolderbyleavingthisoptionalargumentempty.
AddmethodasitappliestotheSharedWorkspaceLinksobject.
Addsalinktothelistoflinksinasharedworkspace.ReturnsaSharedWorkspaceLinkobject.
expression.Add(URL,Description,Notes)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceLinksobject.
URLRequiredString.TheURLofthewebsitetowhichalinkisbeingadded.
DescriptionOptionalString.Optionaldescriptionofthelink.
NotesOptionalString.Optionalnotesaboutthelink.
AddmethodasitappliestotheSharedWorkspaceMembersobject.
Addsamembertothelistofmembersinasharedworkspace.ReturnsaSharedWorkspaceMemberobject.
expression.Add(Email,DomainName,DisplayName,Role)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceMembersobject.
EmailRequiredString.Thenewmember'semailaddressintheformatuser@domain.com.Raisesanerroriftheuserisnotavalidcandidateformembershipinthesharedworkspace.
DomainNameRequiredString.Thenewmember'sWindowsusernameintheformatdomain\user.
DisplayNameRequiredString.Thefriendlynametodisplayforthenewmember.
RoleOptionalString.Anoptionalrolethatdeterminesthetasksthenewmembercanaccomplishinthesharedworkspace;forexample,"Contributor".Aninvalidrolenameraisesanerror.
AddmethodasitappliestotheSharedWorkspaceTasksobject.
Addsatasktothelistoftasksinasharedworkspace.ReturnsaSharedWorkspaceTaskobject.
expression.Add(Title,Status,Priority,Assignee,Description,DueDate)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTasksobject.
TitleRequiredString.Thetitleofthenewtask.
StatusOptionalmsoSharedWorkspaceTaskStatus.Thestatusofthenewtask.DefaultismsoSharedWorkspaceTaskStatusNotStarted.
MsoSharedWorkspaceTaskStatuscanbeoneofthesemsoSharedWorkspaceTaskStatusconstants.msoSharedWorkspaceTaskStatusCompletemsoSharedWorkspaceTaskStatusDeferredmsoSharedWorkspaceTaskStatusInProgressmsoSharedWorkspaceTaskStatusNotStartedmsoSharedWorkspaceTaskStatusWaiting
PriorityOptionalmsoSharedWorkspaceTaskPriority.Thepriorityofthenewtask.DefaultismsoSharedWorkspaceTaskPriorityNormal.
MsoSharedWorkspaceTaskPrioritycanbeoneoftheseMsoSharedWorkspaceTaskPriorityconstants.msoSharedWorkspaceTaskPriorityHighMsoSharedWorkspaceTaskPriorityLowMsoSharedWorkspaceTaskPriorityNormal
AssigneeOptionalSharedWorkspaceMember.Themembertowhomthenewtaskisassigned.
DescriptionOptionalString.Thedescriptionofthenewtask.
DueDateOptionalDate.Theduedateofthenewtask.
Remarks
TheschemathatdefinessharedworkspacetasksandtheirpropertiesforaSharePointProductsandTechnologiessitecanbemodifiedontheserverinsuchawaythattheAddmethodoftheSharedWorkspaceTaskscollectionmayraiseanerror,ormaydisregardthevaluesofcertainarguments.Inparticular,thetaskstatusandpriorityenumerationscanbecustomized.Someexamplesoftheproblemsthatcanresultarementionedbelow:
IfaStatusargumentissupplied,andthestatusfieldhasbeenremovedfromthecustomizedtasksschema,theargumentwillbeignoredandnoerrorwillberaised.IfaStatusvalueissuppliedthatliesoutsidethestatusvaluesrecognizedbythecustomizedtasksschema,theargumentwillbeignored,thedefaultvaluewillbeused,andnoerrorwillberaised.Ifanewrequiredfieldhasbeenaddedtothecustomizedtasksschema,thentheAddmethodwillfailwithanerro,anditwillnolongerbepossibletousetheAddmethodtoaddnewtasks.
Example
AsitappliestotheAnswerWizardFilesobject.
ThisexamplepreparestheAnswerWizardtoacceptacustomfilelistandaddstwocustomAnswerWizardfiles.First,theexampleclearsthefilelist,andthenitaddstwocustomAnswerWizardfilesandchecksthefilecountandthefilenamestoensurethatthefileswereaddedcorrectly.
DimcustomAnswerWizardAsAnswerWizard
SetcustomAnswerWizard=Application.AnswerWizard
customAnswerWizard.ClearFileList
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
customAnswerWizard.Files.Add("c:\awfiles\custom_2.aw")
IfcustomAnswerWizard.Files.Count=2Then
MsgBox"Files"&customAnswerWizard.Files.Item(1)&_
"and"&customAnswerWizard.Files(2)&_
"wereaddedsucessfully."
EndIf
AsitappliestotheCommandBarControlsobject.
Thisexamplecreatesacustomeditingtoolbarthatcontainsbuttons(controls)forcutting,copying,andpasting.
DimcustomBarAsCommandBar
DimnewButtonAsCommandBarButton
SetcustomBar=CommandBars.Add("Custom")
SetnewButton=customBar.Controls_
.Add(msoControlButton,CommandBars("Edit")_
.Controls("Cut").Id)
SetnewButton=customBar.Controls_
.Add(msoControlButton,CommandBars("Edit")_
.Controls("Copy").Id)
SetnewButton=customBar.Controls_
.Add(msoControlButton,CommandBars("Edit")_
.Controls("Paste").Id)
customBar.Visible=True
AsitappliestotheDocumentPropertiesobject.
Thisexample,whichisdesignedtoruninMicrosoftWord,addsthreecustomdocumentpropertiestotheDocumentPropertiescollection.
WithActiveDocument.CustomDocumentProperties
.AddName:="CustomNumber",_
LinkToContent:=False,_
Type:=msoPropertyTypeNumber,_
Value:=1000
.AddName:="CustomString",_
LinkToContent:=False,_
Type:=msoPropertyTypeString,_
Value:="Thisisacustomproperty."
.AddName:="CustomDate",_
LinkToContent:=False,_
Type:=msoPropertyTypeDate,_
Value:=Date
EndWith
AsitappliestothePermissionobject.
Thefollowingexampleassignsacombinationofreadandeditpermissionsonthecurrentdocumenttoauserandspecifiesanexpirationdateforthesedocumentpermissions.
DimobjUserPermAsOffice.UserPermission
SetobjUserPerm=ActiveWorkbook.Permission.Add(_
msoPermissionRead+msoPermissionEdit,#12/31/2005#)
MsgBox"Permissionsaddedfor"&_
objUserPerm.UserId,_
vbInformation+vbOKOnly,_
"PermissionsAdded"
SetobjUserPerm=Nothing
AsitappliestothePropertyTestsobject.
Thisexampleaddstwopropertyteststothesearchcriteria.ThefirsttestisthatthefilesmustbeMicrosoftWorddocuments,andthesecondtestisthattheymusthavebeenmodifiedbetweenJanuary1,1996,andJune30,1996.Theexamplealsodisplaysamessageboxthatshowsthetotalnumberoffilesfound,ifany,andthenameofeachfilefound.
Setfs=Application.FileSearch
fs.NewSearch
Withfs.PropertyTests
.AddName:="FilesofType",_
Condition:=msoConditionFileTypeWordDocuments,_
Connector:=msoConnectorOr
.AddName:="LastModified",_
Condition:=msoConditionAnytimeBetween,_
Value:="1/1/98",SecondValue:="6/30/98",_
Connector:=msoConnectorAnd
EndWith
Iffs.Execute()>0Then
Fori=1Tofs.FoundFiles.Count
strFound=strFound&fs.FoundFiles(i)&vbCrLf
Nexti
MsgBox"Searchfoundthefollowing"_
&fs.FoundFiles.Count&_
"file(s):"&vbCrLf&strFound
Else
MsgBox"Therewerenofilesfound."
EndIf
AsitappliestotheScriptsobject.
ThisexampleaddsanewScripttothespecifiedrangeonworksheetoneintheactiveworkbook.
DimrngScriptAnchorRangeAsRange
DimobjNewScriptAsScript
SetrngScriptAnchorRange=ActiveWorkbook._
Worksheets(1).Range("B5")
SetobjNewScript=ActiveWorkbook._
Worksheets(1).Scripts.Add(rngScriptAnchorRange,_
msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"MyNewScript",,_
"MsgBox(""AddedScriptobjectMyNewScript"")")
AsitappliestotheSharedWorkspaceFilesobject.
Thefollowingexampleaddsanewfiletothefilescollectionofthesharedworkspace.
DimswsfileAsOffice.SharedWorkspaceFile
Setswsfile=ActiveWorkbook.SharedWorkspace.Files.Add(_
"C:\MyWorkbook.xls",_
,True,True)
MsgBox"NewfileURL:"&swsfile.URL,_
vbInformation+vbOKOnly,_
"NewFileinSharedWorkspaceFiles"
Setswsfile=Nothing
AsitappliestotheSharedWorkspaceFoldersobject.
Thefollowingexampleaddsanewfoldertothefolderscollectionofthesharedworkspace.
DimswsFolderAsOffice.SharedWorkspaceFolder
SetswsFolder=ActiveWorkbook.SharedWorkspace.Folders.Add("MyNewFolder")
MsgBox"Newfolder:"&swsFolder.FolderName,_
vbInformation+vbOKOnly,_
"NewFolderinSharedWorkspace"
SetswsFolder=Nothing
AsitappliestotheSharedWorkspaceLinksobject.
Thefollowingexampleaddsanewlinktothelinkscollectionofthesharedworkspace.
DimswsLinkAsOffice.SharedWorkspaceLink
SetswsLink=ActiveWorkbook.SharedWorkspace.Links.Add(_
"http://msdn.microsoft.com",_
"MicrosoftDeveloperNetworkHomePage",_
"Myfavoritedevelopersite!")
MsgBox"Newlink:"&swsLink.Description,_
vbInformation+vbOKOnly,_
"NewLinkinSharedWorkspace"
SetswsLink=Nothing
AsitappliestotheSharedWorkspaceMembersobject.
Thefollowingexampleaddsanewmembertothememberscollectionofthesharedworkspaceintheroleofasitecontributor.
DimswsMemberAsOffice.SharedWorkspaceMember
SetswsMember=ActiveWorkbook.SharedWorkspace.Members.Add(_
"domain\user",_
"NewUser",_
"Contributor")
MsgBox"Newmember:"&swsMember.Name,_
vbInformation+vbOKOnly,_
"NewMemberinSharedWorkspace)"
SetswsMember=Nothing
AsitappliestotheSharedWorkspaceTasksobject.
Thefollowingexampleaddsanewtasktothetaskscollectionofthesharedworkspace,specifiesaduedate,andassignsthetasktothefirstmemberofthesharedworkspace.
DimswsTaskAsOffice.SharedWorkspaceTask
DimswsMemberAsOffice.SharedWorkspaceMember
SetswsMember=ActiveWorkbook.SharedWorkspace.Members(1)
SetswsTask=ActiveWorkbook.SharedWorkspace.Tasks.Add(_
"Completedocumentbyyear-end",_
msoSharedWorkspaceTaskStatusNotStarted,_
msoSharedWorkspaceTaskPriorityNormal,_
swsMember,_
"Myfirstsharedworkspacetask",#12/31/2005#)
MsgBox"Newtask:"&swsTask.Title,_
vbInformation+vbOKOnly,_
"NewTaskinSharedWorkspace"
SetswsMember=Nothing
SetswsTask=Nothing
ShowAll
AddItemMethodAddsalistitemtothespecifiedcommandbarcomboboxcontrol.Thecomboboxcontrolmustbeacustomcontrolandmustbeadrop-downlistboxoracombobox.
NoteThismethodwillfailifit'sappliedtoaneditboxorabuilt-incomboboxcontrol.
expression.AddItem(Text,Index)
expressionRequired.AnexpressionthatreturnsaCommandBarComboBoxobject.
TextRequiredString.Thetextaddedtothecontrol.
IndexOptionalVariant.Thepositionoftheiteminthelist.Ifthisargumentisomitted,theitemisaddedtotheendofthelist.
Example
Thisexampleaddsacomboboxcontroltoacommandbar.Twoitemsareaddedtothecontrol,andthenumberoflineitemsandthewidthofthecomboboxareset.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls.Add(Type:=msoControlComboBox,Id:=1)
WithmyControl
.AddItem"FirstItem",1
.AddItem"SecondItem",2
.DropDownLines=3
.DropDownWidth=75
.ListHeaderCount=0
EndWith
AddToSearchFoldersMethodAddsaScopeFolderobjecttheSearchFolderscollection.
expression.AddToSearchFolders
expressionRequired.AnexpressionthatreturnsaScopeFolderobject.
Remarks
AlthoughyoucanusetheSearchFolderscollection'sAddmethodtoaddaScopeFolderobjecttotheSearchFolderscollection,itisusuallysimplertousetheAddToSearchFoldersmethodoftheScopeFolderobjectthatyouwanttoadd,becausethereisonlyoneSearchFolderscollectionforallsearches.
Example
ThefollowingexampleaddstherootScopeFolderobjecttotheSearchFolderscollection.ForalongerexamplethatusestheAddToSearchFoldersmethod,seetheSearchFolderscollectiontopic.
Application.FileSearch.SearchScopes(1).ScopeFolder.AddToSearchFolders
ApplyFilterMethodAppliesafiltertoamailmergedatasourcetofilterspecifiedrecordsmeetingspecifiedcriteria.
expression.ApplyFilter
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexampleaddsanewfilterthatremovesallrecordswithablankRegionfieldandthenappliesthefiltertotheactivepublication.
SubOfficeFilters()
DimappOfficeAsOfficeDataSourceObject
DimappFiltersAsODSOFilters
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
SetappFilters=appOffice.Filters
MsgBoxappOffice.RowCount
appFilters.AddColumn:="Region",Comparison:=msoFilterComparisonEqual,_
Conjunction:=msoFilterConjunctionAnd,bstrCompareTo:="WA"
appOffice.ApplyFilter
MsgBoxappOffice.RowCount
EndSub
ApplyPolicyMethodAppliesthespecifiedpermissionpolicytotheactivedocument.
expression.ApplyPolicy(Filename)
expressionRequired.AnexpressionthatreturnsaPermissionobject.
FilenameRequiredString.Thepathandfilenameofthepermissionpolicytemplatefile.
Remarks
MicrosoftOfficeInformationRightsManagementsupportstheuseofadministrativepermissionpolicieswhichlistusersandgroupsandtheirdocumentpermissions.TheApplyPolicymethodappliesapermissionpolicytotheactivedocument.
Example
Thefollowingexampleenablespermissionsontheactivedocumentandappliesanadministrativepermissionpolicy.
DimirmPermissionAsOffice.Permission
SetirmPermission=ActiveWorkbook.Permission
DimstrIRMInfoAsString
SelectCaseirmPermission.Enabled
CaseTrue
strIRMInfo="Permissionsarealreadyrestrictedonthisdocument."
CaseFalse
WithirmPermission
.Enabled=True
.ApplyPolicy("\\server\share\permissionpolicy.xml")
EndWith
strIRMInfo="Permissionsarenowrestrictedonthisdocument"&_
vbCrLf&_
"andthepermissionpolicyhasbeenapplied."
EndSelect
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
ShowAll
ClearMethodRemovesalllistitemsfromacommandbarcomboboxcontrol(drop-downlistboxorcombobox)andclearsthetextbox(editboxorcombobox).
NoteThismethodwillfailifit'sappliedtoabuilt-incommandbarcontrol.
expression.Clear
expressionRequired.AnexpressionthatreturnsaCommandBarComboBoxobject.
Example
Thisexamplechecksthenumberofitemsinthecomboboxcontrolonthecommandbarnamed"Custom."Iftherearefewerthanthreeitemsinthelistinthecombobox,theexampleclearsthelist,addsanewfirstitemtothelist,andthendisplaysthisnewitemasthedefaultforthecomboboxcontrol.
SetmyBar=CommandBars("CustomBar")
SetmyControl=myBar.Controls_
Type:=msoControlComboBox)
WithmyControl
.AddItem"FirstItem",1
.AddItem"SecondItem",2
EndWith
IfmyControl.ListCount<3Then
myControl.Clear
myControl.AddItemText:="NewItem",Index:=1
EndIf
ClearFileListMethodClearsthelistoffilesforthecurrentAnswerWizard,includingthedefaultlistoffilesfortheMicrosoftOfficehostapplication.
expression.ClearFileList
expressionAnexpressionthatreturnsanAnswerWizardobject.
Remarks
Usethismethodtoremoveallentriesfromthecurrentfilelistforthespecifiedapplication.YoucanalsouseittoensurethatnoneofthedefaultAnswerWizardfilesforthehostapplicationareavailabletousers.YoucanthenbuildacustomlistoffilesbyusingtheAddmethodoftheAnswerWizardFilescollection.
TorestorethedefaultAnswerWizardfilesetforthehostapplication,usetheResetFileListmethod.
Example
ThisexamplepreparestheAnswerWizardtoacceptacustomfilelistandthenaddstwocustomAnswerWizardfiles.First,theexampleclearsthefilelist,andthenitaddstwocustomAnswerWizardfilesandchecksthefilecountandthefilenamestoensurethatthefileswereaddedcorrectly.
DimcustomAnswerWizardAsAnswerWizard
SetcustomAnswerWizard=Application.AnswerWizard
customAnswerWizard.ClearFileList
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
customAnswerWizard.Files.Add("c:\awfiles\custom_2.aw")
IfcustomAnswerWizard.Files.Count=2Then
MsgBox"Files"&customAnswerWizard.Files.Item(1)&_
"and"&customAnswerWizard.Files(2)&_
"wereaddedsucessfully."
EndIf
CloseMethodClosestheactivemodelessballoon.Youshouldusethismethodonlyincallbackprocedures.
expression.Close
expressionRequired.AnexpressionthatreturnsaBalloonobject.
Example
Thisexampledisplaysaballoonthatcontainsabuttonforeachofthreeprinters.Whenevertheuserclicksoneofthesebuttons,theProcessPrintercallbackprocedureisrunandtheballoonisclosed.
SubselectPrinter()
Setbln=Assistant.NewBalloon
Withbln
.Heading="SelectaPrinter."
.Labels(1).Text="NetworkPrinter"
.Labels(2).Text="LocalPrinter"
.Labels(3).Text="LocalColorPrinter"
.BalloonType=msoBalloonTypeButtons
.Mode=msoModeModeless
.Callback="ProcessPrinter"
.Show
EndWith
EndSub
SubProcessPrinter(blnAsBalloon,lbtnAsLong,_
lPrivAsLong)
Assistant.Animation=msoAnimationPrinting
SelectCaselbtn
Case-1
'Insertnetworkprinter-specificcode.
Case-2
'Insertlocalprinter-specificcode.
Case-3
'Insertcolorprinter-specificcode.
EndSelect
bln.Close
EndSub
CommitMethodCommitsallchangesofthespecifiedSignatureSetcollectiontodisk.UntiltheCommitmethodisexecuted,noneofthechangestotheSignatureSetcollectionaresaved.
expression.Commit
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandcallthisfunction.Thefunctionwilltesttomakesurethatthedigitalsignaturethattheuserselectswillnotexpireinlessthan12months.Ifitwillexpire,thecertificateisn'tattached.
FunctionAddSignature()AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TesttomakesurethatthenewSignatureobject
'doesn'texpiretoosoon.Thisexpressioncalculates
'thenumberofmonthsuntiltheSignatureobjectexpires.
IfDateDiff("m",sig.SignDate,sig.ExpireDate)<12Then
MsgBox"Thiscertificatewillexpireinlessthan1year."&vbCrLf&_
"Pleaseuseanewercertificate."
AddSignature=False
sig.Delete
Else
AddSignature=True
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
ShowAll
CopyMethodCopiesacommandbarcontroltoanexistingcommandbar.
expression.Copy(Bar,Before)
expressionRequired.AnexpressionthatreturnsaCommandBarControl,CommandBarButton,CommandBarPopup,orCommandBarComboBoxobject.
BarOptionalVariant.ACommandBarobjectthatrepresentsthedestinationcommandbar.Ifthisargumentisomitted,thecontroliscopiedtothecommandbarwherethecontrolalreadyexists.
BeforeOptionalVariant.Anumberthatindicatesthepositionforthenewcontrolonthecommandbar.Thenewcontrolwillbeinsertedbeforethecontrolatthisposition.Ifthisargumentisomitted,thecontroliscopiedtotheendofthecommandbar.
Example
Thisexamplecopiesthefirstcontrolfromthecommandbarnamed"Standard"tothefirstcontrolonthecommandbarnamed"Custom”.
SetmyCustomBar=CommandBars("Custom")
SetmyControl=CommandBars("Standard").Controls(1)
WithmyControl
.CopyBar:=myCustomBar,Before:=1
.SetFocus
EndWith
ShowAll
CopyFaceMethodCopiesthefaceofacommandbarbuttoncontroltotheClipboard.
expression.CopyFace
expressionRequired.AnexpressionthatreturnsaCommandBarButtonobject.
Remarks
UsethePasteFacemethodtopastethecontentsoftheClipboardontoabuttonface.
Example
Thisexamplefindsthebuilt-inOpenbutton,copiesthebuttonfacetotheClipboard,andthenpastesthefaceontotheSpellingandGrammarbutton.
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=23)
myControl.CopyFace
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,ID:=2)
myControl.PasteFace
CreateNewMethodCreatesanewdocumentworkspaceontheserverandaddstheactivedocumenttothenewsharedworkspace.
expression.CreateNew(URL,Name)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
URLOptionalString.TheURLfortheparentfolderinwhichthenewsharedworkspaceistobecreated.IfyoudonotsupplyaURL,thenewsharedworkspaceiscreatedintheuser'sdefaultserverlocation.
NameOptionalString.Thenameofthenewsharedworkspace.Defaultstothenameoftheactivedocumentwithoutitsfileextension.Forexample,ifyoucreateasharedworkspacefor"Budget.xls",thenameofthenewsharedworkspacebecomes"Budget".
Remarks
UsetheCreateNewmethodtocreateanewsharedworkspacefortheactivedocument.Omitthe2optionalargumentstocreatetheworkspaceusingthenameoftheactivedocumentintheuser'sdefaultserverlocation.
TheCreateNewmethodraisesanerroriftheactivedocumenthaschangesthathavenotbeensaved.Thedocumentmustbesavedbeforeitcanbeaddedtoasharedworkspace.
Example
ThefollowingexamplecreatesanewsharedworkspaceattheURLhttp://server/sites/mysite/,namestheworkspace"MySharedBudgetDocument",andaddstheactivedocumenttotheworkspace.TheURLpropertyofthenewsharedworkspacereturnshttp://server/sites/mysite/My%20Shared%20Budget%20Document/,theNamepropertyreturns"MySharedBudgetDocument,andCountpropertyoftheFilescollectionshowsasinglefile.
DimswsAsOffice.SharedWorkspace
DimstrSWSInfoAsString
Setsws=ActiveWorkbook.SharedWorkspace
sws.CreateNew"http://server/sites/mysite/","MySharedBudgetDocument"
strSWSInfo="Name:"&sws.Name&vbCrLf&_
"URL:"&sws.URL&vbCrLf&_
"File(s):"&sws.Files.Count
MsgBoxstrSWSInfo,vbInformation+vbOKOnly,_
"NewSharedWorkspaceInformation"
Setsws=Nothing
ShowAll
DeleteMethodDeletemethodasitappliestotheAnswerWizardFilesobject.
Deletesthespecifiedobjectfromitscollection.
expression.Delete(FileName)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
FileNameRequiredString.Thenameofthefiletobedeleted,includingthefully-qualifiedpath,filename,andextension.
DeletemethodasitappliestotheCommandBar,Script,Scripts,andSignatureobjects.
Deletesthespecifiedobjectfromthecollection.
expression.Delete
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Remarks
FortheScriptscollection,usingtheDeletemethodremovesallscriptsfromthespecifiedMicrosoftWorddocument,MicrosoftExcelworksheet,orMicrosoftPowerPointslide.Ascriptanchorisrepresentedbyashapeinthehostapplication.Therefore,theShapeobjectassociatedwitheachscriptanchoroftypemsoScriptAnchorisdeletedfromtheShapescollectioninExcelandPowerPointandfromtheInlineShapesandShapescollectionsinWord.
DeletemethodasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
Deletesthespecifiedobjectfromitscollection.
expression.Delete(Temporary)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
TemporaryOptionalVariant.Truetodeletethecontrolforthecurrentsession.Theapplicationwilldisplaythecontrolagaininthenextsession.
DeletemethodasitappliestotheDocumentLibraryVersionobject.
RemovesadocumentlibraryversionfromtheDocumentLibraryVersionscollection.
expression.Delete
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
DeletemethodasitappliestotheDocumentPropertyobject.
Removesacustomdocumentproperty.
expression.Delete
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Remarks
Youcannotdeleteabuilt-indocumentproperty.
DeletemethodasitappliestotheFileDialogFiltersobject.
Removesafiledialogfilter.
expression.Delete(filter)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
filterOptionalVariant.Thefiltertoberemoved.
DeletemethodasitappliestotheODSOFiltersobject.
DeletesafilterobjectfromtheODSOFilterscollection.
expression.Delete(Index,DeferUpdate)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.Thenumberofthefiltertodelete.
DeferUpdateOptionalBoolean.
DeletemethodasitappliestotheSharedWorkspaceobject.
Deletesthecurrentsharedworkspaceandalldatawithinit.
expression.Delete
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
TheDeletemethodwillfailiftheuserdoesnothavepermissiontodeletethecurrentsharedworkspace.
Iftheactivedocumentwasopeneddirectlyfromtheworkspace,thenafter
deletingtheworkspace,thedocumentwillnolongerbesavedondisk.Thedevelopermustremembertosavethedocumenttoanewlocationbeforeclosingit,orthedocumentwillceasetoexist.
DeletemethodasitappliestotheSharedWorkspaceFile,SharedWorkspaceLink,SharedWorkspaceMember,andSharedWorkspaceTaskobjects.
Deletesthecurrentobject.
expression.Delete
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
TheDeletemethodwillfailiftheuserdoesnothavepermissiontodeletethecurrentobjectfromthesharedworkspace.
DeletemethodasitappliestotheSharedWorkspaceFolderobject.
Deletesthecurrentsharedworkspacefolderandalldatawithinit.
expression.Delete(DeleteEvenIfFolderContainsFiles)
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFolderobject.
DeleteEvenIfFolderContainsFilesOptionalBoolean.Truetodeletethefolderwithoutwarningevenifthefoldercontainsfiles.DefaultisFalse.
TheDeletemethodwillfailiftheuserdoesnothavepermissiontodeletethecurrentfolderfromthesharedworkspace.
Example
AsitappliestotheCommandBarobject.
Thisexampledeletesallcustomcommandbarsthataren'tvisible.
foundFlag=False
delBars=0
ForEachbarInCommandBars
If(bar.BuiltIn=False)And_
(bar.Visible=False)Then
bar.Delete
foundFlag=True
delBars=delBars+1
EndIf
Nextbar
IfNotfoundFlagThen
MsgBox"Nocommandbarshavebeendeleted."
Else
MsgBoxdelBars&"custombar(s)deleted."
EndIf
AsitappliestotheDocumentPropertyobject.
Thisexampledeletesacustomdocumentproperty.Forthisexampletorunproperly,youmusthaveacustomDocumentPropertyobjectnamed"CustomNumber".
ActiveDocument.CustomDocumentProperties("CustomNumber").Delete
DisconnectMethodDisconnectsthelocalcopyoftheactivedocumentfromthesharedworkspace.
expression.Disconnect()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
UsetheDisconnectmethodtodetachthelocalcopyoftheactivedocumentfromthesharedworkspace.Thismethodleavestheshareddocumentontheserver;however,thelocalcopywillnolongerbesynchronizedwiththesharedcopyandwillnolongerbenefitfromtheothercollaborationfeaturesofthesharedworkspace.UsetheRemoveDocumentmethodtoremovetheshareddocumentfromtheserver.
Example
Thefollowingexampledetermineswhethertheactivedocumentisconnectedtoasharedworkspace,thenofferstheusertheoptionofdisconnectingit.
DimrAsLong
IfActiveWorkbook.SharedWorkspace.ConnectedThen
r=MsgBox("Areyousureyouwanttodisconnectthisdocument?",_
vbQuestion+vbOKCancel,"Areyousure?")
Ifr=vbOKThen
ActiveWorkbook.SharedWorkspace.Disconnect
MsgBox"Thedocumenthasbeendisconnected.",_
vbInformation+vbOKOnly,"Disconnected"
Else
MsgBox"Disconnectcancelled.",_
vbInformation+vbOKOnly,"StillConnected"
EndIf
Else
MsgBox"Theactivedocumentisnotconnectedtoasharedworkspace.",_
vbInformation+vbOKOnly,"NotConnected"
EndIf
ShowAll
DoAlertMethodDisplaysanalertandreturnsaLongthatindicateswhichbuttontheuserpressed.YoucanchoosetodisplaythisalerteitherthroughtheMicrosoftOfficeAssistantorasanormalmessagebox.
expression.DoAlert(bstrAlertTitle,bstrAlertText,alb,alc,ald,alq,varfSysAlert)
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
bstrAlertTitleRequiredString.Setsthetitleofthealert.
bstrAlertTextRequiredString.Setsthetextofthealert.
albRequiredMsoAlertButtonType.Determineswhichbuttonsaredisplayedonthealert.
MsoAlertButtonTypecanbeoneoftheseMsoAlertButtonTypeconstants.msoAlertButtonAbortRetryIgnoremsoAlertButtonOKmsoAlertButtonOKCancelmsoAlertButtonRetryCancelmsoAlertButtonYesAllNoCancelOnlyusethiswhenthevarfSysAlertargumentissettoFalse.msoAlertButtonYesNomsoAlertButtonYesNoCancel
alcRequiredMsoAlertIconType.Determinestheiconthatisdisplayedonthealert.
MsoAlertIconTypecanbeoneoftheseMsoAlertIconTypeconstants.msoAlertIconCriticalmsoAlertIconInfo
msoAlertIconNoIconmsoAlertIconQuerymsoAlertIconWarning
aldRequiredMsoAlertDefaultType.Determineswhichbuttonissetasthedefaultbuttonofthealert.Ifthisargumentissettoavaluegreaterthanthenumberofbuttons,anerrorisreturned.
MsoAlertDefaultTypecanbeoneoftheseMsoAlertDefaultTypeconstants.msoAlertDefaultFifthmsoAlertDefaultFirstmsoAlertDefaultFourthmsoAlertDefaultSecondmsoAlertDefaultThird
alqRequiredMsoAlertCancelType.AlwayssetthistomsoAlertCancelDefault.Anyothersettingmayreturnanerror.
MsoAlertCancelTypecanbeoneoftheseMsoAlertCancelTypeconstants.msoAlertCancelDefaultmsoAlertCancelFifthmsoAlertCancelFirstmsoAlertCancelFourthmsoAlertCancelSecondmsoAlertCancelThird
varfSysAlertRequiredBoolean.TrueifthealertisdisplayedinamessageboxorFalseifthealertisdisplayedthroughtheOfficeAssistant.
Remarks
ThereturnvaluesoftheDoAlertmethodcorrespondstothevaluesofthevbMsgBoxResultenumeratedtype(forexample,vbYes,vbNo,orvbCancel).Inadditiontothesevalues,thefollowingvaluesmayalsobereturned:
"Yestoall"=8"Tryagain"=10"Continue"=11
Example
ThefollowingexampledisplaysanalertthroughtheOfficeAssistantanddisplaysamessageboxindicatingwhichbuttontheuserpressed.Iftheassistantisdisabled,thealertisdisplayedinanormalmessagebox.
SubAssistantAlert()
WithApplication.Assistant
SelectCase_
.DoAlert(_
"Test",_
"Clickabutton.",_
msoAlertButtonYesAllNoCancel,_
msoAlertIconCritical,_
msoAlertDefaultSecond,_
msoAlertCancelFirst,_
False)
CasevbYes:MsgBox"TheuserclickedYes."
CasevbNo:MsgBox"TheuserclickedNo."
CasevbCancel:MsgBox"TheuserclickedCancel."
Case8:MsgBox"TheuserclickedYesToAll"'ThisisthereturnvalueforYesToAll
CaseElse
EndSelect
EndWith
EndSub
EndWizardMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReleasesthevariablereturnedbytheStartWizardmethod.
NoteYoushouldusethismethodonlywiththeStartWizardmethod.
expression.EndWizard(WizardID,varfSuccess,Animation)
expressionRequired.AnexpressionthatreturnsanAssistantobject.
WizardIDRequiredLong.ThenumberreturnedbytheStartWizardmethod.
varfSuccessRequiredBoolean.Truetoindicatethattheusercompletedthewizardsuccessfully.
AnimationOptionalVariant.TheanimationtheOfficeAssistantperformsifvarfSuccessissettoTrue.ThedefaultvalueismsoAnimationCharacterSuccessMajor.
Example
ThisexampleclosestheOfficeAssistantforawizardsessionthatwascompletedsuccessfullybytheuser.ThevariablelHelpForWizwasassignedthereturnvalueoftheStartWizardmethod.
Assistant.EndWizardWizardId:=lHelpForWiz,_
varfSuccess:=True,Animation:=msoAnimationGoodbye
ShowAll
ExecuteMethodExecutemethodasitappliestotheFileSearchobject.
Beginsthesearchforthespecifiedfile(s).ReturnsaLong;zero(0)ifnofilesarefound,orapositivenumberifoneormorefilesarefound.
expression.Execute(SortBy,SortOrder,AlwaysAccurate)
expressionRequired.AnexpressionthatreturnsaFileSearchobject.
SortByOptionalMsoSortBy.Themethodusedtosortthereturnedfile(s).
MsoSortBycanbeoneoftheseMsoSortByconstants.msoSortByFileNamedefaultmsoSortByFileTypemsoSortByLastModifiedmsoSortByNonemsoSortBySize
SortOrderOptionalMsoSortOrder.Theorderinwhichthereturnedfile(s)aresorted.
MsoSortOrdercanbeoneoftheseMsoSortOrderconstants.msoSortOrderAscendingdefaultmsoSortOrderDescending
AlwaysAccurateOptionalBoolean.Truetohavethefilesearchincludefilesthathavebeenadded,modified,ordeletedsincethefileindexwaslastupdated.ThedefaultvalueisTrue.
ExecutemethodasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,CommandBarPopup,andFileDialogobjects.
Forthecommandbarobjects,runstheprocedureorbuilt-incommandassignedtothespecifiedcommandbarcontrol.Forcustomcontrols,usetheOnActionpropertytospecifytheproceduretoberun.
ForFileDialogobjectsoftypemsoFileDialogOpenormsoFileDialogSaveAs,carriesoutauser'sactionrightaftertheShowmethodisinvoked.
expression.Execute
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Example
AsitappliestotheFileSearchobject.
ThisexamplesearchesforallfilesintheMyDocumentsfolderthatendwiththefilenameextension“.doc”andthendisplaysthelocationandnameofeachfilefound.Theexamplealsosortsthelistofreturnedfilenamesinascendingalphabeticorder.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.FileName="*.doc"
If.Execute(SortBy:=msoSortbyFileName,_
SortOrder:=msoSortOrderAscending)>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
AsitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
ThisMicrosoftExcelexamplecreatesacommandbarandthenaddsabuilt-incommandbarbuttoncontroltoit.ThebuttonexecutestheExcelAutoSumfunction.ThisexampleusestheExecutemethodtototaltheselectedrangeofcellswhenthecommandbarappears.
DimcbrCustBarAsCommandBar
DimctlAutoSumAsCommandBarButton
SetcbrCustBar=CommandBars.Add("Custom")
SetctlAutoSum=cbrCustBar.Controls_
.Add(msoControlButton,CommandBars("Standard")_
.Controls("AutoSum").Id)
cbrCustBar.Visible=True
ctlAutoSum.Execute
ShowAll
FindControlMethodReturnsaCommandBarControlobjectthatfitsaspecifiedcriteria.
expression.FindControl(Type,Id,Tag,Visible,Recursive)
expressionRequired.AnexpressionthatreturnsaCommandBarsobject.
TypeOptionalMsoControlType.Thetypeofcontrol.
MsoControlTypetypecanbeoneoftheseMsoControlTypeconstants.msoControlActiveXmsoControlAutoCompleteCombomsoControlButtonmsoControlButtonDropdownmsoControlButtonPopupmsoControlComboBoxmsoControlCustommsoControlDropdownmsoControlEditmsoControlExpandingGridmsoControlGaugemsoControlGenericDropdownmsoControlGraphicCombomsoControlGraphicDropdownmsoControlGraphicPopupmsoControlGridmsoControlLabelmsoControlLabelExmsoControlOCXDropDownmsoControlPanemsoControlPopupmsoControlSpinner
msoControlSplitButtonMRUPopupmsoControlSplitButtonPopupmsoControlSplitDropdownmsoControlSplitExpandingGridmsoControlWorkPane
IdOptionalVariant.Theidentifierofthecontrol.
TagOptionalVariant.Thetagvalueofthecontrol.
VisibleOptionalVariant.Truetoincludeonlyvisiblecommandbarcontrolsinthesearch.ThedefaultvalueisFalse.VisiblecommandbarsincludeallvisibletoolbarsandanymenusthatareopenatthetimetheFindControlmethodisexecuted.
RecursiveOptionalBoolean.Truetoincludethecommandbarandallofitspop-upsubtoolbarsinthesearch.ThisargumentonlyappliestotheCommandBarobject.ThedefaultvalueisFalse.
Remarks
IftheCommandBarscollectioncontainstwoormorecontrolsthatfitthesearchcriteria,FindControlreturnsthefirstcontrolthat'sfound.Ifnocontrolthatfitsthecriteriaisfound,FindControlreturnsNothing.
Example
Thisexamplefindsthefirstcontrolonthecommandbarnamed“Custom”.Ifthecontrolisabutton,theexampleusestheFindControlmethodtofindtheCopybutton(ontheStandardtoolbar)andthencopiesthefacefromtheCopybuttonandpastesitontothecontrol.
SetoldCtrl=CommandBars("Custom").Controls(1)
IfoldCtrl.Type=1Then
SetnewCtrl=CommandBars.FindControl(Type:=_
MsoControlButton,ID:=_
CommandBars("Standard").Controls("Copy").ID)
NewCtrl.CopyFace
OldCtrl.PasteFace
EndIf
ShowAll
FindControlsMethodReturnstheCommandBarControlscollectionthatfitsthespecifiedcriteria.
expression.FindControls(Type,Id,Tag,Visible)
expressionRequired.AnexpressionthatreturnsaCommandBarControlscollection.
TypeOptionalMsoControlType.Thetypeofcontrol.
MsoControlTypetypecanbeoneoftheseMsoControlTypeconstants.msoControlActiveXmsoControlAutoCompleteCombomsoControlButtonmsoControlButtonDropdownmsoControlButtonPopupmsoControlComboBoxmsoControlCustommsoControlDropdownmsoControlEditmsoControlExpandingGridmsoControlGaugemsoControlGenericDropdownmsoControlGraphicCombomsoControlGraphicDropdownmsoControlGraphicPopupmsoControlGridmsoControlLabelmsoControlLabelExmsoControlOCXDropDownmsoControlPanemsoControlPopup
msoControlSpinnermsoControlSplitButtonMRUPopupmsoControlSplitButtonPopupmsoControlSplitDropdownmsoControlSplitExpandingGridmsoControlWorkPane
IdOptionalVariant.Thecontrol’sidentifier.
TagOptionalVariant.Thecontrol’stagvalue.
VisibleOptionalVariant.Truetoincludeonlyvisiblecommandbarcontrolsinthesearch.ThedefaultvalueisFalse.
Remarks
Ifnocontrolsthatfitsthecriteriaarefound,theFindControlsmethodreturnsNothing.
Example
ThisexampleusestheFindControlsmethodtoreturnallmembersoftheCommandBarscollectionthathaveanIDof18anddisplays(inamessagebox)thenumberofcontrolsthatmeetthesearchcriteria.
DimmyControlsAsCommandBarControls
SetmyControls=CommandBars.FindControls(Type:=msoControlButton,ID:=18)
MsgBox"Thereare"&myControls.Count&_
"controlsthatmeetthesearchcriteria."
GetUpdateMethodComparesthelocalversionoftheshareddocumenttotheversionontheserver.
expression.GetUpdate
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
UsetheGetUpdatemethodtocomparethelocalversionoftheshareddocumenttotheversionontheserverandtorefreshthesyncstatus.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Inmanycircumstances,thebestwaytoresolveanerrorconditionistocalltheGetUpdatemethod.Forexample,ifacalltoPutUpdateresultsinanerrorcondition,thenacalltoGetUpdatewillresetthestatustomsoSyncStatusLocalChanges.
Example
ThefollowingexamplecomparesthelocalandservercopiesofthedocumentusingtheGetUpdatemethodandreportswhethertheserverhasanewercopy.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
objSync.GetUpdate
IfobjSync.Status=msoSyncStatusNewerAvailableThen
strStatus="Anewerversionisavailableontheserver."
MsgBoxstrStatus,vbInformation+vbOKOnly,"SyncInformation"
EndIf
SetobjSync=Nothing
HelpMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
DisplaystheOfficeAssistantandthebuilt-in"Whatwouldyouliketodo?"AssistantballoonforstandardOfficeonlineHelp.
expression.Help
expressionRequired.AnexpressionthatreturnsanAssistantobject.
Example
Thisexampledisplaysthebuilt-in"Whatwouldyouliketodo?"Assistantballoonwhentheuserchecksthe"Ineedmoreinformation"checkbox.
Setb=Assistant.NewBalloon
Withb
.Heading="UserInformation"
.Text="Selectyourskilllevel"
.CheckBoxes(1).Text="Beginner."
.CheckBoxes(2).Text="Advanced."
.CheckBoxes(3).Text="Ineedmoreinformation."
.Show
EndWith
Ifb.CheckBoxes(3).Checked=TrueThen
Assistant.Help
EndIf
ShowAll
ItemMethodItemmethodasitappliestotheCOMAddInsobject.
ReturnsamemberofthespecifiedCOMAddInscollection.
expression.Item(Index)
expressionRequired.ThespecifiedCOMAddInscollection.
IndexRequiredVariant.EitheranordinalvaluethatreturnstheCOMadd-inatthatpositionintheCOMAddInscollection,oraStringvaluethatrepresentstheProgIDofthespecifiedCOMadd-in.
ItemmethodasitappliestotheFileDialogFiltersobject.
ReturnsaFileDialogFilterobjectthatisamemberofthespecifiedFileDialogFilterscollection.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.TheindexnumberoftheFileDialogFilterobjecttobereturned.
ItemmethodasitappliestotheFileDialogSelectedItemsobject.
ReturnsaStringthatcorrespondstothepathofoneofthefilesthattheuserselectedfromafiledialogboxthatwasdisplayedusingtheShowmethodoftheFileDialogobject.TheFileDialogSelectedItemscollectionisacollectionofstrings.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.Theindexnumberofthestringtobereturned.
ItemmethodasitappliestotheHTMLProjectItemsobject.
ReturnstheHTMLProjectItemobjectthatrepresentsaparticularprojectintheMicrosoftScriptEditor.
expression.Item(Index)
expressionRequired.AnHTMLProjectItemscollection.
IndexRequiredVariant.ThenameorindexnumberoftheHTMLprojectitemtobereturned.
ItemmethodasitappliestotheScriptsobject.
ReturnsamemberoftheScriptscollection.AcceptstheindexnumberorIDofthescriptyouwanttheMicrosoftOfficeapplicationtoreturn.TheItemmethodacceptsaVariantvaluethatcanaccepteitheranordinalnumber(indexvalue),whichreturnsthescriptstoredatthatpositionintheScriptscollection,oraStringvaluethatrepresentsthenameorIDofthescript.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaScriptsobject.
IndexRequiredVariant.TheIDorindexnumberofthescripttobereturned.
Remarks
TheScriptscollectioncontainsallofthescriptsinagivendocument,insourceorder(theorderinwhichScriptobjectsappearinthesourcefile).Scriptsaremaintainedinsourceorderregardlessoftheirlocationinthedocument—thatis,whetherthey’reintheheaderorthebodytext.
YoucanusetheItemmethodtoaccessascriptintheScriptscollectionbyusingtheIDofthe<SCRIPT>tag.TheIDattributeofthe<SCRIPT>tagisidenticaltotheIdpropertyoftheScriptobject.IfthereareduplicateormultipleIDsinthedocumentandyouusetheIdpropertyofaScriptobjecttoaccessascriptbyusingtheItemmethod,OfficereturnsthefirstscriptthatmatchestheID;additionalscriptswiththesameIDareignored.
NewscriptanchorsaddedtothecollectionareappendedtotheendoftheScriptscollectionintheorderinwhichtheywereaddedtothedocument.ThescriptanchorsremaininthisorderuntilthedocumentissavedasHTML,closed,andthenopenedagaininthehostapplication.FollowingthesestepscausestheScriptscollectiontobeindexedintheorderinwhichthescriptanchorsappearinthedocument,whichmaybedifferentthantheorderinwhichtheywereaddedtoit.Therefore,you’readvisedtousetheIdpropertyoftheScriptobject,ratherthanthescript’spositioninthecollection,toensurepositiveidentificationofthescript.
LoadFromFileMethodUpdatesthetextintheMicrosoftScriptEditorwithtextfromthespecifiedfile(ondisk).
expression.LoadFromFile(Filename)
expressionAnHTMLProjectItemobject.
FilenameRequiredString.Thefullyqualifiedpathofthetextfilethatcontainsthetexttobeloaded.
Example
ThisexampledetermineswhetherthespecifiedHTMLprojectitemisopen;iftheitemisopen,theexamplethenloadsscriptfromthespecifiedfile.
IfActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).IsOpenThen
ActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).LoadFromFile("C:\MyScript.txt")
Else
MsgBox"TheHTMLProjectItemisnotopen."
EndIf
ShowAll
MoveMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
MovemethodasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
Movesthespecifiedcommandbarcontroltoanexistingcommandbar.
expression.Move(Bar,Before)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
BarOptionalVariant.ACommandBarobjectthatrepresentsthedestinationcommandbarforthecontrol.Ifthisargumentisomitted,thecontrolismovedtotheendofthecommandbarwherethecontrolcurrentlyresides.
BeforeOptionalVariant.Anumberthatindicatesthepositionforthecontrol.Thecontrolisinsertedbeforethecontrolcurrentlyoccupyingthisposition.Ifthisargumentisomitted,thecontrolisinsertedonthesamecommandbar.
MovemethodasitappliestotheAssistantobject.
MovestheOfficeAssistanttothespecifiedlocation.
expression.Move(xLeft,yTop)
expressionRequired.AnexpressionthatreturnsanAssistantobject.
xLeftRequiredInteger.TheleftpositionoftheOfficeAssistantwindow,inpoints.
yTopRequiredInteger.ThetoppositionoftheOfficeAssistantwindow,inpoints.
Example
AsitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
ThisexamplemovesthefirstcomboboxcontrolonthecommandbarnamedCustomtothepositionbeforetheseventhcontrolonthatcommandbar.Theexamplesetsthetagto"Selectionbox"andassignsthecontrolalowprioritysothatitwilllikelybedroppedfromthecommandbarifallthecontrolsdon'tfitinonerow.
Setallcontrols=CommandBars("Custom").Controls
ForEachctrlInallControls
Ifctrl.Type=msoControlComboBoxThen
Withctrl
.MoveBefore:=7
.Tag="Selectionbox"
.Priority=5
EndWith
ExitFor
EndIf
Next
AsitappliestotheAssistantobject.
ThisexampledisplaystheOfficeAssistantinthespecifiedlocationandsetsseveraloptionsbeforemakingitvisible.
WithAssistant
.Reduced=True
.MovexLeft:=400,yTop:=300
.MoveWhenInTheWay=True
.TipOfDay=True
.Visible=True
.Animation=msoAnimationGreeting
EndWith
NewSearchMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Resetsallthesearchcriteriasettingstotheirdefaultsettings.
expression.NewSearch
expressionRequired.AnexpressionthatreturnsaFileSearchobject.
Remarks
Searchcriteriasettingsareretainedthroughoutanapplicationsession.Usethismethodeverytimeyouchangesearchcriteria.ThismethodwillnotresetthevalueoftheLookInproperty.
Example
ThisexampleusestheNewSearchmethodtoresetthedefaultsearchcriteriabeforebeginninganewsearch.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.FileName="run"
.TextOrProperty="San*"
.MatchAllWordForms=True
.FileType=msoFileTypeAllFiles
If.Execute()>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
ShowAll
OpenMethodAsitappliestotheDocumentLibraryVersionobject.
OpensthespecifiedversionoftheshareddocumentfromtheDocumentLibraryVersionscollectioninread-onlymode.
expression.Open()
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
AsitappliestotheHTMLProjectandHTMLProjectItemobjects.
OpensthespecifiedHTMLprojectorHTMLprojectitemintheMicrosoftScriptEditorinoneoftheviewsspecifiedbytheoptionalMsoHTMLProjectOpenconstantslistedbelow.Ifoneoftheconstantsisnotspecified,theprojectitemisopenedinthedefaultview.
expression.Open(OpenKind)
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
OpenKindOptionalMsoHTMLProjectOpen.Theviewinwhichthespecifiedprojectorprojectitemisopened.
MsoHTMLProjectOpencanbeoneoftheseMsoHTMLProjectOpenconstants.msoHTMLProjectOpenSourceViewmsoHTMLProjectOpenTextView
Remarks
ThedefaultviewisdeterminedbywhetherornottheMicrosoftScriptEditorisopenwhentheOpenmethodisexecuted.IftheScriptEditorisnotopen,theOpenmethodstartstheScriptEditorinsourceview.IftheScriptEditorisalreadyopen,theOpenmethodactivatestheScriptEditoranddisplaysthescriptinthecurrentview.
Example
AsitappliestotheDocumentLibraryVersionobject
Thefollowingexampleopenstheprevioussavedversionoftheactivedocumentinread-onlymode.
DimdlvVersionsAsOffice.DocumentLibraryVersions
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
dlvVersions(dlvVersions.Count-1).Open
SetdlvVersions=Nothing
AsitappliestotheHTMLProjectobject
ThisexampleopenstheHTMLprojectintheactiveworkbookinsourceview.
AppActiveWorkbook.HTMLProject.Open_
(msoHTMLProjectOpenSourceView)
AsitappliestotheHTMLProjectItemobject
ThisexampleopensthefirstHTMLprojectitemintheactiveworkbookintextview.
ActiveWorkbook.HTMLProject.HTMLProjectItems_
Item(1).Open(msoHTMLProjectOpenTextView)
ShowAll
OpenVersionMethodOpensadifferentversionoftheshareddocumentalongsidethecurrentlyopenlocalversion.
expression.OpenVersion(SyncVersionType)
expressionRequired.AnexpressionthatreturnsaSyncobject.
SyncVersionTypeRequiredMsoSyncVersionType.
MsoSyncVersionTypecanbeoneofthefollowingmsoSyncVersionTypeconstants.msoSyncVersionLastViewed(0)msoSyncVersionServer(1)
Remarks
UsetheOpenVersionmethodtoopenthelastversionviewed(msoSyncVersionLastViewed)ortheservercopy(msoSyncVersionServer)oftheshareddocumentalongsidethecurrentlyopenlocalversion.
ThemsoSyncVersionLastViewedoptiondisplaysthecopyofthedocumentthatiscreatedwhenevertheuseroverwritesthelocalcopywiththeservercopy.Forexample,ifyoucalltheResolveConflictmethodwiththemsoSyncConflictServerWinsoption,thenyourlocalchangesaresavedandcanbeviewedbycallingOpenVersion(msoSyncVersionLastViewed).
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Example
Thefollowingexamplepromptstheusertoopentheservercopyoftheshareddocumentalongsidethecurrentlyopenlocalversion.
DimobjSyncAsOffice.Sync
DimlngChoiceAsVbMsgBoxResult
SetobjSync=ActiveDocument.Sync
lngChoice=MsgBox("Viewservercopy?",_
vbQuestion+vbOKCancel,"OpenServerVersion?")
IflngChoice=vbOKThen
objSync.OpenVersionmsoSyncVersionServer
EndIf
SetobjSync=Nothing
ShowAll
PasteFaceMethodPastesthecontentsoftheClipboardontoacommandbarbuttoncontrol.
expression.PasteFace
expressionRequired.AnexpressionthatreturnsaCommandBarButtonobject.
Example
Thisexamplefindsthebuilt-inFileOpenbuttonandpastesthefacefromtheSpellingandGrammarbuttonontoitfromtheClipboard.
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=2)
myControl.CopyFace
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=23)
myControl.PasteFace
PickSolutionMethodDisplaysadialogboxwhichallowstheusertochooseanavailableXMLexpansionpacktoattachtotheactiveMicrosoftOfficeWord2003documentorMicrosoftOfficeExcel2003workbook.
expression.PickSolution(ConsiderAllSchemas)
expressionRequired.AnexpressionthatreturnsaSmartDocumentobject.
ConsiderAllSchemasOptionalBoolean.TruedisplaysallavailableXMLexpansionpacksinstalledontheuser'scomputer.FalsedisplaysonlyXMLexpansionpacksapplicabletotheactivedocument.DefaultvalueisFalse.
Remarks
UsethePickSolutionmethodtoallowtheusertoselectanXMLexpansionpackfromalist.TheschemaattachedtotheactivedocumentorworkbookdetermineswhichXMLexpansionpacksareapplicable.
ThePickSolutionmethoddoesnotreturnavaluetoindicatewhethertheuserselectedanXMLexpansionpackorclickedCancelinthedialogbox.ChecktheSolutionIDpropertyaftercallingPickSolutiontodeterminewhetheranXMLexpansionpackhasbeenattached.
Ifthesmartdocumentdeveloperhasfailedtospecify"targetApplication"intheXMLexpansionpackmanifestfile,thelistdisplayedbyPickSolutionmayincludeXMLexpansionpacksthatarenottargetedtotheactiveapplication;forexample,anExcelusermayseeXMLexpansionpackstargetedexclusivelytoWord.Inthesecircumstances,theusermayselectanXMLexpansionpackthatisnotappropriatefortheactiveapplication.
FormoreinformationonsmartdocumentsorXMLexpansionpacksforsmartdocuments,pleaseseetheSmartDocumentSoftwareDevelopmentKit(SDK)ontheMicrosoftDeveloperNetwork(MSDN)Website.
Example
ThefollowingexamplecheckstheSolutionIDpropertytodeterminewhethertheactiveMicrosoftWorddocumentalreadyhasanattachedXMLexpansionpack;ifnot,itdisplaysadialogboxwhichallowstheusertochooseanavailableXMLexpansionpack.Itthendisplaysthepropertiesofthesmartdocument.
DimobjSmartDocAsOffice.SmartDocument
DimstrSmartDocInfoAsString
SetobjSmartDoc=ActiveDocument.SmartDocument
IfobjSmartDoc.SolutionID="None"OrobjSmartDoc.SolutionID=""Then
objSmartDoc.PickSolutionTrue
EndIf
IfobjSmartDoc.SolutionID<>"None"AndobjSmartDoc.SolutionID<>""Then
strSmartDocInfo="SolutionID:"&objSmartDoc.SolutionID&vbCrLf&_
"SolutionURL:"&objSmartDoc.SolutionURL
MsgBoxstrSmartDocInfo,vbInformation+vbOKOnly,"SmartDocProperties"
Else
MsgBox"TheuserclickedCancel."
EndIf
SetobjSmartDoc=Nothing
PutUpdateMethodUpdatestheservercopyoftheshareddocumentwiththelocalcopy.
expression.PutUpdate()
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
ThePutUpdatemethodcanencounteraconflictconditioniftheclientisunawareofrecentchangestotheservercopyoftheshareddocument.CalltheGetUpdatemethodbeforecallingPutUpdatetorefreshthestatusoftheservercopyandtodetectapossibleconflict.
ThePutUpdatemethodraisesarun-timeerrorifthelocaldocumenthasunsavedchanges.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Inmanycircumstances,thebestwaytoresolveanerrorconditionistocalltheGetUpdatemethod.Forexample,ifacalltoPutUpdateresultsinanerrorcondition,thenacalltoGetUpdatewillresetthestatustomsoSyncStatusLocalChanges.
Example
ThefollowingexampleupdatestheservercopyofthedocumentfromthelocalcopyusingthePutUpdatemethodifthelocalcopyhasbeenedited.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status=msoSyncStatusLocalChangesThen
objSync.PutUpdate
strStatus="Localchangessavedtoserver."
MsgBoxstrStatus,vbInformation+vbOKOnly,"SyncInformation"
EndIf
SetobjSync=Nothing
RefreshMethodRefreshesthelocalcacheoftheSharedWorkspaceobject'sfiles,folders,links,members,andtasksfromtheserver.
expression.Refresh()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
UsetheRefreshmethodtoensurethatyouareworkingwiththemostup-to-datelistofobjectsandtheirpropertiesfromthesharedworkspace.
Example
Thefollowingexamplerefreshesthesharedworkspaceifithasnotbeenrefreshedinthelast3minutes.Theexamplealsohandlestheerrorconditionwheretheworkspacehasnotyetbeenrefreshed.
OnErrorGoToerr_NeverRefreshed
IfDateDiff("s",ActiveWorkbook.SharedWorkspace.LastRefreshed,Now)>180Then
ActiveWorkbook.SharedWorkspace.Refresh
EndIf
ExitSub
err_NeverRefreshed:
ActiveWorkbook.SharedWorkspace.Refresh
RefreshDocumentMethodRefreshesthespecifiedHTMLprojectintheMicrosoftOfficehostapplication.
expression.RefreshDocument(Refresh)
expressionAnexpressionthatreturnsanHTMLProjectobject.
RefreshRequiredBoolean.Trueifallchangesaretobesaved;Falseifallchangesaretobeignored.
Remarks
UsingthismethodisequivalenttoclickingtheRefreshbuttonontheRefreshtoolbarintheOfficehostapplication.IfyourefreshthedocumentbysettingtheRefreshDocumentmethodtoTrue,allchangestotheHTMLsourcemadeintheMicrosoftScriptEditoraresavedintheOfficehostapplication.IfyousetRefreshDocumenttoFalse,allchangestotheHTMLsourceareignored.NotethatthevaluereturnedbytheStatemethodisaffectedbytheRefreshDocumentmethod.IfyoucallRefreshDocument(True),theStatemethodreturnsmsoHTMLProjectStateDocumentProjectUnlockedifitiscalledaftertherefreshoperation.
Example
ThisexamplerefreshestheHTMLprojectintheactiveworkbookinthehostapplication.
ActiveWorkbook.HTMLProject.RefreshDocument(True)
RefreshPaneMethodRefreshestheDocumentActionstaskpanefortheactiveMicrosoftOfficeWord2003documentorMicrosoftOfficeExcel2003workbook.
expression.RefreshPane()
expressionRequired.AnexpressionthatreturnsaSmartDocumentobject.
Remarks
TheRefreshPanemethodraisesanerroriftheactivedocumentdoesnothaveanXMLexpansionpackattached.
Example
ThefollowingexampledetermineswhethertheactiveMicrosoftExcelworkbookhasanXMLexpansionpackattached.Ifso,itrefreshesthesmartdocument'sDocumentActionstaskpane.
DimobjSmartDocAsOffice.SmartDocument
SetobjSmartDoc=ActiveWorkbook.SmartDocument
IfobjSmartDoc.SolutionID<>"None"Then
objSmartDoc.RefreshPane
Else
MsgBox"NoXMLexpansionpackattached."
EndIf
RefreshProjectMethodRefreshesthespecifiedHTMLprojectintheMicrosoftScriptEditor.
expression.RefreshProject
expressionAnexpressionthatreturnsanHTMLProjectobject.
Remarks
UsingthismethodisequivalenttoclickingtheRefreshbuttonontheRefreshtoolbarintheMicrosoftScriptEditor.IfyourefreshthedocumentbysettingRefreshDocumenttoTrue,allchangestotheHTMLsourcemadeintheOfficehostapplicationaresavedtotheHTMLprojectintheMicrosoftScriptEditor.IfyousetRefreshDocumenttoFalse,allchangestotheHTMLsourceareignored.
Example
ThisexamplerefreshestheHTMLprojectintheMicrosoftScriptEditor.
ActiveWorkbook.HTMLProject.RefreshProject(True)
RefreshScopesMethodRefreshesthelistofcurrentlyavailableScopeFolderobjects.
expression.RefreshScopes
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysallofthecurrentlyavailableScopeFolderobjectsontheC:\driveintheMyComputerscopeanddemonstratestheneedfortheRefreshScopesmethodwhenchangestothefolderlistoccur.
SubTestRefreshScopesMethod()
'DisplayswhathappensbeforeandaftertheRefreshScopes
'methodiscalledwhenanewfolderisaddedtothelist
'ofscopefolders.
'Listbeforethefolderiscreated.
CallListFolderNames
'CreateanewfolderontheC:\driveinMyComputer.
'Anerrorwilloccurifthisfolderalreadyexists.
MkDirPath:="C:\Delete_After_Using"
'Listafterthefolderiscreated.
'Thenewly-createdfolderdoesnotappearinthelist.
CallListFolderNames
'Refreshthelistoffolders.
Application.FileSearch.RefreshScopes
'Thenewly-createdfoldernowappearsinthelist.
CallListFolderNames
EndSub
SubListFolderNames()
DimiasInteger
DimstrResultsAsString
'Loopthroughallthetop-levelfoldernamesontheC:\drive
'inMyComputerandreporttheresults.
'.SearchScopes.Item(1)="MyComputer"
'.ScopeFolders.Item(2)="C:\"
WithApplication.FileSearch.SearchScopes.Item(1)._
ScopeFolder.ScopeFolders.Item(2)
Fori=1To.ScopeFolders.Count
strResults=strResults&.ScopeFolders._
Item(i).Name&vbCrLf
Nexti
MsgBox"FolderNamesonC:\...."&vbCrLf&strResults
EndWith
EndSub
ShowAll
ReleaseFocusMethodReleasestheuserinterfacefocusfromallcommandbars.
expression.ReleaseFocus
expressionRequired.AnexpressionthatreturnsaCommandBarsobject.
Example
Thisexampleaddsthreeblankbuttonstothecommandbarnamed“Custom”andsetsthefocustothecenterbutton.Theexamplethenwaitsfivesecondsbeforereleasingtheuserinterfacefocusfromallcommandbars.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlButton
.Controls.AddType:=msoControlButton
.Controls.AddType:=msoControlButton
.Visible=True
EndWith
SetmyControl=CommandBars("Custom").Controls(2)
WithmyControl
.SetFocus
EndWith
PauseTime=5'Setduration.
Start=Timer'Setstarttime.
DoWhileTimer<Start+PauseTime
DoEvents'Yieldtootherprocesses.
Loop
Finish=Timer
CommandBars.ReleaseFocus
ShowAll
RemoveMethodRemovemethodasitappliestotheFileTypes,PropertyTests,and
SearchFoldersobjects.
Removesthespecifiedobjectfromthecollection.
expression.Remove(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.Theindexnumberofthepropertytesttoberemoved.
RemovemethodasitappliestotheNewFileobject.
RemovesanitemfromtheNew<Item>taskpane.ReturnsaBoolean.
expression.Remove(FileName,Section,DisplayName,Action)
expressionRequired.AnexpressionthatreturnsaNewFileobject.
FileNameRequiredString.Thenameofthefilereference.
SectionOptionalVariant.Thesectionofthetaskpanewherethefilereferenceexists.CanbeanymsoFileNewSectionconstant.
DisplayNameOptionalVariant.Thedisplaytextofthefilereference.
ActionOptionalVariant.Theactiontakenwhenauserclicksontheitem.CanbeanymsoFileNewActionconstant.
RemovemethodasitappliestotheUserPermissionobject.
RemovesthespecifiedUserPermissionobjectfromthePermissioncollectionoftheactivedocument.
expression.Remove()
expressionRequired.AnexpressionthatreturnsaUserPermissionobject.
Remarks
TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.TheRemovemethodremovestheuserandthesetofuserpermissionsdeterminedbythespecifiedUserPermissionobject.
Example
AsitappliestotheFileTypes,PropertyTests,andSearchFoldersobjects.
Thisexampleremovesthefirstsearchcriterionfromthecollection.
Application.FileSearch.PropertyTests.Remove(1)
AsitappliestotheNewFileobject.
ThisexampleremovesthespecifieditemfromtheMicrosoftWordNewDocumenttaskpane.
SubRemoveDocFromTaskPane()
Application.NewDocument.RemoveFileName:="C:\Newfile.doc",_
Section:=msoNewfromTemplate,DisplayName:="NewFile"
CommandBars("TaskPane").Visible=True
EndSub
AsitappliestotheUserPermissionobject.
Thefollowingexampleremovestheseconduser'spermissionsontheactivedocumentfromthedocument'sPermissioncollection.
DimirmPermissionAsOffice.Permission
DimirmUserPermAsOffice.UserPermission
SetirmPermission=ActiveWorkbook.Permission
SetirmUserPerm=irmPermission.Item(2)
irmUserPerm.Remove
MsgBox"Permissionremoved.",_
vbInformation+vbOKOnly,"IRMInformation"
SetirmUserPerm=Nothing
SetirmPermission=Nothing
RemoveAllMethodRemovesallUserPermissionobjectsfromthePermissioncollectionoftheactivedocument.
expression.RemoveAll()
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
TheRemoveAllmethodremovesallUserPermissionsthathavebeenaddedtothePermissioncollectionanddisablesrestrictionsontheactivedocument.AftercallingtheRemoveAllmethod,theEnabledpropertyofthePermissionobjectreturnsFalseandtheCountpropertyreturns0(zero).
Example
ThefollowingexampleusestheRemoveAllmethodtoremovealluserpermissionsandtodisablerestrictionsontheactivedocument.
DimirmPermissionAsOffice.Permission
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
irmPermission.RemoveAll
MsgBox"Allpermissionsremoved."&vbCrLf&_
"Count:"&irmPermission.Count&vbCrLf&_
"Enabled:"&irmPermission.Enabled,_
vbInformation+vbOKOnly,"IRMInformation"
Else
MsgBox"Thisdocumentisnotrestricted.",_
vbInformation+vbOKOnly,"IRMInformation"
EndIf
SetirmPermission=Nothing
RemoveDocumentMethodRemovestheactivedocumentfromthesharedworkspace.
expression.RemoveDocument()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
Iftheuserdoesnothavepermissiontoremovethesharedworkspacedocumentfromtheserver,thentheservercopyremainsintact,butthelocalcopyofthedocumentisdisconnectedfromthesharedworkspace.Inthecasewherethedocumenthasbeenopeneddirectlyfromtheworkspace,thenremovedfromtheworkspaceusingRemoveDocument,thedocumentmustbesavedtoanotherlocationbeforeclosing;otherwise,itwillremainintheworkspace.
UsetheDisconnectmethodtodetachthelocalcopyofthedocumentfromthesharedworkspacewithoutremovingthesharedcopy.
Example
Thefollowingexampledetermineswhethertheactivedocumentisconnectedtoasharedworkspace,thenofferstheusertheoptionofremovingthedocumentfromtheworkspace.
DimrAsLong
IfActiveWorkbook.SharedWorkspace.ConnectedThen
r=MsgBox("Areyousureyouwanttoremovethisdocument?",_
vbQuestion+vbOKCancel,"Areyousure?")
Ifr=vbOKThen
ActiveWorkbook.SharedWorkspace.RemoveDocument
MsgBox"Thedocumenthasbeenremoved.",_
vbInformation+vbOKOnly,"Removed"
Else
MsgBox"Removalcancelled.",_
vbInformation+vbOKOnly,"StillInWorkspace"
EndIf
Else
MsgBox"Theactivedocumentisnotconnectedtoasharedworkspace.",_
vbInformation+vbOKOnly,"NotConnected"
EndIf
ShowAll
RemoveItemMethodRemovesanitemfromacommandbarcomboboxcontrol.
NoteThepropertyfailswhenappliedtocontrolsotherthanlistcontrols.
expression.RemoveItem(Index)
expressionRequired.AnexpressionthatreturnsaCommandBarComboBoxobject.
IndexRequiredLong.Theitemtoberemovedfromthelist.
Example
Thisexampledetermineswhethertherearemorethanthreeitemsinthespecifiedcombobox.Iftherearemorethanthreeitems,theexampleremovestheseconditem,altersthestyle,andsetsanewvalue.ItalsosetstheTagpropertyoftheparentobject(theCommandBarControlobject)toshowthatthelisthaschanged.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
WithCommandBars("Custom").Controls(1)
.AddItem"GetStockQuote",1
.AddItem"ViewChart",2
.AddItem"ViewFundamentals",3
.AddItem"ViewNews",4
.Caption="StockData"
.DescriptionText="ViewDataForStock"
EndWith
SetmyControl=myBar.Controls(1)
WithmyControl
If.ListCount>3Then
.RemoveItem2
.Style=msoComboNormal
.Text="NewDefault"
Setctrl=.Parent
EndIf
EndWith
ShowAll
ResetMethodResetsabuilt-incommandbartoitsdefaultconfiguration,orresetsabuilt-incommandbarcontroltoitsoriginalfunctionandface.
expression.Reset
expressionRequired.AnexpressionthatreturnsaCommandBar,CommandBarControl,CommandBarButton,CommandBarPopup,orCommandBarComboBoxobject.
Remarks
Resettingabuilt-incontrolrestorestheactionsoriginallyintendedforthecontrolandresetseachofthecontrol'spropertiesbacktoitsoriginalstate.Resettingabuilt-incommandbarremovescustomcontrolsandrestoresbuilt-incontrols.
Example
Thisexampleusesthevalueofusertoadjustthecommandbarsaccordingtotheuserlevel.Ifuseris"Level1,"thecommandbarnamed"Custom"isdisplayed.Ifuserisanyothervalue,thebuilt-inVisualBasiccommandbarisresettoitsdefaultstateandthecommandbarnamed"Custom"isdisabled.
SetmyBar=CommandBars("Custom")
Ifuser="Level1"Then
myBar.Visible=True
Else
CommandBars("VisualBasic").Reset
myBar.Enabled=False
EndIf
ResetFileListMethodResetsthelistoffilesforthecurrentAnswerWizardtothedefaultlistoffilesfortheMicrosoftOfficehostapplication.
expression.ResetFileList
expressionAnexpressionthatreturnsanAnswerWizardobject.
Remarks
UsethismethodtorestoreallentriesinthecurrentAnswerWizardfilelisttothelistintheWindowsregistryforthehostapplication.Youcanestablishacustomdefaultfilelistintheregistrybyaddingthenamesofthecustomfilestotheappropriateregistrykey.
CautionIncorrectlyeditingtheregistrymayseverelydamageyouroperatingsystem,requiringyoutoreinstallit.Microsoftcannotguaranteethatproblemsresultingfromeditingtheregistryincorrectlycanberesolved.Beforeeditingtheregistry,backupanyvaluabledata.Forthemostrecentinformationaboutusingandprotectingyourcomputer'sregistry,seeMicrosoftWindowsHelp.
Example
ThisexampleresetsthefilelistforthecurrentAnswerWizardandthendisplaysboththefilecountandthefilenamesinamessagebox.
DimcustomAnswerWizardAsAnswerWizard
DimstrFileListAsString
DimintCounterAsInteger
DimintNumFilesAsInteger
SetcustomAnswerWizard=Application.AnswerWizard
intCounter=1
customAnswerWizard.ResetFileList
strFileList=""
intNumFiles=customAnswerWizard.Files.Count
ForintCounter=1To(intNumFiles)
strFileList=strFileList&_
customAnswerWizard.Files.Item(intCounter)&Chr(13)
Next
MsgBox"Thereare"&customAnswerWizard.Files.Count&_
"filesavaialblethroughthisAnswerWizard:"&_
Chr(13)&strFileList
ResetTipsMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ResetstheapplicationtipsthatappearintheOfficeAssistantballoon.
expression.ResetTips
expressionRequired.AnexpressionthatreturnsanAssistantobject.
Remarks
TheResetTipsmethodcorrespondstotheResetmytipsbuttonontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexampleresetstheapplicationtipsbeforemakingtheOfficeAssistantvisible.Aconfirmationballoonwillappear,tellingtheuserthathisorherapplicationtipshavebeenreset.
WithApplication.Assistant
.On=True
.Visible=True
.Animation=msoAnimationGreeting
.ResetTips
EndWith
ShowAll
ResolveConflictMethodResolvesconflictsbetweenthelocalandtheservercopiesofashareddocument.
expression.ResolveConflict(SyncConflictResolution)
expressionRequired.AnexpressionthatreturnsaSyncobject.
SyncConflictResolutionRequiredMsoSyncConflictResolutionType.
MsoSyncConflictResolutionTypecanbeoneofthesesoSyncConflictResolutionTypeconstants.msoSyncConflictClientWins(0)msoSyncConflictServerWins(1)msoSyncConflictMerge(2)
Remarks
UsetheResolveConflictmethodtoresolvedifferencesbetweenthelocalcopyoftheactivedocumentandtheservercopy.UsethemsoSyncConflictMergeoption(notavailableforaMicrosoftExcelWorkbook)tomergethechangesfromeachdocumentintotheother.ReplacetheservercopywithlocalchangesbyusingthemsoSyncConflictClientWinsoption,orreplacethelocalcopywiththechangedservercopybyusingthemsoSyncConflictServerWinsoption.
ThemsoSyncConflictMergeoptionmergeschangesmadetotheservercopyintothelocalcopy,butdoesnotactuallyresolvetheconflict.Inordertoresolvetheconflictwiththemergedchangeswinning,youmustsavetheactivedocumentaftermergingchanges,thencalltheResolveConflictmethodagainwiththemsoSyncConflictClientWinsoption.
TheResolveConflictmethodcanencounteraconflictconditioniftheclientisunawareofrecentchangestotheservercopyoftheshareddocument.CalltheGetUpdatemethodbeforecallingResolveConflicttorefreshthestatusoftheservercopyandtodetectapossibleconflict.
TheResolveConflictmethodraisesarun-timeerrorifthelocaldocumenthasunsavedchangesorifnoconflictexistsbetweenthe2copiesofthedocument.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Example
Thefollowingexampleattemptstoresolveaconflictbymergingchangesbetweenthelocalandtheservercopiesoftheactivedocument.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status=msoSyncStatusConflictThen
objSync.ResolveConflictmsoSyncConflictMerge
ActiveDocument.Save
objSync.ResolveConflictmsoSyncConflictClientWins
strStatus="Conflictresolvedbymergingchanges."
MsgBoxstrStatus,vbInformation+vbOKOnly,"SyncInformation"
EndIf
SetobjSync=Nothing
RestoreMethodRestoresaprevioussavedversionofashareddocumentfromtheDocumentLibraryVersionscollection.
expression.Restore()
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
Remarks
UsetheRestoremethodtoreturntoanearliersavedversionoftheactivedocument.TheRestoremethoddoesseveralthings:
1. Itchangestheopenversionoftheshareddocumenttoread-onlymodebutleavesitopen.
2. Itopenstherestoredversioninread/writemode.3. Itsavestherestoredversiontotheserverasanewdocumentversion,
makingtherestoredversionthelatestversion.
TheRestoremethodraisesarun-timeerroriftheactivedocumenthaschangesthathavenotbeensaved.
Example
Thefollowingexamplerestoresthepreviousversionoftheactivedocument.
DimdlvVersionsAsOffice.DocumentLibraryVersions
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
dlvVersions(dlvVersions.Count-1).Restore
SetdlvVersions=Nothing
SaveMethodUploadschangesmadeprogrammaticallytoaSharedWorkspaceLinkoraSharedWorkspaceTasktotheserver.
expression.Save()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceLinkoraSharedWorkspaceTaskobject.
Remarks
UsetheSavemethodtouploadchangestotheserverafterchangingthepropertiesofasharedworkspacelinkortask.
Example
ThefollowingexamplesetsanewDueDateforeachtaskinthesharedworkspaceanduploadsthechangestotheserverusingtheSavemethod.
DimswsTaskAsOffice.SharedWorkspaceTask
ConstdtmNewDueDateAsDate=#12/31/2005#
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
swsTask.DueDate=dtmNewDueDate
swsTask.Save
Next
SetswsTask=Nothing
SaveCopyAsMethodSavesthespecifiedHTMLprojectitemusinganewfilename.
expression.SaveCopyAs(Filename)
expressionAnHTMLProjectItemobject.
FilenameRequiredString.ThefullyqualifiedpathofthefiletowhichyouwanttosavetheHTMLprojectitem.
Example
ThisexamplesavesacopyofthetextofthecurrentHTMLprojectitemtothefileNewScript.txt.
ActiveWorkbook.HTMLProject.HTMLProjectItems._
Item(1).SaveCopyAs("C:\NewScript.txt")
SetAvoidRectangleMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
PreventstheOfficeAssistantballoonfrombeingdisplayedinaspecifiedareaofthescreen.
expression.SetAvoidRectangle(Left,Top,Right,Bottom)
expressionRequired.AnexpressionthatreturnsanAssistantobject.
Left,Top,Right,BottomRequiredLong.Thecoordinates(inpointsandrelativetothescreen)oftheareaofthescreenthattheOfficeAssistantballoonwillavoidwhenit'sdisplayed.
Remarks
ThispropertyisintendedtopreventtheOfficeAssistantballoonfromoverlappingcustomdialogboxesandwizards.
Example
ThisexamplepreventstheOfficeAssistantballoonrepresentedbythevariablemyBalloonfrombeingdisplayedintheregionofthescreendenotedbythespecifiedcoordinates.
SetmyBalloon=Assistant.NewBalloon
WithmyBalloon
.SetAvoidRectangle300,250,700,500
.Text="Cannotdisplayincoordinates"&_
"300,250,700,500."
.Show
EndWith
ShowAll
SetFocusMethodMovesthekeyboardfocustothespecifiedcommandbarcontrol.Ifthecontrolisdisabledorisn'tvisible,thismethodwillfail.
Remarks
Thefocusonthecontrolissubtle.Afteryouusethismethod,youwillnoticeathreedimensionalhighlightonthecontrol.Pressingthearrowkeyswillnavigateinthetoolbars,asifyouhadarrivedatthecontrolbypressingonlykeyboardcontrols.
expression.SetFocus
expressionRequired.AnexpressionthatreturnsaCommandBarControl,CommandBarButton,CommandBarPopup,orCommandBarComboBoxobject.
Example
Thisexamplecreatesacommandbarnamed"Custom"andaddsaComboBoxcontrolandaButtoncontroltoit.TheexamplethenusestheSetFocusmethodtosetthefocustotheComboBoxcontrol.
SetfocusBar=CommandBars.Add(Name:="Custom")
WithCommandBars("Custom")
.Visible=True
.Position=msoBarTop
EndWith
SettestComboBox=CommandBars("Custom").Controls_
.Add(Type:=msoControlComboBox,ID:=1)
WithtestComboBox
.AddItem"FirstItem",1
.AddItem"SecondItem",2
EndWith
SettestButton=CommandBars("Custom").Controls_
.Add(Type:=msoControlButton)
testButton.FaceId=17
'Setthefocustothecombobox.
testComboBox.SetFocus
SetSortOrderMethodSetsthesortorderformailmergedata.
expression.SetSortOrder(SortField1,SortAscending1,SortField2,SortAscending2,SortField3,SortAscending3)
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
SortField1RequiredString.Thefirstfieldonwhichtosortthemailmergedata.
SortAscending1OptionalBoolean.True(default)toperformanascendingsortonSortField1;Falsetoperformadescendingsort.
SortField2OptionalString.Thesecondfieldonwhichtosortthemailmergedata.Defaultisanemptystring.
SortAscending2OptionalBoolean.True(default)toperformanascendingsortonSortField2;Falsetoperformadescendingsort.
SortField3OptionalString.Thethirdfieldonwhichtosortthemailmergedata.Defaultisanemptystring.
SortAscending3OptionalBoolean.True(default)toperformanascendingsortonSortField3;Falsetoperformadescendingsort.
Example
ThefollowingexamplesortsthedatasourcefirstaccordingtoZIPcodeindescendingorder,thenonlastnameandfirstnameinascendingorder.
SubSetDataSortOrder()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
appOffice.SetSortOrderSortField1:="ZipCode",_
SortAscending1:=False,SortField2:="LastName",_
SortField3:="FirstName"
EndSub
ShowAll
ShowMethodShowmethodasitappliestotheBalloonobject.
Displaysthespecifiedballoonobject.ReturnsanMsoBalloonButtonTypeconstantthatindicateswhichbuttonorlabeltheuserclickedintheballoon.
MsoBalloonButtonTypecanbeoneoftheseMsoBalloonButtonTypeconstants.msoBalloonButtonAbortmsoBalloonButtonBackmsoBalloonButtonCancelmsoBalloonButtonClosemsoBalloonButtonIgnoremsoBalloonButtonNextmsoBalloonButtonNomsoBalloonButtonNullmsoBalloonButtonOKmsoBalloonButtonOptionsmsoBalloonButtonRetrymsoBalloonButtonSearchmsoBalloonButtonSnoozemsoBalloonButtonTipsmsoBalloonButtonYesmsoBalloonButtonYesToAll
expression.Show
expressionRequired.AnexpressionthatreturnsaBalloonobject.
ShowmethodasitappliestotheFileDialogobject.
DisplaysafiledialogboxandreturnsaLongindicatingwhethertheuserpressedtheactionbutton(-1)orthecancelbutton(0).WhenyoucalltheShow
method,nomorecodewillexecuteuntiltheuserdismissesthefiledialogbox.InthecaseofOpenandSaveAsdialogboxes,usetheExecutemethodrightaftertheShowmethodtocarryouttheuser'saction.
expression.Show
expressionRequired.AnexpressionthatreturnsaFileDialogobject.
Example
AsitappliestotheBalloonobject.
Thisexamplecreatesaballooncontainingtwoballoonlabelchoicesforsettingprinterorientation:PortraitandLandscape.TheexampleusesthereturnvaluefromtheShowmethodinaSelectCasestatementtodeterminewhichorientationtheuserhaschosen.
SetbalNew=Assistant.NewBalloon
WithbalNew
.Heading="Pleasechooseaprinterorientation"
.Labels(1).Text="Portrait"
.Labels(2).Text="Landscape"
.Button=msoButtonSetNone
EndWith
SelectCasebalNew.Show
Case1
'InsertcodetosetprintertoPortrait.
Case2
'InsertcodetosetprintertoLandscape.
EndSelect
Thisexamplecreatesaballooncontainingthreecommandbuttons:Yes,No,andCancel.TheexampleusesthereturnvaluefromtheShowmethodinaSelectCasestatementtodeterminethebuttonclickedbytheuser.
SetbalNew=Assistant.NewBalloon
WithbalNew
.Heading="Areyousureyouwanttosetthe"&_
"printerorientationtoLandscape?"
.BalloonType=msoBalloonTypeButtons
.Button=msoButtonSetYesNoCancel
EndWith
SelectCasebalNew.Show
CasemsoBalloonButtonCancel'UserselectedCancelbutton.
returnValue=MsgBox("Operationcanceled.",_
vbOKOnly,"PrinterMessage")
CasemsoBalloonButtonYes'UserselectedYesbutton.
returnValue=MsgBox("Printersetto"&_
"Landscape.",vbOKOnly,"PrinterMessage")
CasemsoBalloonButtonNo'UserselectedNobutton.
returnValue=MsgBox("Printerorientationnot"&_
"reset.",vbOKOnly,"PrinterMessage")
EndSelect
AsitappliestotheFileDialogobject.
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Theuserpressedtheactionbutton.
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisastringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Thepathis:"&vrtSelectedItem
NextvrtSelectedItem
'TheuserpressedCancel.
Else
EndIf
EndWith
'Settheobjectvariabletonothing.
Setfd=Nothing
EndSub
ShowAll
ShowPopupMethodDisplaysacommandbarasashortcutmenuatthespecifiedcoordinatesoratthecurrentpointercoordinates.
NoteIfthePositionpropertyofthecommandbarisnotsettomsoBarPopup,thismethodfails.
expression.ShowPopup(x,y)
expressionRequired.AnexpressionthatreturnsaCommandBarobject.
xOptionalVariant.Thex-coordinateforthelocationoftheshortcutmenu.Ifthisargumentisomitted,thecurrentx-coordinateofthepointerisused.
yOptionalVariant.They-coordinateforthelocationoftheshortcutmenu.Ifthisargumentisomitted,thecurrenty-coordinateofthepointerisused.
Example
Thisexamplecreatesashortcutmenucontainingtwocontrols.TheShowPopupmethodisusedtomaketheshortcutmenuvisible.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarPopup,Temporary:=False)
WithmyBar
.Controls.AddType:=msoControlButton,Id:=3
.Controls.AddType:=msoControlComboBox
EndWith
myBar.ShowPopup
StartWizardMethodSomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
StartstheOfficeAssistantandreturnsaLongvaluethatidentifiesthesession.YoushouldusethismethodonlytoruntheOfficeAssistantinacustomwizard.
NoteThenumberreturnedbyStartWizardmethodisusedbytheActivateWizardandEndWizardmethods.
expression.StartWizard(On,Callback,PrivateX,Animation,CustomTeaser,Top,Left,Bottom,Right)
expressionRequired.AnexpressionthatreturnsanAssistantobject.
OnRequiredBoolean.TruetodisplaytheOfficedecisionballoon.TheOfficedecisionballoonaskstheuserwhetherheorshewantshelpwiththeactivecustomwizard.Itisn'tnecessarytousetheVisiblepropertytodisplaytheOfficeAssistantifyouspecifyTrueforthisargument.
CallbackRequiredString.ThenameofthecallbackprocedurerunbytheOfficedecisionballoonandthebranchballoon.ThebranchballoonallowstheusertochoosebetweencustomHelpyou'veprovidedforthewizardandstandardOfficeHelp.
PrivateXRequiredLong.Anumberthatidentifiestheballoonthatinitiatedthecallbackprocedure.
AnimationOptionalVariant.TheanimationtheOfficeAssistantperformswhenthismethodisused.ThedefaultvalueismsoAnimationGetWizardy.
CustomTeaserOptionalVariant.FalsetodisplaytheOfficedecisionballoon.
Top,Left,Bottom,RightOptionalVariant.Thepositionofthecorners(inpointsandrelativetothescreen)ofthecustomwizardformtheOfficeAssistantwillavoidwhentheOfficeAssistantappears.
Remarks
Unlikecallbackproceduresusedbystandardmodelessballoons,thecallbackprocedurecalledbythemodelessdecisionandbranchballoonsdisplayedduringanOfficeAssistantwizardsessiontakesonlytwoarguments:anMsoWizardMsgTypeconstant,andtheuniquevaluespecifiedbythePrivateXargumentoftheStartWizardmethod.
Iftheuserclickstheleftbuttoninthedecisionorbranchballoon,theconstantmsoWizardMsgShowHelpispassedtothefirstargumentofthecallbackprocedure.Iftheuserclickstherightbutton,theconstantmsoWizardLocalStateOffispassed.(TheotherMsoWizardMsgTypeconstantsarepassedbytheActivateWizardmethodifyou’vespecifiedmsoWizardActResumeormsoWizardActSuspendfortheActargument.)InthecaseofmsoWizardMsgShowHelp,thecallbackprocedureshoulddisplaytheappropriateballoonforthecurrentpanelofthecustomwizard.AndinthecaseofmsoWizardLocalStateOff,thecallbackprocedureshouldhidethevisibleballoon.
Example
ThisexamplestartstheOfficeAssistantaspartofaprocesstoprovideinformationwhileacustomwizardisrunning.ThevariablelHelpForWizissettothereturnvalueoftheStartWizardmethod,whichisLong.
lHelpForWiz=Assistant.StartWizard(On:=True,_
Callback:="myCallback",PrivateX:=23)
UnsuspendMethodResumessynchronizationbetweenthelocalcopyandtheservercopyofashareddocument.
expression.Unsuspend()
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
UsetheUnsuspendmethodtoresumedocumentsynchronizationwhentheStatuspropertyreturnsmsoSyncStatusSuspended.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Example
Thefollowingexampleresumesdocumentsynchronizationifithasbeensuspended.
DimobjSyncAsOffice.Sync
SetobjSync=ActiveDocument.Sync
IfobjSync.Status=msoSyncStatusSuspendedThen
objSync.Unsuspend
MsgBox"Synchronizationresumed.",_
vbInformation+vbOKOnly,"SyncStatus"
EndIf
SetobjSync=Nothing
UpdateMethodUpdatesthecontentsoftheCOMAddInscollectionfromthelistofadd-insstoredintheWindowsregistry.
expression.Update
expressionTheCOMAddInscollection.
Remarks
BeforeyoucanuseagivenCOMadd-ininaMicrosoftOfficeapplication,thatadd-inmustberegisteredintheWindowsregistryasaCOMcomponentwithacorrespondingComponentCategoryID.NormallythesetupprogramforaCOMadd-inwilladdthenecessaryentriestotheregistry.
Example
ThefollowingexampleupdatesthecontentsoftheCOMAddInscollectionfromthelistofadd-insstoredintheWindowsregistry.
Application.COMAddIns.Update
ActionControlPropertyReturnstheCommandBarControlobjectwhoseOnActionpropertyissettotherunningprocedure.Iftherunningprocedurewasnotinitiatedbyacommandbarcontrol,thispropertyreturnsNothing.Read-only.
Example
Thisexamplecreatesacommandbarnamed“Custom”,addsthreebuttonstoit,andthenusestheActionControlpropertyandtheTagpropertytodeterminewhichcommandbarbuttonwaslastclicked.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
SetbuttonOne=myBar.Controls.Add(Type:=msoControlButton)
WithbuttonOne
.FaceId=133
.Tag="RightArrow"
.OnAction="whichButton"
EndWith
SetbuttonTwo=myBar.Controls.Add(Type:=msoControlButton)
WithbuttonTwo
.FaceId=134
.Tag="UpArrow"
.OnAction="whichButton"
EndWith
SetbuttonThree=myBar.Controls.Add(Type:=msoControlButton)
WithbuttonThree
.FaceId=135
.Tag="DownArrow"
.OnAction="whichButton"
EndWith
myBar.Visible=True
ThewhichButtonsubroutinerespondstotheOnActionmethodanddetermineswhichcommandbarbuttonwaslastclicked.
SubwhichButton()
SelectCaseCommandBars.ActionControl.Tag
Case"RightArrow"
MsgBox("RightArrowbuttonclicked.")
Case"UpArrow"
MsgBox("UpArrowbuttonclicked.")
Case"DownArrow"
MsgBox("DownArrowbuttonclicked.")
EndSelect
EndSub
ActiveMenuBarPropertyReturnsaCommandBarobjectthatrepresentstheactivemenubarinthecontainerapplication.Read-only.
Example
Thisexampleaddsatemporarypop-upcontrolnamed"Custom"totheendoftheactivemenubar,andaddsacontrolnamed"Import"tothepop-upcontrol.
SetmyMenuBar=CommandBars.ActiveMenuBar
SetnewMenu=myMenuBar.Controls.Add(Type:=msoControlPopup,Temporary:=True)
newMenu.Caption="Custom"
Setctrl1=newMenu.CommandBar.Controls_
.Add(Type:=msoControlButton,Id:=1)
Withctrl1
.Caption="Import"
.TooltipText="Import"
.Style=msoButtonCaption
EndWith
AdaptiveMenuPropertyTrueifanindividualmenuisenabledtouseadaptivemenus.Read/writeBoolean.
NoteThispropertywillnotfunctionwhiletheAdaptiveMenuspropertyissettoFalse.
Thispropertychecksorunchecksthecheckboxcontrolfortheoptiontoshowanindividualmenuasfullorpersonalized.OnlyrecentlyusedsubmenusshowupinamenuifthispropertyissettoTrue.AllsubmenusshowupifthispropertyissettoFalse.
Example
ThisexamplesetstheAdaptiveMenupropertytoFalsefortheFilemenuintheMicrosoftOfficeapplicationyou’reworkingin.
CommandBars("File").AdaptiveMenu=False
NoteThispropertyworksonlywhenthespecifiedcommandbar("File"inthiscase)istheMSOBarTypePopup.ARunTimeErrorisreturnedwhenthispropertyisusedwithanothercommandbartypesuchasMSOBarTypeMenuBar.
AdaptiveMenusPropertyTrueifadaptivemenusareenabledforallapplicationsinMicrosoftOffice.Read/writeBoolean.
ThispropertychecksorunchecksthecheckboxcontrolfortheoptiontoshowmenusinMicrosoftOfficeasfullorpersonalized.Thiscontrolissetinanyapplicationbydoingthefollowing:
1. OntheToolsmenu,selectCustomize.
2. SelecttheOptionstab.
3. TheAlwaysshowfullmenusoptionislocatedinthePersonalizedMenusandToolbarssection.
Example
ThisexamplesetsthreeoptionsforallcommandbarsinMicrosoftOffice,includingcustomcommandbarsandthecontrolsonthem.
WithCommandBars
.LargeButtons=True
.DisplayFonts=True
.AdaptiveMenus=True
EndWith
AllowMultiSelectPropertyTrueiftheuserisallowedtoselectmultiplefilesfromafiledialogbox.Read/writeBoolean.
expression.AllowMultiSelect
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
ThispropertyhasnoeffectonFolderPickerdialogboxesorSaveAsdialogboxesbecauseusersshouldneverbeabletoselectmultiplefilesinthesetypesoffiledialogboxes.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Allowtheselectionofmultiplefiles.
.AllowMultiSelect=True
'UsetheShowmethodtodisplaythefilepickerdialogandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
Next
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
ShowAll
AnimationPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsananimationactionfortheOfficeAssistant.WhenthispropertyisappliedtotheAssistantobjectandtheAssistantsupportsthespecifiedanimation,theAssistantisanimatedimmediately(iftheAssistantisvisibleandenabled).WhenthispropertyisappliedtotheBalloonobject,theAssistantisanimatedonlywhiletheballoonisdisplayed.Read/writeMsoAnimationType.
MsoAnimationTypecanbeoneoftheseMsoAnimationTypeconstants.msoAnimationAppearmsoAnimationBeginSpeakingmsoAnimationCharacterSuccessMajormsoAnimationCheckingSomethingmsoAnimationDisappearmsoAnimationEmptyTrashmsoAnimationGestureDownmsoAnimationGestureLeftmsoAnimationGestureRightmsoAnimationGestureUpmsoAnimationGetArtsymsoAnimationGetAttentionMajormsoAnimationGetAttentionMinormsoAnimationGetTechymsoAnimationGetWizardymsoAnimationGoodbyemsoAnimationGreetingmsoAnimationIdlemsoAnimationListensToComputermsoAnimationLookDownmsoAnimationLookDownLeftmsoAnimationLookDownRight
msoAnimationLookLeftmsoAnimationLookRightmsoAnimationLookUpmsoAnimationLookUpLeftmsoAnimationLookUpRightmsoAnimationPrintingmsoAnimationRestPosemsoAnimationSavingmsoAnimationSearchingmsoAnimationSendingMailmsoAnimationThinkingmsoAnimationWorkingAtSomethingmsoAnimationWritingNotingSomething
Remarks
“Clippit”isthedefaultAssistant,andmsoAnimationIdleisthedefaultanimationtypefortheAssistant.
DependingontheselectedAssistant,settingtheAnimationpropertymayormaynotresultinanobviousanimation.However,allMsoAnimationTypeconstantsarevalidforallAssistants.Notethatdifferentconstantsmayproducethesameanimation.
ThefollowingMsoAnimationTypeconstantsrepresentanimationsthatrepeatthespecifiedactionuntiltheAssistantisdismissedoruntiltheAnimationpropertyisresetwithanotheranimation:
msoAnimationCheckingSomething
msoAnimationGetTechy
msoAnimationListensToComputer
msoAnimationSearching
msoAnimationThinking
msoAnimationWorkingAtSomething
msoAnimationWritingNotingSomething
Example
ThisexampledisplaystheOfficeAssistantinaspecificlocationanditsetsseveraloptionsbeforemakingtheAssistantvisible.
WithAssistant
.On=True
.Visible=True
.MovexLeft:=400,yTop:=300
.MoveWhenInTheWay=True
.TipOfDay=True
.Animation=msoAnimationGreeting
EndWith
ApplicationPropertyReturnsanApplicationobjectthatrepresentsthecontainerapplicationfortheobject(youcanusethispropertywithanAutomationobjecttoreturnthatobject'scontainerapplication).
expression.Application
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexamplereturnsthenameoftheapplicationinwhichthecommandbarnamedStandardwascreatedanddisplaysthisresultinamessagebox.
SetAppobj=CommandBars("Standard").Application
MsgBoxAppobj
AssignedToPropertyReturnsorsetstheSharedWorkspaceMembertowhomthetaskisassigned.Read/writeString.
expression.AssignedTo()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTaskobject.
Remarks
TheoptionalAssignedTopropertyofasharedworkspacetaskreturnsthedisplaynameorNamepropertyoftheSharedWorkspaceMembertowhomthetaskisassigned.However,usetheDomainNamepropertyofaSharedWorkspaceMembertosetthisproperty.
Example
ThefollowingexampleusestheAssignedTopropertytoreassignallsharedworkspacetaskscurrentlyassignedtooneworkspacemembertoadifferentmember,usingthemember'sNamewhenreadingthepropertyandDomainNamewhenwritinganewvalueforit.
DimswsTaskAsOffice.SharedWorkspaceTask
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
Debug.PrintswsTask.AssignedTo
IfswsTask.AssignedTo="NewEmployee"Then
swsTask.AssignedTo="MYCOMPANY\user123"
EndIf
Next
SetswsTask=Nothing
AssistWithAlertsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantballoondeliversapplicationalertswhentheOfficeAssistantisvisible.Read/writeBoolean.
Remarks
TheAssistWithAlertspropertycorrespondstotheDisplayalertsoptionunderUsetheOfficeAssistantontheOptionstabintheOfficeAssistantdialogbox.
IfthispropertyissettoFalse,theapplicationdisplaysalertsindialogboxes.
Example
ThisexamplesetstheOfficeAssistanttobedisplayedwheneveranapplicationalertisgenerated.
WithAssistant
.On=True
.Visible=True
.AssistWithHelp=True
.AssistWithAlerts=True
.Animation=msoAnimationGetAttentionMajor
EndWith
AssistWithHelpPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantappearswhentheuserpressestheF1keytodisplayHelp.Read/writeBoolean.
NoteThispropertyisobsoletebuthasbeenretainedforcompatibilitywithcodewritteninpreviousversionsofMicrosoftOffice.
Remarks
TheAssistWithHelppropertycorrespondstotheRespondtoF1keyoptionunderUsetheOfficeAssistantontheOptionstabintheOfficeAssistantdialogbox.
IfthispropertyissettoFalse,theHelpTopicsdialogboxappearsinsteadoftheOfficeAssistant.
Example
ThisexampledisplaystheOfficeAssistantwhenevertheuserpressestheF1keytodisplayHelp.
WithAssistant
.On=True
.Visible=True
.AssistWithHelp=True
.AssistWithAlerts=True
.Animation=msoAnimationGetAttentionMajor
EndWith
AssistWithWizardsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantprovidesonlineHelpwithwizards.Read/writeBoolean.
Remarks
TheAssistWithWizardspropertycorrespondstotheHelpwithwizardsoptionunderUsetheOfficeAssistantontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexamplesetstheOfficeAssistanttoprovideHelpinformationaboutwizards.
Assistant.AssistWithWizards=True
AttachCertificatePropertyTrueifthedigitalcertificatethatcorrespondstothespecifiedSignatureobjectisattachedtothedocument.Read/writeBoolean.
expression.AttachCertificate
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandcallthisfunction.Thefunctionwilltesttomakesurethatthedigitalsignaturethattheuserselectswillnotexpireinlessthan12months.Ifitwillexpire,thecertificateisn'tattached.
FunctionAddSignature()AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
sig.AttachCertificate=True
'TesttomakesurethatthenewSignatureobject
'doesn'texpiretoosoon.Thisexpressioncalculates
'thenumberofmonthsuntiltheSignatureobjectexpires.
IfDateDiff("m",sig.SignDate,sig.ExpireDate)<12Then
MsgBox"Thiscertificatewillexpireinlessthan1year."&vbCrLf&_
"Pleaseuseanewercertificate."
AddSignature=False
sig.Delete
Else
AddSignature=True
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
ShowAll
BalloonErrorPropertyReturnsavaluethatindicatesthelastrecordedballoonerror.Read-onlyMsoBalloonErrorType.
MsoBalloonErrorTypecanbeoneoftheseMsoBalloonErrorTypeconstants.msoBalloonErrorBadCharacterTheballooncontainsanASCIIcontrolcharacterotherthanCRorLFandlessthan32.msoBalloonErrorBadPictureRefTheballooncontainsagraphicthatcouldn'tbedisplayedbecausethefiledoesn'texistorbecausethegraphicisn'tavalid.BMPor.WMFfile.msoBalloonErrorBadReferenceTheballooncontainsanunrecognizedorunsupportedreference.msoBalloonErrorButtonlessModalTheballoonyouattemptedtodisplayismodal,butitcontainsnobuttons.Theballoonwon'tbeshownbecauseitcan'tbedismissed.msoBalloonErrorButtonModelessTheballoonyouattemptedtodisplayismodeless,containsbuttons,andhasnoprocedureassignedtotheCallbackproperty.Theballoonwon'tbeshownbecauseacallbackprocedureisrequiredformodelessballoons.msoBalloonErrorCharNotTopmostForModalThemodalballoonwasrequestedbyanapplicationthatisn’ttheactiveapplication.MicrosoftOfficerendersballoonsfortheactive(topmost)applicationonly.msoBalloonErrorCOMFailureTheballooncouldnotbedisplayedbecauseofaCOMfailure.msoBalloonErrorNoneNoerrorwasencountered.msoBalloonErrorOtherTheballoonwon'tappearbecausesomeothererroroccurred,suchasanothermodalballoonisalreadyactive.msoBalloonErrorOutOfMemoryTheballoonwon'tappearbecausethereisinsufficientmemory.msoBalloonErrorTooBigTheballoonistoobigtoappearonthescreen.msoBalloonErrorTooManyControlsTheballooncontainsmorethantwentycontrols(checkboxesorlabels).
Example
Thisexamplecreatesaballoonthatgeneratesanerror.Theerrorisgeneratedbecausetheballooniscreatedwithoutawaytodismissit:thebuttontypeissettomsoButtonSetNoneandthedefaultballoonmodeismsoModeModal,resultinginabuttonless,modalballoon.Notethatthere'snowaytodismissabuttonlessmodalballoon.
WithApplication.Assistant
With.NewBalloon
.Heading="Thiswillnevershow."
.Text="Imagineaballoonhere."
.Button=msoButtonSetNone
.Show
EndWith
.Visible=True
If.BalloonError=msoBalloonErrorButtonlessModalThen
MsgBox"Youneedabuttontodismisstheballoon."
EndIf
EndWith
ShowAll
BalloonTypePropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsthetypeofballoontheOfficeAssistantuses.WhenyoucreateaBalloonobject,thispropertyisinitiallysettomsoBalloonTypeButtons.Read/writeMsoBalloonType.
MsoBalloonTypecanbeoneoftheseMsoBalloonTypeconstants.msoBalloonTypeBulletsmsoBalloonTypeButtonsmsoBalloonTypeNumbers
Example
Thisexamplecreatesaninstructionballoonthatexplainshowtoselectaprinter.Theballoonismodeless,sotheusercanfollowtheinstructionsintheballoonandkeeptheballoonvisibleasheorsheworks.
Setbln=Assistant.NewBalloon
Withbln
.Heading="InstructionsforChoosingaPrinter."
.Text="ClickOKwhenyou'vechosenaprinter."
.Labels(1).Text="FromtheFilemenu,choosePrint."
.Labels(2).Text="ClickSetup."
.Labels(3).Text="Selectthenameoftheprinter."
.BalloonType=msoBalloonTypeNumbers
.Mode=msoModeModeless
.Callback="ProcessPrinter"
.Button=msoButtonSetOK
.Show
EndWith
ShowAll
BeginGroupPropertyTrueifthespecifiedcommandbarcontrolappearsatthebeginningofagroupofcontrolsonthecommandbar.Read/writeBoolean.
Example
Thisexamplebeginsanewgroupwiththelastcontrolontheactivemenubar.
SetmyMenuBar=CommandBars.ActiveMenuBar
SetlastMenu=myMenuBar_
.Controls(myMenuBar.Controls.Count)
lastMenu.BeginGroup=True
ShowAll
BuiltInPropertyTrueifthespecifiedcommandbarorcommandbarcontrolisabuilt-incommandbarorcontrolofthecontainerapplication.Falseifit'sacustomcommandbarorcontrol,orifit'sabuilt-incontrolwhoseOnActionpropertyhasbeenset.Read-onlyBoolean.
Example
Thisexampledeletesallcustomcommandbarsthataren'tvisible.
foundFlag=False
deletedBars=0
ForEachbarInCommandBars
If(bar.BuiltIn=False)And(bar.Visible=False)Then
bar.Delete
foundFlag=True
deletedBars=deletedBars+1
EndIf
Next
IfNotfoundFlagThen
MsgBox"Nocommandbarshavebeendeleted."
Else
MsgBoxdeletedBars&"customcommandbar(s)deleted."
EndIf
ShowAll
BuiltInFacePropertyTrueifthefaceofacommandbarbuttoncontrolisitsoriginalbuilt-inface.ThispropertycanonlybesettoTrue,whichwillresetthefacetothebuilt-inface.Read/writeBoolean.
Example
Thisexampledetermineswhetherthefaceofthefirstcontrolonthecommandbarnamed"Custom"isitsbuilt-inbuttonface.Ifitis,theexamplecopiesthebuttonfacetotheClipboard.
SetmyControl=CommandBars("MyCustomBar").Controls(1)
WithmyControl
If.BuiltInFace=TrueThen.CopyFace
EndWith
ShowAll
ButtonPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsthetypeofbuttondisplayedatthebottomoftheOfficeAssistantballoon.WhenyoucreateaBalloonobject,thispropertyisinitiallysettomsoButtonSetOK.Read/writeMsoButtonSetType.
MsoButtonSetTypecanbeoneoftheseMsoButtonSetTypeconstants.msoButtonSetAbortRetryIgnoremsoButtonSetBackClosemsoButtonSetBackNextClosemsoButtonSetBackNextSnoozemsoButtonSetCancelmsoButtonSetNextClosemsoButtonSetNonemsoButtonSetOKmsoButtonSetOkCancelmsoButtonSetRetryCancelmsoButtonSetSearchClosemsoButtonSetTipsOptionsClosemsoButtonSetYesAllNoCancelmsoButtonSetYesNomsoButtonSetYesNoCancel
Example
Thisexampledisplaysaballoonthatcontainsaheading,text,threeregionchoices,andtwocommandbuttons(OKandCancel).
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
.Show
EndWith
ButtonNamePropertySetsorreturnsaStringrepresentingthetextthatisdisplayedontheactionbuttonofafiledialogbox.Bydefault,thispropertyissettothestandardtextforthetypeoffiledialogbox.Forexample,inthecaseoftheOpendialogbox,thepropertyissetto"Open"bydefault.Thisstringislimitedtofifty-onecharacters.Read/write.
expression.ButtonName
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Changethetextontheactionbutton.
.ButtonName="Archive"
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachStringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
CallbackPropertySetsthenameoftheproceduretorunfromamodelessballoon.Read/writeString.
Remarks
TheprocedureyouspecifyfortheCallbackpropertymustbewrittentoreceiveeithertwoorthreearguments,dependingonwhatyouusethepropertywith.IfyouusetheCallbackpropertywithawizard,youmustwritetheproceduretoreceivetwoarguments:alongintegerthatrepresentsthemsoBalloonButtonTypevalueofthebuttonthattheuserclicked,andalongintegerthatuniquelyidentifiestheballoon.IfyouusetheCallbackpropertywithamodelessballoon,youmustwritetheproceduretoreceivethreearguments:theBalloonobjectthatcalledtheprocedure;alongintegerthatrepresentsthemsoBalloonButtonTypevalueofthebuttontheuserclicked;andalongintegerthatuniquelyidentifiestheballoonthatcalledtheprocedure,asdenotedintheballoon’sPrivateproperty.
ThecallbackproceduremustcontainatleastoneconditionunderwhichtheClosemethodisappliedtotheBalloonobjectthatispassedtoit;otherwise,themodelessballooncannotbedismissed.
Ifyouspecifyaprocedurethatisstoredinaseparateclassmodule,youmustincludethemodulenameinthevalueassignedtotheCallbackproperty(forexample,"Sheet1.MyCallback).
Example
Thisexampledisplaysaballoonthatcontainsabuttonforeachofthreeprinters.Whenevertheuserclicksoneofthesebuttons,theProcessPrintercallbackprocedureisrunandtheballoonisclosed.
SubselectPrinter()
Setbln=Assistant.NewBalloon
Withbln
.Heading="SelectaPrinter."
.Labels(1).Text="NetworkPrinter"
.Labels(2).Text="LocalPrinter"
.Labels(3).Text="LocalColorPrinter"
.BalloonType=msoBalloonTypeButtons
.Mode=msoModeModeless
.Callback="ProcessPrinter"
.Show
EndWith
EndSub
SubProcessPrinter(blnAsBalloon,lbtnAsLong,_
lPrivAsLong)
Assistant.Animation=msoAnimationPrinting
SelectCaselbtn
Case-1
'Insertnetworkprinter-specificcode.
Case-2
'Insertlocalprinter-specificcode.
Case-3
'Insertcolorprinter-specificcode.
EndSelect
bln.Close
EndSub
ShowAll
CaptionPropertyReturnsorsetsthecaptiontextforacommandbarcontrol.Read/writeString.
NoteAcontrol'scaptionisalsodisplayedasitsdefaultScreenTip.
Example
Thisexampleaddsacommandbarcontrolwithaspellingcheckerbuttonfacetoacustomcommandbar,andthenitsetsthecaptionto"Spellingchecker."
SetmyBar=CommandBars.Add(Name:="Custom",_
Position:=msoBarTop,Temporary:=True)
myBar.Visible=True
SetmyControl=myBar.Controls_
.Add(Type:=msoControlButton,Id:=2)
WithmyControl
.DescriptionText="Startsthespellingchecker"
.Caption="Spellingchecker"
EndWith
CheckboxesPropertyReturnstheBalloonCheckboxescollectionthatrepresentsallthecheckboxescontainedinthespecifiedballoon.Read-only.
Forinformationaboutreturningasinglememberofacollection,seeReturninganObjectfromaCollection.
Example
Thisexamplecreatesaballoonwithaheading,text,andthreeregionchoices.WhentheuserclicksOKintheballoon,datafortheselectedregionorregionsisprinted.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selecttheregion(s)youwanttoprint."
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
If.Show=msoBalloonButtonOKThen
dataPrinted=0
Fori=1To3
If.CheckBoxes(i).Checked=TrueThen
'Codetoprintregiondata.
dataPrinted=dataPrinted+1
MsgBox"Region"&i&"dataprinted."
EndIf
Next
IfdataPrinted=0ThenMsgBox"Nodataprinted."
EndIf
EndWith
CheckedPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueifthespecifiedcheckboxintheOfficeAssistantballoonischecked.Read/writeBoolean.
Example
Thisexamplecreatesaballoonwithaheading,text,andthreeregionchoices.WhentheuserclicksOKintheballoon,datafortheselectedregionorregionsisprinted.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selecttheregion(s)youwanttoprint."
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
If.Show=msoBalloonButtonOKThen
dataPrinted=0
Fori=1To3
If.CheckBoxes(i).Checked=TrueThen
'Codetoprintregiondata.
dataPrinted=dataPrinted+1
MsgBox"Region"&i&"dataprinted."
EndIf
Next
IfdataPrinted=0ThenMsgBox"Nodataprinted."
EndIf
EndWith
ColumnPropertyReturnsorsetsaStringthatrepresentsthenameofthefieldinthemailmergedatasourcetouseinthefilter.Read/write.
expression.Column
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
ColumnsPropertyReturnsanODSOColumnsobjectthatrepresentsthefieldsinadatasource.
expression.Columns
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
Thefollowingexampledisplaysthefieldnamesinthedatasourceattachedtotheactivepublication.
SubShowFieldNames()
DimappOfficeAsOfficeDataSourceObject
DimintCountAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Columns
ForintCount=1To.Count
MsgBox"FieldName:"&.Item(intCount).Name
Next
EndWith
EndSub
ShowAll
CommandBarPropertyReturnsaCommandBarobjectthatrepresentsthemenudisplayedbythespecifiedpop-upcontrol.Read-only.
Example
ThisexamplesetsthevariablefourthLeveltothefourthcontrolonthecommandbarnamed"Drawing."
SetfourthLevel=CommandBars("Drawing")_
.Controls(1).CommandBar.Controls(4)
CommandBarsPropertyReturnsaCommandBarscollection.
expression.CommandBars
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplereturntheCommandBarscollectionfromtheMsoEnvelopeobjectinMicrosoftWord.
DimcbarsAsCommandBars
Setcbars=Application.ActiveDocument.MailEnvelope.Commandbars
CommentsPropertyReturnsanyoptionalcommentsassociatedwiththespecifiedversionoftheshareddocument.Read-onlyString.
expression.Comments()
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
Remarks
Ausercanattachversioncommentsthroughthedocumentlibraryuserinterfacewhencheckinginadocumentthatwaspreviouslycheckedout.
Example
Thefollowingexamplelistscommentsandotherpropertiesforeachversionofashareddocument.
DimdlvVersionsAsOffice.DocumentLibraryVersions
DimdlvVersionAsOffice.DocumentLibraryVersion
DimstrVersionInfoAsString
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
strVersionInfo="Thisdocumenthas"&_
dlvVersions.Count&"versions:"&vbCrLf
ForEachdlvVersionIndlvVersions
strVersionInfo=strVersionInfo&_
"-Version#:"&dlvVersion.Index&vbCrLf&_
"-Modifiedby:"&dlvVersion.ModifiedBy&vbCrLf&_
"-Modifiedon:"&dlvVersion.Modified&vbCrLf&_
"-Comments:"&dlvVersion.Comments&vbCrLf
Next
Else
strVersionInfo="Versioningnotenabledforthisdocument."
EndIf
MsgBoxstrVersionInfo,vbInformation+vbOKOnly,"VersionInformation"
SetdlvVersion=Nothing
SetdlvVersions=Nothing
CompareToPropertyReturnsorsetsaStringthatrepresentsthetexttocompareinthequeryfiltercriterion.Read/write.
expression.CompareTo
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
ShowAll
ComparisonPropertyReturnsorsetsanMsoFilterComparisonconstantthatrepresentshowtocomparetheColumnandCompareToproperties.Read/write.
MsoFilterComparisoncanbeoneoftheseMsoFilterComparisonconstants.msoFilterComparisonContainsmsoFilterComparisonEqualmsoFilterComparisonGreaterThanmsoFilterComparisonGreaterThanEqualmsoFilterComparisonIsBlankmsoFilterComparisonIsNotBlankmsoFilterComparisonLessThanmsoFilterComparisonLessThanEqualmsoFilterComparisonNotContainsmsoFilterComparisonNotEqual
expression.Comparison
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
ShowAll
ConditionPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Returnstheconditionofthespecifiedsearchcriteria.Read-onlyMsoCondition.
MsoConditioncanbeoneoftheseMsoConditionconstants.msoConditionAnyNumberBetweenmsoConditionAnytimemsoConditionAnytimeBetweenmsoConditionAtLeastmsoConditionAtMostmsoConditionBeginsWithmsoConditionDoesNotEqualmsoConditionEndsWithmsoConditionEqualsmsoConditionFileTypeAllFilesmsoConditionFileTypeBindersmsoConditionFileTypeCalendarItemmsoConditionFileTypeContactItemmsoConditionFileTypeDatabasesmsoConditionFileTypeDataConnectionFilesmsoConditionFileTypeDesignerFilesmsoConditionFileTypeEPaperFilesmsoConditionFileTypeExcelWorkbooksmsoConditionFileTypeJournalItemmsoConditionFileTypeMailItemmsoConditionFileTypeNoteItemmsoConditionFileTypeOfficeFilesmsoConditionFileTypeOutlookItemsmsoConditionFileTypePhotoDrawFilesmsoConditionFileTypePowerPointPresentations
msoConditionFileTypeProjectFilesmsoConditionFileTypePublisherFilesmsoConditionFileTypeTaskItemmsoConditionFileTypeTemplatesmsoConditionFileTypeVisioDocumentsmsoConditionFileTypeWebPagesmsoConditionFileTypeWordDocumentsmsoConditionFreeTextmsoConditionIncludesmsoConditionIncludesFormsOfmsoConditionIncludesNearEachOthermsoConditionIncludesPhrasemsoConditionInTheLastmsoConditionInTheNextmsoConditionIsExactlymsoConditionIsNomsoConditionIsNotmsoConditionIsYesmsoConditionLastMonthmsoConditionLastWeekmsoConditionLessThanmsoConditionMoreThanmsoConditionNextMonthmsoConditionNextWeekmsoConditionOnmsoConditionOnOrAftermsoConditionOnOrBeforemsoConditionThisMonthmsoConditionThisWeekmsoConditionTodaymsoConditionTomorrowmsoConditionYesterday
Example
Thisexamplereturnstheconditionvalueforsearchcriteriaforthefirstpropertytest.
WithApplication.FileSearch.PropertyTests(1)
MsgBox"Theconditionyou'vesetis:"&.Condition
EndWith
ShowAll
ConjunctionPropertyReturnsorsetsanMsoFilterConjunctionconstantthatrepresentshowafiltercriterionrelatestootherfiltercriteriaintheODSOFiltersobject.Read/write.
MsoFilterConjunctioncanbeoneoftheseMsoFilterConjunctionconstants.msoFilterConjunctionAndmsoFilterConjunctionOr
expression.Conjunction
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplechangesanexistingfiltertoremovefromthemailmergeallrecordsthatdonothaveaRegionfieldequalto"WA".
SubSetQueryCriterion()
DimappOfficeAsOffice.OfficeDataSourceObject
DimintItemAsInteger
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
WithappOffice.Filters
ForintItem=1To.Count
With.Item(intItem)
If.Column="Region"Then
.Comparison=msoFilterComparisonNotEqual
.CompareTo="WA"
If.Conjunction="Or"Then.Conjunction="And"
EndIf
EndWith
NextintItem
EndWith
EndSub
ConnectPropertyReturnsorsetsthestateoftheconnectionforthespecifiedCOMAddInobject.Read/writeBoolean.
Remarks
TheConnectpropertyreturnsTrueiftheadd-inisactive;itreturnsFalseiftheadd-inisinactive.Anactiveadd-inisregisteredandconnected;aninactiveadd-inisregisteredbutnotcurrentlyconnected.
Example
ThefollowingexampledisplaysamessageboxthatindicateswhetherCOMadd-inoneisregisteredandcurrentlyconnected.
IfApplication.COMAddIns(1).ConnectThen
MsgBox"Theadd-inisconnected."
Else
MsgBox"Theadd-inisnotconnected."
EndIf
ConnectedPropertyReturnsaBooleanvaluethatindicateswhetherornottheactivedocumentiscurrentlysavedinandconnectedtoasharedworkspace.Read-onlyBoolean.
expression.Connected
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
UsetheDisconnectmethodoftheSharedWorkspaceobjecttodisconnectthelocalcopyoftheactivedocumentfromthesharedworkspace.UsetheRemoveDocumentmethodtoremovethedocumentfromthesharedworkspace.
Example
ThefollowingexamplecheckstheConnectedpropertytodeterminewhethertheactivedocumentisalreadysavedinasharedworkspace.
IfActiveWorkbook.SharedWorkspace.ConnectedThen
MsgBox"Thisdocumentisalreadysavedinasharedworkspace."
EndIf
ShowAll
ConnectorPropertyReturnstheconnectorbetweentwosimilarpropertytestvalues.ThedefaultvalueismsoConnectorAnd.Read-onlyMsoConnector.
MsoConnectorcanbeoneoftheseMsoConnectorconstants.msoConnectorAndmsoConnectorOr
Remarks
Aconnectorspecifieswhethertwosimilarsearchcriteriawillbecombinedtoformonepropertytest(aswithmsoConnectorAnd)ortreatedindependently(aswithmsoConnectorOr).
Example
Thisexampledisplaysamessagethatdescribeshowthesearchcriteriawillbeevaluatedinafilesearch.
WithApplication.FileSearch.PropertyTests(1)
If.Connector=msoConnectorAndThen
MsgBox"Allsearchcriteriawillbecombined."
Else
MsgBox"Criteriawillbetreatedindependently"
EndIf
EndWith
ConnectStringPropertyReturnsorsetsaStringthatrepresentstheconnectiontothespecifiedmailmergedatasource.Read/write.
expression.ConnectString
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexamplechecksiftheconnectionstringcontainsthecharactersODSOOutlookanddisplaysamessageaccordingly.
SubVerifyCorrectDataSource()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
IfInStr(appOffice.ConnectString,"ODSOOutlook")>0Then
MsgBox"YourOutlookaddressbookisusedasthedatasource."
Else
MsgBox"YourOutlookaddressbookisnotusedasthedatasource."
EndIf
EndSub
ShowAll
ContextPropertyReturnsorsetsastringthatdetermineswhereacommandbarwillbesaved.Thestringisdefinedandinterpretedbytheapplication.Read/writeString.
Remarks
YoucansettheContextpropertyonlyforcustomcommandbars.Thispropertywillfailiftheapplicationdoesn'trecognizethecontextstring,oriftheapplicationdoesn'tsupportchangingcontextstringsprogrammatically.
Example
Thisexampledisplaysamessageboxcontainingthecontextstringforthecommandbarnamed“Custom”.ThisexampleworksinMicrosoftWordandotherapplicationsthatsupporttheContextproperty.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlButton,ID:=2
.Visible=True
EndWith
MsgBox(myBar.Context)
ControlsPropertyReturnsaCommandBarControlsobjectthatrepresentsallthecontrolsonacommandbarorpop-upcontrol.Read-only.
Forinformationaboutreturningasinglememberofacollection,seeReturninganObjectfromaCollection.
Example
Thisexampleaddsacomboboxcontroltothecommandbarnamed"Custom"andfillsthelistwithtwoitems.Theexamplealsosetsthenumberoflineitems,thewidthofthecombobox,andanemptydefaultforthecombobox.
SetmyControl=CommandBars("Custom").Controls_
.Add(Type:=msoControlComboBox,Before:=1)
WithmyControl
.AddItemText:="FirstItem",Index:=1
.AddItemText:="SecondItem",Index:=2
.DropDownLines=3
.DropDownWidth=75
.ListHeaderCount=0
EndWith
CountPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsaLongindicatingthenumberofitemsinthespecifiedcollection.Read/writeLongfortheBalloonCheckboxesandBalloonLabelsobjects;read-onlyLongforallotherobjectsintheAppliesTolist.
expression.Count
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Remarks
FortheCommandBarscollection,thecountincludesonlymenubars,toolbars,andshortcutmenus.
ForthePermissionobject,theCountpropertyreturns0(zero)ifpermissionsarenotenabledontheactivedocument.Whenpermissionsareenabled,theCountpropertyalwaysreturnsatleast1,representingthepermissionsofthedocumentauthor.
FortheScriptscollection,thecountreturnedisthenumberofscriptblocksinthespecifieddocument.InMicrosoftWord,Scripts.Countreturnsthetotalnumberofinlineandfloatingscriptanchorscombined.
Example
ThisexampleusestheCountpropertytodisplaythenumberofcommandbarsintheCommandBarscollection.
MsgBox"Thereare"&CommandBars.Count&_
"barsintheCommandBarscollection."
ThisexampleusestheCountpropertytodisplaythenumberofcheckboxesintheOfficeAssistantballoon.
WithAssistant.NewBalloon
.CheckBoxes(1).Text="FirstChoice"
.CheckBoxes(2).Text="SecondChoice"
.Text="Youhavethefollowing"_
&.CheckBoxes.Count&"choices."
.Show
EndWith
Thisexampledisplaysthenumberofcustomdocumentpropertiesintheactivedocument.
MsgBox("Thereare"&_
ActiveDocument.CustomDocumentProperties.Count&_
"customdocumentpropertiesinthe"&_
"activedocument.")
CreatedByPropertyReturnsthefriendlynameofthememberwhocreatedthesharedworkspaceobject.Read-onlyString.
expression.CreatedBy
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheCreatedBypropertyreturnsthefriendlynamestoredintheNamepropertyoftheDWSMemberobject.
TheSharedWorkspaceFolderandSharedWorkspaceMemberobjectsdonothaveaCreatedByproperty.
Example
Thefollowingexamplelistsfilesinthesharedworkspacethatwerecreatedbyusersotherthanthecreatoroftheworkspace.
DimswsFileAsOffice.SharedWorkspaceFile
DimswsOwnerAsOffice.SharedWorkspaceMember
DimstrMemberFilesAsString
SetswsOwner=ActiveWorkbook.SharedWorkspace.Members(1)
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
IfswsFile.CreatedBy<>swsOwner.NameThen
strMemberFiles=strMemberFiles&swsFile.URL&vbCrLf
EndIf
Next
MsgBox"Thesefileswerecreatedbyotherusers:"&_
vbCrLf&strMemberFiles,_
vbInformation+vbOKOnly,"FilesCreatedbyOtherUsers"
SetswsOwner=Nothing
SetswsFile=Nothing
CreatedDatePropertyReturnsthedateandtimewhenthesharedworkspaceobjectwascreated.Read-onlyVariant.
expression.CreatedDate
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheSharedWorkspaceFolderandSharedWorkspaceMemberobjectsdonothaveaCreatedDateproperty.
Example
Thefollowingexamplereturnsalistofsharedworkspacefileswhosedateandtimecreatedisearlierthantoday.
DimswsFileAsOffice.SharedWorkspaceFile
DimdtmMidnightAsDate
DimdtmFileDateAsDate
DimstrOlderFilesAsString
dtmMidnight=CDate(FormatDateTime(Now,vbShortDate)&"12:00:00am")
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
dtmFileDate=swsFile.CreatedDate
IfdtmFileDate<dtmMidnightThen
strOlderFiles=strOlderFiles&swsFile.URL&vbCrLf
EndIf
Next
MsgBox"Filesolderthantoday:"&vbCrLf&strOlderFiles,_
vbInformation+vbOKOnly,"OlderFiles"
SetswsFile=Nothing
CreatorPropertyReturnsa32-bitintegerthatindicatestheapplicationinwhichthespecifiedobjectwascreated.Forexample,iftheobjectwascreatedinMicrosoftWord,thispropertyreturns1297307460,whichrepresentsthestring"MSWD";inMicrosoftExcel,thispropertyreturns1480803660.ThisvaluecanalsoberepresentedbytheconstantwdCreatorCodeinWord,orxlCreatorCodeinExcel.Read-onlyLong.
expression.Creator
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Remarks
TheCreatorpropertywasprimarilydesignedtobeusedontheMacintosh,whereeachapplicationhasafour-charactercreatorcode.Forexample,MicrosoftWordhasthecreatorcodeMSWD.Foradditionalinformationaboutthisproperty,consultthelanguagereferenceHelpincludedwithMicrosoftOfficeMacintoshEdition.
TheCreatorpropertyalwaysreturnsthenumericidentifierfortheactiveapplication,justastheApplicationpropertyalwaysreturnsthenameoftheactiveapplicatininstringform.UsedtheCreatedBypropertyoftheSharedWorkspaceFile,SharedWorkspaceFolder,SharedWorkspaceLink,andSharedWorkspaceTaskobjectstoreturnthenameoftheindividualwhocreatedthoseobjects.UsedocumentpropertiestoreturninformationabouttheauthorsofOfficedocuments.
Example
ThisexampledisplaysamessageaboutthecreatorofmyObject.
SetmyObject=ActiveDocument
IfmyObject.Creator=wdCreatorCodeThen
MsgBox"ThisisaMicrosoftWordobject"
Else
MsgBox"ThisisnotaMicrosoftWordobject"
EndIf
DataSourcePropertyReturnsorsetsaStringthatrepresentsthenameoftheattacheddatasource.Read/write.
expression.DataSource
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
Thefollowingexamplesetsthenameofthedatasourceifthenameisblank.
SubSetAndReturnDataSourceName()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
WithappOffice
.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
If.DataSource=""Then
.DataSource="Northwind"
MsgBox.DataSource
EndIf
EndWith
EndSub
ShowAll
DescriptionPropertyDescriptionpropertyasitappliestotheCOMAddInobject.
ReturnsorsetsadescriptiveStringvalueforthespecifiedCOMAddinobject.Read/write.
expression.Description
expressionRequired.AnexpressionthatreturnsaCOMAddinobject.
DescriptionpropertyasitappliestotheFileDialogFilterobject.
ReturnsthedescriptionofeachFilterobjectasaStringvalue.Thedescriptionisthetextthatisdisplayedinthefiledialogbox.Read-only.
expression.Description
expressionRequired.AnexpressionthatreturnsaFileDialogFilterobject.
DescriptionpropertyasitappliestotheSharedWorkspaceLinkandSharedWorkspaceTaskobjects.
ReturnsorsetsadescriptiveStringvalueforthespecifiedSharedWorkspaceLinkorSharedWorkspaceTaskobject.Read/write.
expression.Description
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceLinkorSharedWorkspaceTaskobject.
Remarks
TheDescriptionpropertyisoptionalwhenanewsharedworkspacelinkortaskiscreated,andmaybeempty.
Example
AsitappliestotheCOMAddInobject.
ThefollowingexampledisplaysthedescriptiontextoftheMicrosoftAccessibilityCOMadd-infordrawing.
MsgBox"Thedescriptionofthis"&_
"COMAddInis"""&Application.COMAddIns._
Item("msodraa9.ShapeSelect")._
Description&"""
AsitappliestotheFileDialogFilterobject.
ThefollowingexampleiteratesthroughthedefaultfiltersoftheSaveAsdialogboxanddisplaysthedescriptionofeachfilterthatincludesaMicrosoftExcelfile.TheExtensionspropertyisusedtofindtheappropriatefilterobjects.
SubMain()
'DeclareavariableasaFileDialogFilterscollection.
DimfdfsAsFileDialogFilters
'DeclareavariableasaFileDialogFilterobject.
DimfdfAsFileDialogFilter
'SettheFileDialogFilterscollectionvariableto
'theFileDialogFilterscollectionoftheSaveAsdialogbox.
Setfdfs=Application.FileDialog(msoFileDialogSaveAs).Filters
'Iteratethroughthedescriptionandextensionsofeach
'defaultfilterintheSaveAsdialogbox.
ForEachfdfInfdfs
'Displaythedescriptionoffiltersthatinclude
'MicrosoftExcelfiles.
IfInStr(1,fdf.Extensions,"xls",vbTextCompare)>0Then
MsgBox"Filterdescription:"&fdf.Description
EndIf
Nextfdf
EndSub
ShowAll
DescriptionTextPropertyReturnsorsetsthedescriptionforacommandbarcontrol.Thedescriptionisnotdisplayedtotheuser,butitcanbeusefulfordocumentingthebehaviorofthecontrolforotherdevelopers.Read/writeString.
Remarks
ThispropertyisusedforBalloonHelpontheMacintosh.
Example
Thisexampleaddsacontroltoacustomcommandbar,includingadescriptionofthecontrol'sbehavior.
SetmyBar=CommandBars.Add("Custom",msoBarTop,,True)
myBar.Visible=True
SetmyControl=myBar.Controls_
.Add(Type:=msoControlButton,ID:=_
CommandBars("Standard").Controls("Paste").ID)
WithmyControl
.DescriptionText="PastesthecontentsoftheClipboard"
.Caption="Paste"
EndWith
ShowAll
DialogTypePropertyReturnsanMsoFileDialogTypeconstantrepresentingthetypeoffiledialogboxthattheFileDialogobjectissettodisplay.Read-only.
MsoFileDialogTypecanbeoneoftheseMsoFileDialogTypeconstants.msoFileDialogFilePickermsoFileDialogFolderPickermsoFileDialogOpenmsoFileDialogSaveAs
expression.DialogType
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampletakesaFileDialogobjectofanunknowntypeandrunstheExecutemethodifitisaSaveAsdialogboxoranOpendialogbox.
SubDisplayAndExecuteFileDialog(ByReffdAsFileDialog)
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'UsetheDialogTypepropertytodeterminewhetherto
'usetheExecutemethod.
SelectCase.DialogType
CasemsoFileDialogOpen,msoFileDialogSaveAs:.Execute
'Donothingotherwise.
CaseElse
EndSelect
'IftheuserpressesCancel...
Else
EndIf
EndWith
EndSub
DisableAskAQuestionDropdownPropertyTrueiftheAnswerWizarddropdownmenuisenabled.Read/writeBoolean.
expression.DisableAskAQuestionDropdown
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampletogglestheDisableAskAQuestionDropdownproperty.
SubToggleQuestionDropdown()
WithApplication.CommandBars
If.DisableAskAQuestionDropdown=TrueThen
.DisableAskAQuestionDropdown=False
Else
.DisableAskAQuestionDropdown=True
EndIf
EndWith
EndSub
DisableCustomizePropertyTrueiftoolbarcustomizationisdisabled.Read/writeBoolean.
expression.DisableCustomize
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampletogglestheDisableCustomizeproperty.
SubToggleCustomize()
WithApplication.CommandBars
If.DisableCustomize=TrueThen
.DisableCustomize=False
Else
.DisableCustomize=True
EndIf
EndWith
EndSub
DisplayFontsPropertyTrueifthefontnamesintheFontboxaredisplayedintheiractualfonts.Read/writeBoolean.
Example
ThisexamplesetsthreeoptionsforallcommandbarsinMicrosoftOffice,includingcustomcommandbarsandthecontrolsonthem.
WithCommandBars
.LargeButtons=True
.DisplayFonts=True
.AdaptiveMenus=True
EndWith
ShowAll
DisplayKeysInTooltipsPropertyTrueifshortcutkeysaredisplayedintheToolTipsforeachcommandbarcontrol.Read/writeBoolean.
Remarks
TodisplayshortcutkeysinToolTips,youmustalsosettheDisplayTooltipspropertytoTrue.
Example
ThisexamplesetsoptionsforallcommandbarsinMicrosoftOffice.
WithCommandBars
.LargeButtons=True
.DisplayTooltips=True
.DisplayKeysInTooltips=True
.MenuAnimationStyle=msoMenuAnimationUnfold
EndWith
ShowAll
DisplayTooltipsPropertyTrueifScreenTipsaredisplayedwhenevertheuserpositionsthepointerovercommandbarcontrols.Read/writeBoolean.
Remarks
SettingtheDisplayTooltipspropertyinacontainerapplicationimmediatelyaffectseverycommandbarineveryrunningMicrosoftOfficeapplication,andineveryOfficeapplicationopenedafterthepropertyisset.
Example
ThisexampledisplayslargecontrolsandToolTipsonallcommandbars.
SetallBars=CommandBars
allBars.LargeButtons=True
allBars.DisplayTooltips=True
DocumentAuthorPropertyReturnsorsetsthenameinemailformoftheauthoroftheactivedocument.Read/writeString.
expression.DocumentAuthor
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
TheDocumentAuthorpropertyreturnsorsetstheauthoroftheactivedocument.Theauthoralwayshasnon-expiringownerrightstothedocument,whetherownerpermissionisgrantedexplicitly(throughaUserPermissionobject)ornot.
TheDocumentAuthorpropertycanonlybechangedtoadifferentaccountthathasbeencertifiedthroughthepermissionsuserinterfacetoopenrestrictedcontentonthelocalmachine.Inmostcases,userswhohaveasingleWindowsaccountcanonlychoosebetweentheirWindowsandtheirPassportidentities.
Iftheuser'sMicrosoftWindowsandPassportidentitiesusethesameemailaddress,thenusetheformatpassport:someone@example.comtospecifythePassportidentityastheDocumentAuthorproperty.
Example
Thefollowingexampledisplaysinformationaboutthepermissionssettingsoftheactivedocument,includingthedocumentauthor.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsareenabledonthisdocument."&vbCrLf
strIRMInfo=strIRMInfo&"Viewintrustedbrowser:"&_
irmPermission.EnableTrustedBrowser&vbCrLf&_
"Documentauthor:"&irmPermission.DocumentAuthor&vbCrLf&_
"Userswithrights:"&irmPermission.Count&vbCrLf&_
"Cachelicenseslocally:"&irmPermission.StoreLicenses&vbCrLf&_
"RequestpermissionURL:"&irmPermission.RequestPermissionURL&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."
EndIf
Else
strIRMInfo="PermissionsareNOTenabledonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
DomainNamePropertyReturnsthedomainandusernameofthespecifiedSharedWorkspaceMemberintheformatdomain\user.Read-onlyString.
expression.DomainName
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceMemberobject.
Example
ThefollowingexampleextractsthedomainnamefromtheDomainNamepropertyofeachsharedworkspacememberandlistsmemberswhobelongtothe"MyCompany"domain.
DimswsMemberAsOffice.SharedWorkspaceMember
DimstrDomainAsString
DimstrMemberListAsString
ForEachswsMemberInActiveWorkbook.SharedWorkspace.Members
strDomain=UCase(Left(swsMember.DomainName,_
InStr(swsMember.DomainName,"\")-1))
IfstrDomain="MYCOMPANY"Then
strMemberList=strMemberList&swsMember.Name&vbCrLf
EndIf
Next
MsgBoxstrMemberList,vbInformation+vbOKOnly,_
"MembersintheMYCOMPANYDomain"
SetswsMember=Nothing
ShowAll
DropDownLinesPropertyReturnsorsetsthenumberoflinesinacommandbarcomboboxcontrol.Thecomboboxcontrolmustbeacustomcontrolanditmustbeadrop-downlistboxoracombobox.Read/writeLong.
NoteAnerroroccursifyouattempttosetthispropertyforacomboboxcontrolthat'saneditboxorabuilt-incomboboxcontrol.
Remarks
Ifthispropertyissetto0(zero),thenumberoflinesinthecontrolwillbebasedonthenumberofitemsinthelist.
Example
Thisexampleaddsacomboboxcontrolcontainingtwoitemstothecommandbarnamed"Custom".Theexamplealsosetsthenumberoflineitems,thewidthofthecombobox,andanemptydefaultforthecombobox.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls.Add(Type:=msoControlComboBox,Id:=1)
WithmyControl
.AddItemText:="FirstItem",Index:=1
.AddItem"SecondItem",2
.DropDownLines=3
.DropDownWidth=75
.ListHeaderCount=0
EndWith
ShowAll
DropDownWidthPropertyReturnsorsetsthewidth(inpixels)ofthelistforthespecifiedcommandbarcomboboxcontrol.Read/writeLong.
NoteAnerroroccursifyouattempttosetthispropertyforabuilt-incontrol.
Remarks
Ifthispropertyissetto-1,thewidthofthelistisbasedonthelengthofthelongestiteminthecomboboxlist.Ifthispropertyissetto0,thewidthofthelistisbasedonthewidthofthecontrol.
Example
Thisexampleaddsacomboboxcontrolcontainingtwoitemstothecommandbarnamed"Custom".Theexamplealsosetsthenumberoflineitems,thewidthofthecombobox,andanemptydefaultforthecombobox.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls.Add(Type:=msoControlComboBox,Id:=1)
WithmyControl
.AddItem"FirstItem",1
.AddItem"SecondItem",2
.DropDownLines=3
.DropDownWidth=75
.ListHeaderCount=0
EndWith
DueDatePropertyReturnsorsetstheoptionalduedateandtimeofaSharedWorkspaceTaskobject.Read/writeVariant.
expression.DueDate()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTaskobject.
Example
ThefollowingexamplesetstheDueDateofalltasksinasharedworkspaceto12:00noononDecember31,2005anduploadsthesechangestotheserverusingtheSavemethod.
DimswsTaskAsOffice.SharedWorkspaceTask
ConstdtmNewDueDateAsDate=#12/31/200512:00:00PM#
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
swsTask.DueDate=dtmNewDueDate
swsTask.Save
Next
SetswsTask=Nothing
EmailPropertyReturnstheemailnameofthespecifiedSharedWorkspaceMemberintheformatuser@domain.com.Read-onlyString.
expression.Email
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceMemberobject.
Example
ThefollowingexampleextractstheemaildomainnamefromtheEmailpropertyofeachsharedworkspacememberandlistsmemberswhohaveemailaddressesatthe"mycompany.com"domain.
DimswsMemberAsOffice.SharedWorkspaceMember
DimstrEmailDomainAsString
DimstrMemberListAsString
ForEachswsMemberInActiveWorkbook.SharedWorkspace.Members
strEmailDomain=LCase(Right(swsMember.Email,_
Len(swsMember.Email)-InStr(swsMember.Email,"@")))
IfstrEmailDomain="mycompany.com"Then
strMemberList=strMemberList&swsMember.Email&vbCrLf
EndIf
Next
MsgBoxstrMemberList,vbInformation+vbOKOnly,_
"Memberswithmycompany.comEmail"
SetswsMember=Nothing
ShowAll
EnabledPropertyEnabledpropertyasitappliestotheCommandBar,
CommandBarButton,CommandBarComboBox,andCommandBarControlobjects.
Trueifthespecifiedcommandbarorcommandbarcontrolisenabled.Read/writeBoolean.
Remarks
Forcommandbars,settingthispropertytoTruecausesthenameofthecommandbartoappearinthelistofavailablecommandbars.
Forbuilt-incontrols,ifyousettheEnabledpropertytoTrue,theapplicationdeterminesitsstate,butsettingittoFalsewillforceittobedisabled.
EnabledpropertyasitappliestothePermissionobject.
ReturnsorsetsaBooleanvaluethatindicateswhetherpermissionsareenabledontheactivedocument.Read/writeBoolean.
expression.Enabled
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
UsetheEnabledpropertytodeterminewhetherpermissionsarerestrictedontheactivedocument,andtoenableordisablepermissions.SetEnabledtoFalsetodisablepermissionsandtoremoveallusers,otherthanthedocumentauthor,andtheirpermissions.
Whenpermissionsaredisabled,theCountpropertyofthePermissionobjectreturns0(zero);however,whenpermissionsarere-enabled,thepermissionsofthedocumentauthorremainintact.
Example
AsitappliestotheCommandBar,CommandBarButton,CommandBarComboBox,andCommandBarControlobjects.
Thisexampleadjuststhecommandbarsaccordingtotheuserlevelspecifiedbyuser.Ifuseris"Level1,"thecommandbarnamed"VBCustomBar"isdisplayed.Ifuserisanyothervalue,thebuilt-inVisualBasiccommandbarisresettoitsdefaultstateandthecommandbarnamed"VBCustomBar"isdisabled.
SetmyBar=CommandBars_
.Add(Name:="VBCustomBar",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlButton,ID:=2
.Visible=True
EndWith
Ifuser="Level1"Then
myBar.Visible=True
Else
CommandBars("VisualBasic").Reset
myBar.Enabled=False
EndIf
Thisexampleaddstwocommandbarbuttonstothecommandbarnamed“Custom”.Thefirstcontrolisdisabled;thesecondcontrolisenabledbydefault.
SetmyBar=CommandBars("Custom")
WithmyBar
.Controls.AddType:=msoControlButton,Id:=3
.Controls(1).Enabled=False
.Controls.AddType:=msoControlButton,Id:=3
EndWith
myBar.Visible=True
AsitappliestothePermissionobject.
ThefollowingexamplecheckstheEnabledpropertytodeterminewhetherpermissionsarerestrictedontheactivedocument.
DimirmPermissionAsOffice.Permission
SetirmPermission=ActiveWorkbook.Permission
SelectCaseirmPermission.Enabled
CaseTrue
MsgBox"Permissionsarerestrictedonthisdocument."&vbCrLf&_
"Thereare"&irmPermission.Count&"userswithrights.",_
vbInformation+vbOKOnly,"IRMInformation"
CaseFalse
MsgBox"PermissionsareNOTrestrictedonthisdocument.",_
vbInformation+vbOKOnly,"IRMInformation"
EndSelect
SetirmPermission=Nothing
EnableTrustedBrowserPropertyReturnsorsetstheoptionthatallowsausertoviewadocumentwithrestrictedpermissionsinawebbrowseriftheuserdoesnothavetheappropriateclientapplicationinstalled.Read/writeBoolean.DefaultisFalse.
expression.EnableTrustedBrowser
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
TheEnableTrustedBrowserproperty,whenTrue,allowsauserwhotriestoopenaOfficeWord2003documentwithrestrictedpermissions,forexample,butwhodoesnothavetheOfficeWord2003applicationinstalled,toviewthedocumentinMicrosoftInternetExploreroranotherbrowserthatsupportsthisfunctionality.ThispropertycorrespondstothecheckboxAllowuserswithearlierversionsofOfficetoreadwithbrowserssupportingInformationRightsManagement.(Increasesfilesize.)intheuserinterface.
Example
Thefollowingexamplereportswhethertheactivedocumenthasrestrictedpermissionsand,ifso,whethertheEnableTrustedBrowserpropertyisalsoenabled.
DimirmPermissionAsOffice.Permission
SetirmPermission=ActiveWorkbook.Permission
SelectCaseirmPermission.Enabled
CaseTrue
SelectCaseirmPermission.EnableTrustedBrowser
CaseTrue
MsgBox"Permissionsarerestrictedonthisdocument."&_
vbCrLf&"Viewingintrustedbrowserisalsoenabled.",_
vbInformation+vbOKOnly,"IRMInformation"
CaseFalse
MsgBox"Permissionsarerestrictedonthisdocument."&_
vbCrLf&"However,viewingintrustedbrowserisdisabled.",_
vbInformation+vbOKOnly,"IRMInformation"
EndSelect
CaseFalse
MsgBox"PermissionsareNOTrestrictedonthisdocument.",_
vbInformation+vbOKOnly,"IRMInformation"
EndSelect
SetirmPermission=Nothing
ShowAll
ErrorTypePropertyReturnsaconstantwhichindicatesthetypeofthemostrecentdocumentsynchronizationerror.Read-onlyMsoSyncErrorType.
MsoSyncErrorTypecanbeoneofthefollowingmsoSyncErrorTypeconstants.msoSyncErrorNone(0)msoSyncErrorUnauthorizedUser(1)msoSyncErrorCouldNotConnect(2)msoSyncErrorOutOfSpace(3)msoSyncErrorFileNotFound(4)msoSyncErrorFileTooLarge(5)msoSyncErrorFileInUse(6)msoSyncErrorVirusUpload(7)msoSyncErrorVirusDownload(8)msoSyncErrorUnknownUpload(9)msoSyncErrorUnknownDownload(10)msoSyncErrorCouldNotOpen(11)msoSyncErrorCouldNotUpdate(12)msoSyncErrorCouldNotCompare(13)msoSyncErrorCouldNotResolve(14)msoSyncErrorNoNetwork(15)msoSyncErrorUnknown(16)
expression.ErrorType()
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
UsetheErrorTypepropertytodeterminethetypeofthemostrecentdocumentsynchronizationerror.
Notalldocumentsynchronizationproblemsraisetrappablerun-timeerrors.AfterperforminganoperationusingtheSyncobject,it'sagoodideatochecktheStatusproperty;iftheStatuspropertyismsoSyncStatusError,checktheErrorTypepropertyforadditionalinformationonthetypeoferrorthathasoccurred.
Example
ThefollowingexamplecheckstheStatusproperty,thenusestheErrorTypepropertytodisplaythetypeofsyncerrorthathasoccurred.
DimobjSyncAsOffice.Sync
DimstrErrorAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status=msoSyncStatusErrorThen
strError="Asyncerrorhasoccurred."&vbCrLf&_
"Errortype:"&objSync.ErrorType
Else
strError="Nosyncerrorhasoccurred."
EndIf
MsgBoxstrError,vbInformation+vbOKOnly,"ErrorInformation"
SetobjSync=Nothing
ExpirationDatePropertyReturnsorsetstheoptionalexpirationdateofthepermissionsontheactivedocumentassignedtotheuserassociatedwiththespecifiedUserPermissionobject.Read/writeVariant.
expression.ExpirationDate
expressionRequired.AnexpressionthatreturnsaUserPermissionobject.
Remarks
TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.TheExpirationDatepropertyreturnsorsetstheoptionalexpirationdateofthespecifiedUserPermissionobjectusingthelocaltimezone.
Example
Thefollowingexampleextendstheexpirationdateoftheseconduser'spermissionsontheactivedocumentbyanadditionalsixmonths.
DimirmPermissionAsOffice.Permission
DimirmUserPermAsOffice.UserPermission
DimdtmOldDateAsDate,dtmNewDateAsDate
SetirmPermission=ActiveWorkbook.Permission
SetirmUserPerm=irmPermission.Item(2)
dtmOldDate=irmUserPerm.ExpirationDate
dtmNewDate=DateAdd("m",6,dtmOldDate)
irmUserPerm.ExpirationDate=dtmNewDate
MsgBox"Permissionsexpirationfor"&irmUserPerm.UserId&vbCrLf&_
"extendedfrom"&dtmOldDate&"to"&dtmNewDate,_
vbInformation+vbOKOnly,"IRMInformation"
SetirmUserPerm=Nothing
SetirmPermission=Nothing
ExpireDatePropertyReturnsaVariantrepresentingthedateonwhichthedigitalsignaturethatcorrespondstotheSignatureobjectwillexpire.Read-only.
expression.ExpireDate
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandcallthisfunction.Thefunctionwilltesttomakesurethatthedigitalsignaturethattheuserselectswillnotexpireinlessthan12months.Ifitwillexpire,thecertificateisn'tattached.
FunctionAddSignature()AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TesttomakesurethatthenewSignatureobject
'doesn'texpiretoosoon.Thisexpressioncalculates
'thenumberofmonthsuntiltheSignatureobjectexpires.
IfDateDiff("m",sig.SignDate,sig.ExpireDate)<12Then
MsgBox"ThisCertificatewillexpireinlessthan1year."&vbCrLf&_
"Pleaseuseanewercertificate."
AddSignature=False
sig.Delete
Else
AddSignature=True
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
ExtendedPropertySetsorreturnsattributesaddedtothe<SCRIPT>tag,withtheexceptionoftheLANGUAGEandIDattributes.Read/writeString.
Remarks
Attributesareseparatedbyspaces,thesameasinHTML.YoucannotpasstheLANGUAGEattributeortheIDattributebyusingtheExtendedproperty.
TheMicrosoftOfficehostapplicationdoesn’tprovideanymeansofcheckingthesyntaxofpassedattributes.
IfyoupasstheLANGUAGEattributeintheExtendedproperty,the<SCRIPT>tagreceivestwolanguagesettings,whichcausesaconflict.
IfyoupassanIDattributeintheExtendedpropertyandnoIDhasbeensetthrougheithertheIDparameteroftheAddmethodortheIdpropertyoftheScriptobject,theIDisexportedcorrectly.
Example
ThisexamplecheckstheExtendedpropertytoensurethatnoadditionalattributeshavebeenaddedtothefirstscriptinworksheetoneintheactiveworkbook.
IfActiveWorkbook.Worksheets(1).Scripts(1).Extended_
<>""Then
MsgBox"Thisscriptcontainsextendedattributes."
EndIf
ExtensionsPropertyReturnsaStringvaluecontainingtheextensionsthatdeterminewhichfilesaredisplayedinafiledialogboxforeachFilterobject.Read-only.
expression.Extensions
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampleiteratesthroughthedefaultfiltersoftheSaveAsdialogboxanddisplaysthedescriptionofeachfilterthatincludesaMicrosoftExcelfile.TheExtensionspropertyisusedtofindtheappropriatefilterobjects.
SubMain()
'DeclareavariableasaFileDialogFilterscollection.
DimfdfsAsFileDialogFilters
'DeclareavariableasaFileDialogFilterobject.
DimfdfAsFileDialogFilter
'SettheFileDialogFilterscollectionvariableto
'theFileDialogFilterscollectionoftheSaveAsdialogbox.
Setfdfs=Application.FileDialog(msoFileDialogSaveAs).Filters
'Iteratethroughthedescriptionandextensionsofeach
'defaultfilterintheSaveAsdialogbox.
ForEachfdfInfdfs
'Displaythedescriptionoffiltersthatinclude
'MicrosoftExcelfiles.
IfInStr(1,fdf.Extensions,"xls",vbTextCompare)>0Then
MsgBox"Descriptionoffilter:"&fdf.Description
EndIf
Nextfdf
EndSub
ShowAll
FaceIdPropertyReturnsorsetstheIdnumberforthefaceofacommandbarbuttoncontrol.Read/writeLong.
Remarks
TheFaceIdpropertydictatesthelook,notthefunction,ofacommandbarbutton.TheIdpropertyoftheCommandBarControlobjectdeterminesthefunctionofthebutton.
ThevalueoftheFaceIdpropertyforacommandbarbuttonwithacustomfaceis0(zero).
Example
Thisexampleaddsacommandbarbuttontoacustomcommandbar.ClickingthisbuttonisequivalenttoclickingtheOpencommandontheFilemenubecausetheIDnumberis23,yetthebuttonhasthesamebuttonfaceasthebuilt-inChartingbutton.
SetnewBar=CommandBars.Add(Name:="Custom2",_
Position:=msoBarTop,Temporary:=True)
newBar.Visible=True
Setcon=newBar.Controls.Add(Type:=msoControlButton,Id:=23)
con.FaceId=17
FeatureTipsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantprovidesinformationaboutusingapplicationfeaturesmoreeffectively.Read/writeBoolean.
Remarks
TheFeatureTipspropertycorrespondstotheUsingfeaturesmoreeffectivelycheckboxontheOptionstabintheAssistantdialogbox.
Example
ThisexampleallowstheOfficeAssistanttoprovideinformationaboutusingapplicationfeaturesmoreeffectively.
Assistant.FeatureTips=True
FileNamePropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Assistantobject:ReturnsorsetsthepathandfilenamefortheactiveOfficeAssistant.Read/writeString.
FileSearchobject:Returnsorsetsthenameofthefiletolookforduringafilesearch.Thenameofthefilemayincludethe*(asterisk)or?(questionmark)wildcards.Usethequestionmarkwildcardtomatchanysinglecharacter.Forexample,typegr?ytomatchboth"gray"and"grey."Usetheasteriskwildcardtomatchanynumberofcharacters.Forexample,type*.txttofindallfilesthathavethe.TXTextension.Read/writeString.
expression.FileName
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexamplesearchesforallfileslocatedintheMyDocumentsfolderthatbeginwith"cmd"andhaveafilenameextension.Theexampledisplaysthenameandlocationofeachfoundfile.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.FileName="cmd*.*"
If.Execute>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
ShowAll
FilesPropertyFilespropertyasitappliestotheAnswerWizardobject.
ReturnsanAnswerWizardFilescollectionthatrepresentsthelistoffilesavailabletothecurrentAnswerWizard.Read-only.
Forinformationaboutreturningasinglememberofacollection,seeReturninganObjectfromaCollection.
FilespropertyasitappliestotheSharedWorkspaceobject.
ReturnsaSharedWorkspaceFilescollectionthatrepresentsthelistoffilesstoredinthedocumentlibraryassociatedwiththecurrentsharedworkspace.Read-only.
Example
AsitappliestotheAnswerWizardobject.
ThisexampleresetsthefilelistforthecurrentAnswerWizardandthendisplaysboththefilecountandthefilenamesinamessagebox.
DimcustomAnswerWizardAsAnswerWizard
DimstrFileListAsString
DimintCounterAsInteger
DimintNumFilesAsInteger
SetcustomAnswerWizard=Application.AnswerWizard
intCounter=1
customAnswerWizard.ResetFileList
strFileList=""
intNumFiles=customAnswerWizard.Files.Count
ForintCounter=1To(intNumFiles)
strFileList=strFileList&_
customAnswerWizard.Files.Item(intCounter)&Chr(13)
Next
MsgBox"Thereare"&customAnswerWizard.Files.Count&_
"filesavaialblethroughthisAnswerWizard:"&_
Chr(13)&strFileList
AsitappliestotheSharedWorkspaceobject.
Thefollowingexampleliststhefilessavedinthecurrentsharedworkspace.
DimswsFilesAsOffice.SharedWorkspaceFiles
SetswsFiles=ActiveWorkbook.SharedWorkspace.Files
MsgBox"Thereare"&swsFiles.Count&_
"file(s)
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsFiles=Nothing
ShowAll
FileTypePropertyReturnsorsetsthetypeoffiletolookforduringafilesearch.Read/write
MsoFileType.
MsoFileTypecanbeoneoftheseMsoFileTypeconstants.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeCustommsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFilesmsoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItemmsoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPagesmsoFileTypeWordDocuments
expression.FileType
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheconstantmsoFileTypeOfficeFilesincludesallfileswithanyofthefollowingextensions:*.doc,*.xls,*.ppt,*.pps,*.obd,*.mdb,*.mpd,*.dot,*.xlt,*.pot,*.obt,*.htm,or*.html.
Example
ThisexamplesearchesforallBinderfileslocatedintheMyDocumentsfolder.Theexampledisplaysamessageboxthatcontainsthenameandlocationofeachfilethat’sfound.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.FileType=msoFileTypeBinders
If.Execute>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"Binderfile(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"TherewerenoBinderfilesfound."
EndIf
EndWith
FileTypesPropertyReturnsaFileTypescollection.
expression.FileTypes
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplesearchesforallHTMLandMicrosoftExcelfilesontheC:\drive.
SubSearchForFiles()
'Declareavariabletoactasagenericcounter.
DimlngCountAsLong
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'Clearalltheparametersoftheprevioussearches.
'Thismethoddoesn'tcleartheLookInpropertyor
'theSearchFolderscollection.
.NewSearch
'SettingtheFileTypepropertyclearsthe
'FileTypescollectionandsetsthefirst
'iteminthecollectiontothefiletype
'definedbytheFileTypeproperty.
.FileType=msoFileTypeWebPages
'AddaseconditemtotheFileTypescollection.
.FileTypes.AddmsoFileTypeExcelWorkbooks
'DisplaythenumberofFileTypesobjectsinthecollection.
MsgBox"Youareabouttosearchfor"&.FileTypes.Count&_
"filetypes."
'SetupthesearchtolookinallsubfoldersontheC:\drive.
.LookIn="C:\"
.SearchSubFolders=True
'Executethesearchandtesttoseeifanyfiles
'werefound.
If.Execute<>0Then
'Displaythenumberoffilesfound.
MsgBox"Filesfound:"&.FoundFiles.Count
'Loopthroughthelistoffoundfilesand
'displaythepathofeachoneinamessagebox.
ForlngCount=1To.FoundFiles.Count
IfMsgBox(.FoundFiles.Item(lngCount),vbOKCancel,_
"Foundfiles")=vbCancelThen
'Breakoutoftheloop
lngCount=.FoundFiles.Count
EndIf
NextlngCount
Else
MsgBox"Nofilesfound."
EndIf
EndWith
EndSub
FilterIndexPropertyReturnsorsetsaLongindicatingthedefaultfilefilterofafiledialogbox.Thedefaultfilterdetermineswhichtypesoffilesaredisplayedwhenthefiledialogboxisfirstopened.Read/write.
expression.FilterIndex
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
Ifyoutrytosetthispropertytoanumbergreaterthanthenumberoffilters,thelastavailablefilterwillbeselected.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.Thisexamplealsodemonstrateshowtoaddanewfilefilterandhowtomakeitthedefaultfilter.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'AddafilterthatincludesGIFandJPEGimagesandmakeittheseconditeminthelist.
.Filters.Add"Images","*.gif;*.jpg;*.jpeg",2
'Setstheinitialfilefiltertonumber2.
.FilterIndex=2
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
FiltersPropertyReturnsaFileDialogFilterscollection.
expression.Filters
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.Theexamplealsoaddsanewfilefiltercalled"Images."
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialog.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'AddafilterthatincludesGIFandJPEGimagesandmakeitthefirstiteminthelist.
.Filters.Add"Images","*.gif;*.jpg;*.jpeg",1
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
FixedWidthFontPropertySetsorreturnsthefixed-widthfontsettinginthehostapplication.Read/writeString.
Remarks
WhenyousettheFixedWidthFontproperty,thehostapplicationdoesnotcheckthevalueforvalidity.
Example
Thisexamplesetsthefixed-widthfontandfixed-widthfontsizefortheEnglish/WesternEuropean/OtherLatinScriptcharactersetintheactiveapplication.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFont="System"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFontSize=12
FixedWidthFontSizePropertySetsorreturnsthefixed-widthfontsizesettinginthehostapplication,inpoints.Read/writeSingle.
Remarks
WhenyousettheFixedWidthFontSizeproperty,thehostapplicationdoesnotcheckthevalueforvalidity.Ifyouenteraninvalidvalue,suchasanonnumber,thehostapplicationsetsthesizeto0points.Youcanenterhalf-pointsizes;ifyouenterotherfractionalpointsizes,theyareroundedupordowntothenearesthalf-point.
Example
Thisexamplesetsthefixed-widthfontandfixed-widthfontsizefortheEnglish/WesternEuropean/OtherLatinScriptcharactersetintheactiveapplication.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFont="System"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFontSize=12
FolderNamePropertyReturnsthenameofasubfolderwithinthemaindocumentlibraryfolderofasharedworkspace.Read-onlyString.
expression.FolderName()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFolderobject.
Remarks
TheFolderNamepropertyreturnsthesubfoldernameintheformatparentfolder/subfolder.Forexample,ifthesharedworkspacecontainsafoldernamed"SupportingDocuments",theFolderNamepropertyreturnsSharedDocuments/SupportingDocuments.
Example
Thefollowingexampledisplaysthenumberofsubfoldersinthesharedworkspaceandtheirnames.
DimswsFolderAsOffice.SharedWorkspaceFolder
DimstrFolderInfoAsString
strFolderInfo="Thesharedworkspacecontains"&_
ActiveWorkbook.SharedWorkspace.Folders.Count&"folder(s)."&vbCrLf
IfActiveWorkbook.SharedWorkspace.Folders.Count>0Then
ForEachswsFolderInActiveWorkbook.SharedWorkspace.Folders
strFolderInfo=strFolderInfo&swsFolder.FolderName&vbCrLf
Next
EndIf
MsgBoxstrFolderInfo,vbInformation+vbOKOnly,_
"FoldersinSharedWorkspace"
SetswsFolder=Nothing
FoldersPropertyReturnsaSharedWorkspaceFolderscollectionthatrepresentsthelistofsubfoldersinthedocumentlibraryassociatedwiththecurrentsharedworkspace.Read-only.
expression.Folders()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
TheSharedWorkspaceFolderscollectiondoesnotincludetherootdocumentlibraryfolderitself,whichbydefaultisnamed"SharedDocuments".
Example
Thefollowingexampleliststhesubfoldersinthecurrentsharedworkspace.
DimswsFoldersAsOffice.SharedWorkspaceFolders
SetswsFolders=ActiveWorkbook.SharedWorkspace.Folders
MsgBox"Thereare"&swsFolders.Count&_
"folder(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsFolders=Nothing
FoundFilesPropertyReturnsaFoundFilesobjectthatcontainsthenamesofallthefilesfoundduringasearch.Read-only.
Example
Thisexamplestepsthroughthelistoffilesfoundduringasearchanddisplaysthepathforeachfile.
WithApplication.FileSearch
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
NextI
EndWith
GuessHelpPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantballoonpresentsalistofHelptopicsbasedonkeywordstheuserselectsbeforeclickingtheAssistantwindoworpressingF1.Read/writeBoolean.
NoteThispropertyisobsoletebuthasbeenretainedforcompatibilitywithcodewritteninpreviousversionsofMicrosoftOffice.
Remarks
TheGuessHelppropertycorrespondstotheGuesshelptopicsoptionunderUsetheOfficeAssistantontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexampleallowstheOfficeAssistanttoguessatHelptopics.
Assistant.GuessHelp=True
GuidPropertyReturnsthegloballyuniqueclassidentifier(GUID)forthespecifiedCOMAddInobject.Read-onlyString.
Example
ThefollowingexampledisplaystheProgIDandGUIDforCOMadd-inoneinamessagebox.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
HeadingPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetstheheadingthatappearsintheOfficeAssistantballoon.Read/writeString.
Remarks
Youcanspecifyagraphictobedisplayedintheballoonheadingbyusingthefollowingsyntax:{typelocationsizing_factor},wheretypeisbmp(bitmap)orwmf(Windowsmetafile),locationistheresourceIDorthepathandfilename,andsizing_factorspecifiesthewidthofthewmf(omittedforbmp).
Theballoonheadingalsosupportsunderlinedtextandtextthathasoneofthe16systempalettecolorsappliedtoit.Todisplayunderlinedtextinaheading,usethesyntax{ul}or{ul1};use{ul0}toturnunderliningoff.Tochangethecolorofheadingtext,precedethetextstringwiththecharactersequence{cfnumber},wherenumberisoneofthesystemcolornumberslistedinthefollowingtable.
Systemcolornumber Color0 Black1 Darkred2 Darkgreen3 Darkyellow4 Darkblue5 Darkmagenta6 Darkcyan7 Lightgray248 Mediumgray249 Red250 Green251 Yellow252 Blue253 Magenta254 Cyan255 White
Ifyouspecifyanumberotherthanoneoftheprecedingsystemcolornumbers,theheadingtextisblack.
Example
Thisexampledisplaysaballoonwithaheading,text,andthreeregionchoices.
WithAssistant.NewBalloon
.Button=msoButtonSetOkCancel
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
ShowAll
HeightPropertyReturnsorsetstheheightofacommandbarcontrolorcommandbar.Read/writeLong.
expression.Height
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Example
ThisexampleaddsacustomcontroltothecommandbarnamedCustom.Theexamplesetstheheightofthecustomcontroltotwicetheheightofthecommandbarandsetsthecontrol’swidthto50pixels.Noticehowthecommandbarautomaticallyresizesitselftoaccommodatethecontrol.
SetmyBar=CommandBars("Custom")
barHeight=myBar.Height
SetmyControl=myBar.Controls_
.Add(Type:=msoControlButton,_
Id:=CommandBars("Standard").Controls("Save").Id,_
Temporary:=True)
WithmyControl
.Height=barHeight*2
.Width=50
EndWith
myBar.Visible=True
ShowAll
HelpContextIdPropertyReturnsorsetstheHelpcontextIdnumberfortheHelptopicattachedtothecommandbarcontrol.Read/writeLong.
Remarks
Tousethisproperty,youmustalsosettheHelpFileproperty.HelptopicsrespondtoShift+F1.
Example
Thisexampleaddsacustomcommandbarwithacomboboxthattracksstockdata.TheexamplealsospecifiestheHelptopictobedisplayedforthecomboboxwhentheuserpressesSHIFT+F1.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
WithCommandBars("Custom").Controls(1)
.AddItem"GetStockQuote",1
.AddItem"ViewChart",2
.AddItem"ViewFundamentals",3
.AddItem"ViewNews",4
.Caption="StockData"
.DescriptionText="ViewDataForStock"
.HelpFile="C:\corphelp\custom.hlp"
.HelpContextID=47
EndWith
ShowAll
HelpFilePropertyReturnsorsetsthefilenamefortheHelptopicattachedtothecommandbarcontrol.Read/writeString.
Remarks
Tousethisproperty,youmustalsosettheHelpContextIDproperty.HelptopicsrespondtotheuserpressingSHIFT+F1.
Example
Thisexampleaddsacustomcommandbarwithacomboboxthattracksstockdata.TheexamplealsospecifiestheHelptopictobedisplayedforthecomboboxwhentheuserpressesSHIFT+F1.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
WithCommandBars("Custom").Controls(1)
.AddItem"GetStockQuote",1
.AddItem"ViewChart",2
.AddItem"ViewFundamentals",3
.AddItem"ViewNews",4
.Caption="StockData"
.DescriptionText="ViewDataForStock"
.HelpFile="C:\corphelp\custom.hlp"
.HelpContextID=47
EndWith
HighPriorityTipsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantdisplayshigh-prioritytips.Read/writeBoolean.
Remarks
TheHighPriorityTipspropertycorrespondstotheOnlyshowhighprioritytipsoptionunderShowtipsaboutontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexamplesetstheOfficeAssistanttodisplayhigh-prioritytips.
Assistant.HighPriorityTips=True
HTMLProjectItemsPropertyReturnstheHTMLProjectItemscollectionthatisincludedinthespecifiedHTMLproject.Read-onlyHTMLProjectItems.
Example
ThisexamplereturnsthenumberofitemsintheHTMLProjectItemscollectionintheHTMLprojectintheactiveworkbook.
intCount=ActiveWorkbook.HTMLProject.HTMLProjectItems.Count
ShowAll
HyperlinkTypePropertySetsorreturnsthetypeofhyperlinkassociatedwiththespecifiedcommandbarbutton.Read/writeMsoCommandBarButtonHyperlinkType.
MsoCommandBarButtonHyperlinkTypecanbeoneoftheseMsoCommandBarButtonHyperlinkTypeconstants.msoCommandBarButtonHyperlinkInsertPicturemsoCommandBarButtonHyperlinkNonemsoCommandBarButtonHyperlinkOpen
Example
ThisexamplecheckstheHyperlinkTypepropertyforthespecifiedcommandbarbuttononthecommandbarnamed"Custom.".IfHyperlinkTypeissettomsoCommandBarButtonHyperlinkNone,theexamplesetsthepropertytomsoCommandBarButtonHyperlinkOpenandsetstheURLtowww.microsoft.com.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
SetmyButton=myBar.Controls.Add(Type:=msoControlButton)
WithmyButton
.FaceId=277
.HyperlinkType=msoCommandBarButtonHyperlinkNone
EndWith
IfmyButton.HyperlinkType<>_
msoCommandBarButtonHyperlinkOpenThen
myButton.HyperlinkType=_
msoCommandBarButtonHyperlinkOpen
myButton.TooltipText="www.microsoft.com"
EndIf
ShowAll
IconPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Returnsorsetsthetypeoficonthatappearsintheupper-leftportionoftheOfficeAssistantballoon.Read/writeMsoIconType.
MsoIconTypecanbeoneoftheseMsoIconTypeconstants.msoIconAlertmsoIconAlertCriticalmsoIconAlertInfomsoIconAlertQuerymsoIconAlertWarningmsoIconNonemsoIconTip
Example
Thisexamplecreatesaballoonwithan“Alert”iconthatinstructstheusertoselectaprinter.
WithAssistant.NewBalloon
.Heading="SelectAPrinter"
.Text="Youmustselectaprinterbeforeprinting."
.Icon=msoIconAlert
.CheckBoxes(1).Text="Localprinter"
.CheckBoxes(2).Text="Networkprinter"
.Show
EndWith
ShowAll
IdPropertyIdpropertyasitappliestotheCommandBarButton,
CommandBarComboBox,andCommandBarControlobjects.
ReturnstheIDforabuilt-incommandbarcontrol.Read-onlyLong.
expression.Id
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Remarks
Acontrol'sIDdeterminesthebuilt-inactionforthatcontrol.ThevalueoftheIdpropertyforallcustomcontrolsis1.
IdpropertyasitappliestotheScriptobject.
SetsorreturnstheIDofaScriptobject.Read/writeString.
expression.Id
expressionRequired.AnexpressionthatreturnsaScriptobject.
Remarks
TheIDreturnedistheIDattributeofthe<SCRIPT>taginHTML.Ifthere’snoIDattributespecifiedinthe<SCRIPT>tag,theIdpropertyreturnsanemptystring.
IdspecifiesanSGMLidentifierusedfornamingelements.Valididentifiersincludeanystringthatbeginswithaletterandiscomposedofalphanumericcharacters;thestringcanalsoincludetheunderscorecharacter(_).
TheIDmustbeuniquewithintheHTMLdocument.
Example
AsitappliestotheCommandBarButton,CommandBarComboBox,andCommandBarControlobjects.
Thisexamplechangesthebuttonfaceofthefirstcontrolonthecommandbarnamed"Custom2"ifthebutton'sIDvalueislessthan25.
Setctrl=CommandBars("Custom").Controls(1)
Withctrl
If.Id<25Then
.FaceId=17
.Tag="Changedcontrol"
EndIf
EndWith
Thefollowingexamplechangesthecaptionofeverycontrolonthetoolbarnamed"Standard"tothecurrentvalueoftheIdpropertyforthatcontrol.
ForEachctlInCommandBars("Standard").Controls
ctl.Caption=CStr(ctl.Id)
Nextctl
AsitappliestotheScriptobject.
ThisexamplesetstheIdpropertyofthefirstscriptinworksheetoneoftheactiveworkbooktoanewvalue.
ActiveWorkbook.Worksheets(1).Scripts(1).Id="UpdatedScriptName"
IndexPropertyReturnsaLongrepresentingtheindexnumberforanobjectinthecollection.Read-only.
expression.Index
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
Thepositionofthefirstcommandbarcontrolis1.SeparatorsarenotcountedintheCommandBarControlscollection.
Example
Thisexamplesearchesthecommandbarnamed"Custom2"foracontrolwithanIdvalueof23.Ifsuchacontrolisfoundandtheindexnumberofthecontrolisgreaterthan5,thecontrolwillbepositionedasthefirstcontrolonthecommandbar.
SetmyBar=CommandBars("Custom2")
Setctrl1=myBar.FindControl(Id:=23)
Ifctrl1.Index>5Then
ctrl1.Movebefore:=1
EndIf
InitialFileNamePropertySetorreturnsaStringrepresentingthepathand/orfilenamethatisinitiallydisplayedinafiledialogbox.Read/write.
expression.InitialFileName
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
Youcanusethe'*'and'?'wildcardcharacterswhenspecifyingthefilenamebutnotwhenspecifyingthepath.The'*'representsanynumberofconsecutivecharactersandthe'?'representsasinglecharacter.Forexample,.InitialFileName="c:\c*s.txt"willreturnboth"charts.txt"and"checkregister.txt."
Ifyouspecifyapathandnofilename,thenallfilesthatareallowedbythefilefilterwillappearinthedialogbox.
Ifyouspecifyafilethatexistsintheinitialfolder,thenonlythatfilewillappearinthedialogbox.
Ifyouspecifyafilenamethatdoesn'texistintheinitialfolder,thenthedialogboxwillcontainnofiles.ThetypeoffilethatyouspecifyintheInitialFileNamepropertywilloverridethefilefiltersettings.
Ifyouspecifyaninvalidpath,thelast-usedpathisused.Amessagewillwarnuserswhenaninvalidpathisused.
Settingthispropertytoastringlongerthan256characterswillcausearun-timeerror.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'SettheinitialpathtotheC:\drive.
.InitialFileName="C:\"
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
ShowAll
InitialViewPropertyReturnsorsetsanMsoFileDialogViewconstantrepresentingtheinitialpresentationoffilesandfoldersinafiledialogbox.Read/write.
MsoFileDialogViewcanbeoneoftheseMsoFileDialogViewconstants.msoFileDialogViewDetailsmsoFileDialogViewLargeIconsmsoFileDialogViewListmsoFileDialogViewPreviewmsoFileDialogViewPropertiesmsoFileDialogViewSmallIconsmsoFileDialogViewThumbnailThisconstantisonlyavailableinconjunctionwithMicrosoftWindows2000orMicrosoftWindowsMillenniumEdition,orlater.msoFileDialogViewWebViewNotavailable.Ifyouselectthisconstant,thedefaultviewwillbeused.
expression.InitialView
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysaFilePickerdialogboxindetailsviewusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Settheinitialviewtothedetailsview.
.InitialView=msoFileDialogViewDetails
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
IntroductionPropertySetsorreturnstheintroductorytextthatisincludedwithadocumentthatissentusingtheMsoEnvelopeobject.Theintroductorytextisincludedatthetopofthedocumentinthee-mail.Read/writeString.
expression.Introduction
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplesendstheactiveMicrosoftWorddocumentasane-mailtothee-mailaddressthatyoupasstothesubroutine.
SubSendMail(ByValstrRecipientAsString)
'UseaWith...EndWithblocktoreferencetheMsoEnvelopeobject.
WithApplication.ActiveDocument.MailEnvelope
'Addsomeintroductorytextbeforethebodyofthee-mail.
.Introduction="Pleasereadthisandsendmeyourcomments."
'ReturnaMailItemobjectthatyoucanusetosendthedocument.
With.Item
'Allofthemailitemsettingsaresavedwiththedocument.
'WhenyouaddarecipienttotheRecipientscollection
'orchangeotherpropertiesthesesettingswillpersist.
.Recipients.AddstrRecipient
.Subject="Hereisthedocument."
'Thebodyofthismessagewillbe
'thecontentoftheactivedocument.
.Send
EndWith
EndWith
EndSub
IsCertificateExpiredPropertyTrueifthedigitalcertificatethatcorrespondstotheSignatureobjecthasexpired.Read-onlyBoolean.
expression.IsCertificateExpired
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
IsCertificateRevokedPropertyTrueifthedigitalcertificatethatcorrespondstotheSignatureobjecthasbeenrevokedbytheissuerofthecertificate.Read-onlyBoolean.
expression.IsCertificateRevoked
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
IsOpenPropertyTrueifthespecifiedHTMLprojectitemisopenintheMicrosoftScriptEditor.Read-onlyBoolean.
Example
ThisexampledetermineswhetherthespecifiedHTMLprojectitemisopen.andifitis,theexamplethenloadsscriptfromthespecifiedfile.
IfActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).IsOpenThen
ActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).LoadFromFile("C:\MyScript.txt")
Else
MsgBox"TheHTMLProjectItemisnotopen."
EndIf
IsPriorityDroppedPropertyTrueifthecontroliscurrentlydroppedfromthemenuortoolbarbasedonusagestatisticsandlayoutspace.(Notethatthisisnotthesameasthecontrol'svisibility,assetbytheVisibleproperty.)AcontrolwithVisiblesettoTrue,willnotbeimmediatelyvisibleonaPersonalizedMenuorToolbarifIsPriorityDroppedisTrue.Read-onlyBoolean.
Remarks
TodeterminewhentosetIsPriorityDroppedtoTrueforaspecificmenuitem,MicrosoftOfficemaintainsatotalcountofthenumberoftimesthemenuitemwasusedandarecordofthenumberofdifferentapplicationsessionsinwhichtheuserhasusedanothermenuiteminthesamemenuasthismenuitem,withoutusingthespecificmenuitem.Whenthisvaluereachescertainthresholdvalues,thecountisdecremented.Whenthecountreacheszero,IsPriorityDroppedissettoTrue.Programmerscannotsetthesessionvalue,thethresholdvalue,ortheIsPriorityDroppedproperty.Programmerscan,however,usetheAdaptiveMenuspropertytodisableadaptivemenusforspecificmenusinanapplication.
TodeterminewhentosetIsPriorityDroppedtoTrueforaspecifictoolbarcontrol,Officemaintainsalistoftheorderinwhichallthecontrolsonthattoolbarwerelastexecuted.Atoolbarwillalwaysshowasmanycontrolsasithasspacetoshow,intheorderofmostrecentlyusedtoleastrecentlyused.ControlswithPrioritysetto1willalwaysbeshownandthetoolbarwillwraprows,ifnecessary,toshowthesecontrols.ProgrammerscanusethePrioritypropertytoensurethatspecifictoolbarcontrolsarealwaysshown,ortorepositiontoolbarssothattheyhaveenoughspacetodisplayalloftheircontrols.
YoucanusethefollowingtabletopredictthenumberofsessionsforwhichamenuitemonaPersonalizedMenuwillremainvisiblebeforethemenuitem'sIsPriorityDroppedpropertyissettoTrue.
Numberofusesofthecommandbarcontrol
Numberofsessionsoftheapplication
0,1 32 63 94,5 126–8 179–13 2314–24 2925ormore 31
Example
ThisexamplecheckstheIsPriorityDroppedpropertyforthefirstcontrolonthecommandbarnamed“Custom.”IfIsPriorityDroppedisTrue,theexamplesetstheAdaptiveMenuspropertytoFalse,restoringthedroppedcommandbar.
IfCommandBars("Custom").Controls(1).IsPriorityDroppedThen
CommandBars.AdaptiveMenus=True
EndIf
IssuerPropertyReturnsaStringrepresentingthenameoftheissuerofthedigitalcertificatethatcorrespondstotheSignatureobject.Read-only.
expression.Issuer
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
IsValidPropertyTrueifthedigitalsignaturethatcorrespondstotheSignatureobjectisavalidsignature.Asignaturemaybeinvalidforseveralreasonsrangingfromitscertificatehavingexpiredtochangesinthedocumentthatcontainsit.Read-onlyBoolean.
expression.IsValid
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalcertificatewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalcertificatethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalcertificate.
'Iftheuserselectsacertificate,
'thenasignatureiscreatedand
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.'
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
IsVersioningEnabledPropertyReturnsaBooleanvaluethatindicateswhetherthedocumentlibraryinwhichtheactivedocumentissavedontheserverisconfiguredtocreateabackupcopy,orversion,eachtimethefileiseditedontheWebsite.Read-onlyBoolean.
expression.IsVersioningEnabled()
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionsobject.
Remarks
Versioningisenabledordisabledonthedocumentlibraryandnotonindividualdocuments.ThereforethevalueoftheIsVersioningEnabledpropertydependsonthedocumentlibraryinwhichthedocumentissaved.
Example
Thefollowingexampledisplaysthenumberofsavedversionsoftheactivedocument,ifversioningisenabled.
DimdlvVersionsAsOffice.DocumentLibraryVersions
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
MsgBox"Thisdocumenthas"&dlvVersions.Count&_
"savedversions.",vbInformation+vbOKOnly,_
"VersionInformation"
Else
MsgBox"Versioningisnotenabledforthisdocument.",_
vbInformation+vbOKOnly,"NoVersioning"
EndIf
SetdlvVersions=Nothing
ShowAll
ItemPropertyItempropertyasitappliestotheAnswerWizardFilesandFoundFiles
objects.
ReturnsafilenamestringfromanAnswerWizardFilescollection,orafilenamefromthelistoffilenamesrepresentedbytheFoundFilesobject,respectively.Read-onlyString.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.TheindexnumberoftheAnswerWizardfilenamestring,orthefilename,tobereturned.
ItempropertyasitappliestotheAssistant,BalloonCheckbox,BalloonLabel,andFileDialogobjects.
Returnsthetextassociatedwithanobject.Read-onlyString.
expression.Item
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
ItempropertyasitappliestotheBalloonCheckboxesandBalloonLabelsobjects.
ReturnsaBalloonCheckBoxorBalloonLabelobject.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.Theindexnumberofthecheckboxorlabeltobereturned.
ItempropertyasitappliestotheCommandBarsobject.
ReturnsaCommandBarobjectfromtheCommandBarscollection.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaCommandBarsobject.
IndexRequiredVariant.Thenameorindexnumberoftheobjecttobereturned.
ItempropertyasitappliestotheCommandBarControlsobject.
ReturnsaCommandBarControlobjectfromtheCommandBarControlscollection.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaCommandBarControlsobject.
IndexRequiredVariant.Thenameorindexnumberoftheobjecttobereturned.
ItempropertyasitappliestotheDocumentLibraryVersionsobject.
ReturnsaDocumentLibraryVersionobjectfromtheDocumentLibraryVersionscollection.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionsobject.
IndexRequiredLong.TheindexnumberoftheDocumentLibraryVersionreturned.
ItempropertyasitappliestotheDocumentPropertiesobject.
ReturnsaDocumentPropertyobjectfromtheDocumentPropertiescollection.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaDocumentPropertiesobject.
IndexRequiredVariant.Thenameorindexnumberofthedocumentpropertyreturned.
ItempropertyasitappliestotheFileTypescollection.
ReturnsavaluethatindicateswhichfiletypewillbesearchedforbytheExecutemethodoftheFileSearchobject.Read-onlyMsoFileType.
MsoFileTypecanbeoneoftheseMsoFileTypeconstants.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFilesmsoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItem
msoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPagesmsoFileTypeWordDocuments
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaFileTypescollection.
IndexRequiredLong.Theindexnumberoftheobjecttobereturned.
ItempropertyasitappliestotheMsoEnvelopeobject.
ReturnsaMailItemobjectthatcanbeusedtosendthedocumentasane-mail.
expression.Item
expressionRequired.AnexpressionthatreturnsanMsoEnvelopeobject.
ItempropertyasitappliestothePermissionobject.
ReturnsaUserPermissionobjectthatisamemberofthePermissioncollection.TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.
expression.Item(Index)
expressionRequired.AnitemthatreturnsaPermissionobject.
IndexRequiredVariant.ThenumericindexoftheUserPermissioninthePermissioncollection,ortheemailaddressoftheuserwhosesetofpermissionsontheactivedocumentistobereturned.
ItempropertyasitappliestothePropertyTestsobject.
ReturnsaPropertyTestobjectfromthePropertyTestscollection.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaPropertyTestsobject.
IndexRequiredLong.Theindexnumberofthepropertytesttobereturned.
ItempropertyasitappliestotheScopeFoldersandSearchFoldersobjects.
ReturnsaScopeFolderobjectthatrepresentsasubfolderoftheparentobject.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredLong.Determineswhichsubfoldertoreturn.
ItempropertyasitappliestotheSearchScopesobject.
ReturnsaSearchScopeobjectthatcorrespondstoanareainwhichtoperformafilesearch,suchaslocaldrivesorMicrosoftOutlookfolders.
expression.Item(Index)
expressionRequired.AnexpressionthatreturnsaSearchScopesobject.
IndexRequiredLong.DetermineswhichSearchScopeobjecttoreturn.
ItempropertyasitappliestotheSharedWorkspaceFilesobject.
ReturnsaSharedWorkspaceFileobjectfromtheFilescollectionofthesharedworkspace.
expression.Item(Index)
expressionRequired.ThespecifiedSharedWorkspaceFilescollection.
IndexRequiredLong.ReturnstheSharedWorkspaceFileatthepositionspecified.IndexdoesnotcorrespondtotheorderinwhichtheitemsaredisplayedintheSharedWorkspacepane,andisnotaffectedbyre-sortingthedisplay.
ItempropertyasitappliestotheSharedWorkspaceFoldersobject.
ReturnsaSharedWorkspaceFolderobjectfromtheFolderscollectionofthesharedworkspace.
expression.Item(Index)
expressionRequired.ThespecifiedSharedWorkspaceFolderscollection.
IndexRequiredLong.ReturnstheSharedWorkspaceFolderatthepositionspecified.IndexdoesnotcorrespondtotheorderinwhichtheitemsaredisplayedintheSharedWorkspacepane,andisnotaffectedbyre-sortingthedisplay.
ItempropertyasitappliestotheSharedWorkspaceLinksobject.
ReturnsaSharedWorkspaceLinkobjectfromtheLinkscollectionofthesharedworkspace.
expression.Item(Index)
expressionRequired.ThespecifiedSharedWorkspaceLinkscollection.
IndexRequiredLong.ReturnstheSharedWorkspaceLinkatthepositionspecified.IndexdoesnotcorrespondtotheorderinwhichtheitemsaredisplayedintheSharedWorkspacepane,andisnotaffectedbyre-sortingthedisplay.
ItempropertyasitappliestotheSharedWorkspaceMembersobject.
ReturnsaSharedWorkspaceMemberobjectfromtheMemberscollectionofthesharedworkspace.
expression.Item(Index)
expressionRequired.ThespecifiedSharedWorkspaceMemberscollection.
IndexRequiredLong.ReturnstheSharedWorkspaceMemberatthepositionspecified.Indexdoesnotcorrespondtotheorderinwhichtheitemsare
displayedintheSharedWorkspacepane.
ItempropertyasitappliestotheSharedWorkspaceTasksobject.
ReturnsaSharedWorkspaceTaskobjectfromtheTaskscollectionofthesharedworkspace.
expression.Item(Index)
expressionRequired.ThespecifiedSharedWorkspaceTaskscollection.
IndexRequiredLong.ReturnstheSharedWorkspaceTaskatthepositionspecified.IndexdoesnotcorrespondtotheorderinwhichtheitemsaredisplayedintheSharedWorkspacepane,andisnotaffectedbyre-sortingthedisplay.
ItempropertyasitappliestotheSignatureSetobject.
ReturnsaSignatureobjectthatcorrespondstooneofthedigitalsignatureswithwhichthedocumentiscurrentlysigned.
expression.Item(iSig)
expressionRequired.AnexpressionthatreturnsaSignatureSetobject.
iSigRequiredLong.DetermineswhichSignatureobjecttoreturn.
ItempropertyasitappliestotheWebPageFontsobject.
ReturnsaWebPageFontobjectfromtheWebPageFontscollectionforaparticularvalueofMsoCharacterSet.
expression.Item(Index)
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
IndexRequiredMsoCharacterSet.Thespecifiedcharacterset.
MsoCharacterSetcanbeoneoftheseMsoCharacterSetconstants.
msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
Example
AsitappliestotheAnswerWizardFilesandFoundFilesobjects.
ThisexampleresetsthefilelistforthecurrentAnswerWizardanddisplaysboththefilecountandthefilenamesinamessagebox,usingtheItempropertytoreturnthefilenames.
DimcustomAnswerWizardAsAnswerWizard
DimstrFileListAsString
DimintCounterAsInteger
DimintNumFilesAsInteger
SetcustomAnswerWizard=Application.AnswerWizard
intCounter=1
customAnswerWizard.ResetFileList
strFileList=""
intNumFiles=customAnswerWizard.Files.Count
ForintCounter=1To(intNumFiles)
strFileList=strFileList&_
customAnswerWizard.Files.Item(intCounter)&Chr(13)
Next
MsgBox"Thereare"&customAnswerWizard.Files.Count&_
"filesavaialblethroughthisAnswerWizard:"&_
Chr(13)&strFileList
AsitappliestotheBalloonCheckboxesandBalloonLabelsobjects.
Itemisthedefaultmemberoftheobjectorcollection.ThefollowingtwostatementsbothassigntolblTextthetextofthefirstlabelintheBalloonobjectassignedtomyBalloon.
lblText=myBalloon.Labels(1).Item
lblText=myBalloon.Labels(1)
AsitappliestotheCommandBarsobject.
Itemisthedefaultmemberoftheobjectorcollection.ThefollowingtwostatementsbothassignaCommandBarobjecttocmdBar.
SetcmdBar=CommandBars.Item("Standard")
SetcmdBar=CommandBars("Standard")
AsitappliestotheMsoEnvelopeobject.
ThefollowingexamplesendstheactiveMicrosoftWorddocumentasane-mailtothee-mailaddressthatyoupasstothesubroutine.
SubSendMail(ByValstrRecipientAsString)
'UseaWith...EndWithblocktoreferencethemsoEnvelopeobject.
WithApplication.ActiveDocument.MailEnvelope
'Addsomeintroductorytextbeforethebodyofthee-mailmessage.
.Introduction="Pleasereadthisandsendmeyourcomments."
'ReturnaMailItemobjectthatyoucanusetosendthedocument.
With.Item
'Allofthemailitemsettingsaresavedwiththedocument.
'WhenyouaddarecipienttotheRecipientscollection
'orchangeotherpropertiesthesesettingswillpersist.
.Recipients.AddstrRecipient
.Subject="Hereisthedocument."
'Thebodyofthismessagewillbe
'thecontentoftheactivedocument.
.Send
EndWith
EndWith
EndSub
AsitappliestotheWebPageFontsobject.
ThefollowingexampleusestheItempropertytosetmyFonttotheWebPageFontobjectfortheEnglish/WesternEuropean/OtherLatinScriptcharactersetintheactiveapplication.
DimmyFontAsWebPageFont
SetmyFont=_
Application.DefaultWebOptions.Fonts._
Item(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)
ItemCountExceededPropertyReturnsaBooleanvaluethatindicateswhetherthenumberofitemsinthecollectionhasexceededthe99thatcanbedisplayedintheSharedWorkspacetaskpane.Read-onlyBoolean.
expression.Connected
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheSharedWorkspacetaskpanecanonlydisplay99sharedworkspacefilesandfolders,links,members,ortasks.Ifmorethan99itemsareaddedtoanyofthesecollections:
thecorrespondingtaboftheSharedWorkspacetaskpanewillstopdisplayingthelistofitemsandwilldisplayalinktothesharedworkspacesitewebpageinstead;thecollectionwillnolongerbepopulatedlocallyanditsCountpropertywillreturn0(zero).
Furthermore,oncetheItemCountExceededpropertyreturnsTrueforoneofthecollectionslistedabove,thedevelopercannolongerremedythesituationprogrammaticallybydeletingitemsfromthecollectiontoreducethecountbelow99,becausethecollectionisnolongerpopulated.
TheItemCountExceededpropertyoftheSharedWorkspaceFilesandtheSharedWorkspaceFolderscollectionsreturnsTruewhenthecombinedCountoffilesandfoldersexceeds99,sincebothlistsarecombinedanddisplayedtogetherontheDocumentstaboftheSharedWorkspacetaskpane.
Example
ThefollowingexamplecheckstheCountpropertyoftheSharedWorkspaceLinkscollection.IfCountreturns0(zero),itcheckstheItemCountExceededpropertytodeterminewhetherinfactthesharedworkspacehasnosavedlinks,orwhetherithasmorethan99andthelinkscollectionhasbeencleared.
ActiveWorkbook.SharedWorkspace.Refresh
IfActiveWorkbook.SharedWorkspace.Links.Count=0Then
IfActiveWorkbook.SharedWorkspace.Links.ItemCountExceededThen
MsgBox"Morethan99linksinsharedworkspace.",_
vbInformation+vbOKOnly,"ItemCountExceeded"
Else
MsgBox"Nolinksinsharedworkspace.",_
vbInformation+vbOKOnly,"NoLinks"
EndIf
EndIf
KeyboardShortcutTipsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantdisplaysHelpaboutkeyboardshortcuts.Read/writeBoolean.
Remarks
TheKeyboardShortcutTipspropertycorrespondstotheKeyboardshortcutsoptionintheShowtipsaboutsectionontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexamplesetstheOfficeAssistanttoprovideHelpinformationaboutkeyboardshortcuts.
Assistant.KeyboardShortcutTips=True
LabelsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsaBalloonLabelscollectionthatrepresentsthebuttonlabels,numberlabels,andbulletlabelscontainedinthespecifiedOfficeAssistantballoon.Read-only.
Forinformationaboutreturningasinglememberofacollection,seeReturninganObjectfromaCollection.
Example
Thisexamplecreatesaballooncontainingthreechoices.ThevariablexissettothereturnvalueoftheShowmethod,whichwillbe1,2or3,dependingonthelabeltheuserclicks.Intheexample,amessageboxdisplaysthevalueofthevariablex,butyoucanpassthevaluetoanotherprocedureoryoucanusethevalueinaSelectCasestatement.
Setb=Assistant.NewBalloon
Withb
.Heading="Thisismyheading"
.Text="Selectoneofthesethings:"
.Labels(1).Text="ChoiceOne"
.Labels(2).Text="ChoiceTwo"
.Labels(3).Text="ChoiceThree"
x=.Show
EndWith
MsgBoxx
ShowAll
LanguagePropertySpecifiesorreturnsthescriptinglanguageoftheactivescript.Read/writeMsoScriptLanguage.
MsoScriptLanguagecanbeoneoftheseMsoScriptLanguageconstants.msoScriptLanguageASPmsoScriptLanguageJavamsoScriptLanguageOthermsoScriptLanguageVisualBasic
Remarks
TheMsoScriptLanguageconstantsusedwiththeLanguagepropertyarealsousedintheLanguageparameterintheAddmethodoftheScriptscollection.
Example
ThisexamplecheckstheLanguagepropertytoensurethatthefirstscriptinworksheetoneintheactiveworkbookiswritteninVBScript.
IfActiveWorkbook.Worksheets(1).Scripts(1).Language<>_
msoScriptLanguageVisualBasicThen
MsgBox"LanguageisnotsettoVBScript."
EndIf
ShowAll
LanguageIDPropertyReturnsthelocaleidentifier(LCID)fortheinstalllanguage,theuserinterfacelanguage,ortheHelplanguage.Read-onlyLong.
expression.LanguageID(Id)
expressionRequired.AnexpressionthatreturnsaLanguageSettingsobject.
IdRequiredMsoAppLanguageID.
MsoAppLanguageIDconstant Meaning
msoLanguageIDExeMode
Thelanguagemodethattheapplicationisusing.ThissettingappliesonlytoMicrosoftExcelandMicrosoftAccess.Thissettingaffectslanguagesthatcanbedisplayedandedited,availablelanguage-specificfeatures,numberstyles,currencysettings,andsoforth.
IfnoneofthelanguagessupportedbyExcelandAccessareused,thehostapplicationwillnotbeconfiguredtosupportright-to-leftandEastAsianlanguages.Thesupportedlanguagesareasfollows:
ArabicFarsiHebrewJapaneseKoreanSimplifiedChineseTraditionalChineseUrduYiddish
msoLanguageIDHelp ThelanguageusedforonlineHelp.
msoLanguageIDInstall
ThelanguagesettingsusedbyMicrosoftOfficetosetupdefaults.Forexample,MicrosoftWordusesthissettingtodeterminethelayoutoftoolbarsandthedefaulttypesofbulletsandnumbersonalanguage-by-languagebasis.
msoLanguageIDUI Thelanguageusedbythehostapplication'suserinterface.
msoLanguageIDUIPrevious
Thelanguagesettingfortheuserinterfacewhenagivencomputerwaslastrebooted.Aprogramoradd-incanusethistodeterminewhethertheuserinterfacelanguagehaschanged.
Example
ThisMicrosoftExcelexamplecheckstheLanguageIDpropertysettingsfortheuserinterfaceandexecutionmodetoverifythattheyaresettothesameLCID.Theexamplereturnsanerrorifthereisadiscrepancy.
IfApplication.LanguageSettings.LanguageID(msoLanguageIDExeMode)_
<>Application.LanguageSettings.LanguageID(msoLanguageIDUI)_
ThenMsgBox"Theuserinterfacelanguageandexecution"&_
"modearedifferent."
ShowAll
LanguagePreferredForEditingPropertyReturnsTrueifthevalueforthemsoLanguageIDconstanthasbeenidentifiedintheWindowsregistryasapreferredlanguageforediting.Read-onlyBoolean.
expression.LanguagePreferredForEditing(lid)
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
lidRequiredMsoLanguageID.
MsoLanguageIDcanbeoneoftheseMsoLanguageIDconstants.msoLanguageIDAfrikaansmsoLanguageIDAlbanianmsoLanguageIDAmharicmsoLanguageIDArabicmsoLanguageIDArabicAlgeriamsoLanguageIDArabicBahrainmsoLanguageIDArabicEgyptmsoLanguageIDArabicIraqmsoLanguageIDArabicJordanmsoLanguageIDArabicKuwaitmsoLanguageIDArabicLebanonmsoLanguageIDArabicLibyamsoLanguageIDArabicMoroccomsoLanguageIDArabicOmanmsoLanguageIDArabicQatarmsoLanguageIDArabicSyriamsoLanguageIDArabicTunisiamsoLanguageIDArabicUAE
msoLanguageIDArabicYemenmsoLanguageIDArmenianmsoLanguageIDAssamesemsoLanguageIDAzeriCyrillicmsoLanguageIDAzeriLatinmsoLanguageIDBasquemsoLanguageIDBelgianDutchmsoLanguageIDBelgianFrenchmsoLanguageIDBengalimsoLanguageIDBrazilianPortuguesemsoLanguageIDBulgarianmsoLanguageIDBurmesemsoLanguageIDByelorussianmsoLanguageIDCatalanmsoLanguageIDCherokeemsoLanguageIDChineseHongKongmsoLanguageIDChineseMacaomsoLanguageIDChineseSingaporemsoLanguageIDCroatianmsoLanguageIDCzechmsoLanguageIDDanishmsoLanguageIDDutchmsoLanguageIDEnglishAUSmsoLanguageIDEnglishBelizemsoLanguageIDEnglishCanadianmsoLanguageIDEnglishCaribbeanmsoLanguageIDEnglishIrelandmsoLanguageIDEnglishJamaicamsoLanguageIDEnglishNewZealandmsoLanguageIDEnglishPhilippinesmsoLanguageIDEnglishSouthAfricamsoLanguageIDEnglishTrinidadmsoLanguageIDEnglishUK
msoLanguageIDEnglishUSmsoLanguageIDEnglishZimbabwemsoLanguageIDEstonianmsoLanguageIDFaeroesemsoLanguageIDFarsimsoLanguageIDFinnishmsoLanguageIDFrenchmsoLanguageIDFrenchCameroonmsoLanguageIDFrenchCanadianmsoLanguageIDFrenchCotedIvoiremsoLanguageIDFrenchLuxembourgmsoLanguageIDFrenchMalimsoLanguageIDFrenchMonacomsoLanguageIDFrenchReunionmsoLanguageIDFrenchSenegalmsoLanguageIDFrenchWestIndiesmsoLanguageIDFrenchZairemsoLanguageIDFrisianNetherlandsmsoLanguageIDGaelicIrelandmsoLanguageIDGaelicScotlandmsoLanguageIDGalicianmsoLanguageIDGeorgianmsoLanguageIDGermanmsoLanguageIDGermanAustriamsoLanguageIDGermanLiechtensteinmsoLanguageIDGermanLuxembourgmsoLanguageIDGreekmsoLanguageIDGujaratimsoLanguageIDHebrewmsoLanguageIDHindimsoLanguageIDHungarianmsoLanguageIDIcelandicmsoLanguageIDIndonesian
msoLanguageIDInuktitutmsoLanguageIDItalianmsoLanguageIDJapanesemsoLanguageIDKannadamsoLanguageIDKashmirimsoLanguageIDKazakhmsoLanguageIDKhmermsoLanguageIDKirghizmsoLanguageIDKonkanimsoLanguageIDKoreanmsoLanguageIDLaomsoLanguageIDLatvianmsoLanguageIDLithuanianmsoLanguageIDMacedonianmsoLanguageIDMalayalammsoLanguageIDMalayBruneiDarussalammsoLanguageIDMalaysianmsoLanguageIDMaltesemsoLanguageIDManipurimsoLanguageIDMarathimsoLanguageIDMexicanSpanishmsoLanguageIDMixedmsoLanguageIDMongolianmsoLanguageIDNepalimsoLanguageIDNonemsoLanguageIDNoProofingmsoLanguageIDNorwegianBokmolmsoLanguageIDNorwegianNynorskmsoLanguageIDOriyamsoLanguageIDOromomsoLanguageIDPolishmsoLanguageIDPortuguesemsoLanguageIDPunjabi
msoLanguageIDRhaetoRomanicmsoLanguageIDRomanianmsoLanguageIDRomanianMoldovamsoLanguageIDRussianmsoLanguageIDRussianMoldovamsoLanguageIDSamiLappishmsoLanguageIDSanskritmsoLanguageIDSerbianCyrillicmsoLanguageIDSerbianLatinmsoLanguageIDSesothomsoLanguageIDSimplifiedChinesemsoLanguageIDSindhimsoLanguageIDSlovakmsoLanguageIDSlovenianmsoLanguageIDSorbianmsoLanguageIDSpanishmsoLanguageIDSpanishArgentinamsoLanguageIDSpanishBoliviamsoLanguageIDSpanishChilemsoLanguageIDSpanishColombiamsoLanguageIDSpanishCostaRicamsoLanguageIDSpanishDominicanRepublicmsoLanguageIDSpanishEcuadormsoLanguageIDSpanishElSalvadormsoLanguageIDSpanishGuatemalamsoLanguageIDSpanishHondurasmsoLanguageIDSpanishModernSortmsoLanguageIDSpanishNicaraguamsoLanguageIDSpanishPanamamsoLanguageIDSpanishParaguaymsoLanguageIDSpanishPerumsoLanguageIDSpanishPuertoRicomsoLanguageIDSpanishUruguay
msoLanguageIDSpanishVenezuelamsoLanguageIDSutumsoLanguageIDSwahilimsoLanguageIDSwedishmsoLanguageIDSwedishFinlandmsoLanguageIDSwissFrenchmsoLanguageIDSwissGermanmsoLanguageIDSwissItalianmsoLanguageIDTajikmsoLanguageIDTamilmsoLanguageIDTatarmsoLanguageIDTelugumsoLanguageIDThaimsoLanguageIDTibetanmsoLanguageIDTigrignaEritreamsoLanguageIDTigrignaEthiopicmsoLanguageIDTraditionalChinesemsoLanguageIDTsongamsoLanguageIDTswanamsoLanguageIDTurkishmsoLanguageIDTurkmenmsoLanguageIDUkrainianmsoLanguageIDUrdumsoLanguageIDUzbekCyrillicmsoLanguageIDUzbekLatinmsoLanguageIDVendamsoLanguageIDVietnamesemsoLanguageIDWelshmsoLanguageIDXhosamsoLanguageIDZulu
Remarks
YoumusttestallvalidmsoLanguageIDvaluestoenumeratethesetofpreferredlanguages.
Example
ThisexampledisplaysamessageifU.S.Englishisapreferrededitinglanguage.
IfApplication.LanguageSettings._
LanguagePreferredForEditing(msoLanguageIDEnglishUS)Then
MsgBox"OneofthepreferrededitinglanguagesisUSEnglish."
EndIf
LargeButtonsPropertyTrueifthetoolbarbuttonsdisplayedarelargerthannormalsize.Read/writeBoolean.
Example
Thisexampletogglesthedisplaysizeoftoolbarbuttonsonallcommandbars.
SetallBars=CommandBars
IfallBars.LargeButtonsThen
allBars.LargeButtons=False
Else
allBars.LargeButtons=True
EndIf
ShowAll
LastModifiedPropertyReturnsorsetsaconstantthatrepresentstheamountoftimesincethespecifiedfilewaslastmodifiedandsaved.ThedefaultvalueismsoLastModifiedAnyTime.Read/writeMsoLastModified.
MsoLastModifiedcanbeoneoftheseMsoLastModifiedconstants.msoLastModifiedAnyTimemsoLastModifiedLastMonthmsoLastModifiedLastWeekmsoLastModifiedThisMonthmsoLastModifiedThisWeekmsoLastModifiedTodaymsoLastModifiedYesterday
Example
Thisexamplesetsoptionsforafilesearch.ThefilesthissearchreturnsweremodifiedyesterdayandarelocatedintheC:\MyDocumentsfolderorinoneofitssubfolders.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.LastModified=msoLastModifiedYesterday
EndWith
LastRefreshedPropertyReturnsthedateandtimewhentheRefreshmethodwasmostrecentlycalled.Read-onlyVariant.
expression.LastRefreshed
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
TheLastRefreshedpropertyraisesanerroriftheRefreshmethodhasneverbeencalled.
Example
Thefollowingexamplerefreshesthesharedworkspaceifithasnotbeenrefreshedinthelast3minutes.Theexamplealsohandlestheerrorconditionwheretheworkspacehasnotyetbeenrefreshed.
OnErrorGoToerr_NeverRefreshed
IfDateDiff("s",ActiveWorkbook.SharedWorkspace.LastRefreshed,Now)>180Then
ActiveWorkbook.SharedWorkspace.Refresh
EndIf
ExitSub
err_NeverRefreshed:
ActiveWorkbook.SharedWorkspace.Refresh
LastSyncTimePropertyReturnsthedateandtimewhenthelocalcopyoftheactivedocumentwaslastsynchronizedwiththeservercopy.Read-onlyVariant.
expression.LastSyncTime
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
UsetheLastSyncTimepropertytodeterminehowmuchtimehaselapsedsincethelocalcopyoftheactivedocumentwaslastsynchronizedwiththeservercopy.ChecktheStatuspropertytodeterminewhetherthelocalcopyandtheservercopyareoutofsync.
Iftheactivedocumentisnotconfiguredforsynchronizationbetweenthelocalcopyandtheservercopy,theLastSyncTimepropertyraisesarun-timeerror.
Example
Thefollowingexamplealertstheuseranddisplaysthesyncstatusifmorethan24hourshaveelapsedsincetheLastSyncTime.
DimobjSyncAsOffice.Sync
DimdtmLastSyncAsDate
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
dtmLastSync=CDate(objSync.LastSyncTime)
IfDateDiff("h",dtmLastSync,Now)>24Then
strStatus="Documenthasnotbeensynced"&_
"withinthelast24hours."&vbCrLf&_
"Documentstatus:"&objSync.Status
MsgBoxstrStatus,vbInformation+vbOKOnly,"ErrorInformation"
EndIf
SetobjSync=Nothing
ShowAll
LeftPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
LeftpropertyasitappliestotheAssistantandCommandBarobjects.
SetsorreturnsthehorizontalpositionoftheOfficeAssistantwindow(inpoints),orthedistance(inpixels)ofthecommandbar,fromtheleftedgeofthespecifiedobjectrelativetothescreen.Read/writeLong.
expression.Left
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
LeftpropertyasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
Setorreturnsthehorizontalpositionofthespecifiedcommandbarcontrol(inpixels)relativetotheleftedgeofthescreen.Returnsthedistancefromtheleftsideofthedockingarea.Read-onlyLong.
expression.Left
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Example
AsitappliestotheAssistantandCommandBarobjects.
ThisexampledisplaystheOfficeAssistantandmovesittothespecifiedpositionwithintheapplicationwindow.
WithAssistant
.Visible=True
.Left=300
.Top=300
EndWith
ThisexamplemovesthecommandbarnamedCustomfromitsdockedpositionalongthetopofthewindowtotheleftedgeofthewindow.
SetmyBar=CommandBars("Custom")
WithmyBar
.Position=1
.RowIndex=2
.Left=0
EndWith
LinksPropertyReturnsaSharedWorkspaceLinkscollectionthatrepresentsthelistoflinkssavedinthecurrentsharedworkspace.Read-only.
expression.Links()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Example
Thefollowingexampleliststhelinkssavedinthecurrentsharedworkspace.
DimswsLinksAsOffice.SharedWorkspaceLinks
SetswsLinks=ActiveWorkbook.SharedWorkspace.Links
MsgBox"Thereare"&swsLinks.Count&_
"link(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsLinks=Nothing
LinkSourcePropertyReturnsorsetsthesourceofalinkedcustomdocumentproperty.Read/writeString.
Remarks
Thispropertyappliesonlytocustomdocumentproperties;youcannotuseitwithbuilt-indocumentproperties.
Thesourceofthespecifiedlinkisdefinedbythecontainerapplication.
SettingtheLinkSourcepropertysetstheLinkToContentpropertytoTrue.
Example
Thisexampledisplaysthelinkedstatusofacustomdocumentproperty.Fortheexampletowork,dpmustbeavalidDocumentPropertyobject.
SubDisplayLinkStatus(dpAsDocumentProperty)
DimstatAsString,tfAsString
Ifdp.LinkToContentThen
tf=""
Else
tf="not"
EndIf
stat="Thispropertyis"&tf&"linked"
Ifdp.LinkToContentThen
stat=stat+Chr(13)&"Thelinksourceis"&dp.LinkSource
EndIf
MsgBoxstat
EndSub
LinkToContentPropertyTrueifthevalueofthecustomdocumentpropertyislinkedtothecontentofthecontainerdocument.Falseifthevalueisstatic.Read/writeBoolean.
Remarks
Thispropertyappliesonlytocustomdocumentproperties.Forbuilt-indocumentproperties,thevalueofthispropertyisFalse.
UsetheLinkSourcepropertytosetthesourceforthespecifiedlinkedproperty.SettingtheLinkSourcepropertysetstheLinkToContentpropertytoTrue.
Example
Thisexampledisplaysthelinkedstatusofthecustomdocumentproperty.Fortheexampletowork,dpmustbeavalidDocumentPropertyobject.
SubDisplayLinkStatus(dpAsDocumentProperty)
DimstatAsString,tfAsString
Ifdp.LinkToContentThen
tf=""
Else
tf="not"
EndIf
stat="Thispropertyis"&tf&"linked"
Ifdp.LinkToContentThen
stat=stat+Chr(13)&"Thelinksourceis"&dp.LinkSource
EndIf
MsgBoxstat
EndSub
ShowAll
ListPropertyReturnsorsetsaniteminthecommandbarcomboboxcontrol.Read/writeString.
NoteThispropertyisread-onlyforbuilt-incomboboxcontrols.
expression.List(Index)
expressionRequired.AnexpressionthatreturnsaCommandBarComboBoxobject.
IndexRequiredLong.Thelistitemtobeset.
Example
Thisexamplechecksthefourthlistiteminthecomboboxcontrolwhosecaptionis"StockData"onthecommandbarnamed"Custom."Iftheitemisn’t"ViewNews,"theexampledisplaysamessageadvisingtheuserthatthecomboboxmaybedamagedandaskstheusertoreinstalltheapplication.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
WithCommandBars("Custom").Controls(1)
.AddItem"GetStockQuote",1
.AddItem"ViewChart",2
.AddItem"ViewFundamentals",3
.AddItem"ViewNews",4
.Caption="StockData"
.DescriptionText="ViewDataForStock"
EndWith
IfCommandBars("Custom").Controls(1).List(4)_
<>"ViewNews"Then
MsgBox("StockDataappearstobedamaged."&_
"Pleasereinstallapplication.")
EndIf
ShowAll
ListCountPropertyReturnsthenumberoflistitemsinacommandbarcomboboxcontrol.Read-onlyLong.
Example
Thisexamplechecksthenumberofitemsinthecomboboxonthecommandbarnamed"Custom."Iftherearen’tthreeitemsinthelistthattheprocedureproduces,theexampledisplaysamessageadvisingtheuserthatthecomboboxmaybedamagedandaskstheusertoreinstalltheapplication.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
WithCommandBars("Custom").Controls(1)
.AddItem"GetStockQuote",1
.AddItem"ViewChart",2
.AddItem"ViewFundamentals",3
.Caption="StockData"
.DescriptionText="ViewDataForStock"
EndWith
IfCommandBars("Custom").Controls(1).ListCount_
<>4Then
MsgBox("ComboBoxappearstobedamaged."&_
"Pleasereinstall.")
EndIf
ShowAll
ListHeaderCountPropertyReturnsorsetsthenumberoflistitemsinacommandbarcomboboxcontrolthatappearsabovetheseparatorline.Read/writeLong.
NoteThispropertyisread-onlyforbuilt-incomboboxcontrols.
Remarks
AListHeaderCountpropertyvalueof–1indicatesthatthere'snoseparatorlineinthecomboboxcontrol.
Example
Thisexampleaddsacomboboxcontroltothecommandbarnamed"Custom"andthenaddstwoitemstothecombobox.TheexampleusestheListHeaderCountpropertytodisplayaseparatorlinebetweenFirstItemandSecondIteminthecombobox.Theexamplealsosetsthenumberoflineitems,thewidthofthecombobox,andanemptydefaultforthecombobox.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls.Add(Type:=msoControlComboBox)
WithmyControl
.AddItemText:="FirstItem",Index:=1
.AddItemText:="SecondItem",Index:=2
.DropDownLines=3
.DropDownWidth=75
.ListHeaderCount=1
EndWith
ShowAll
ListIndexPropertyReturnsorsetstheindexnumberoftheselectediteminthelistportionofthecommandbarcomboboxcontrol.Ifnothingisselectedinthelist,thispropertyreturnszero.Read/writeLong.
NoteThispropertyfailswhenappliedtocontrolsotherthanlistcontrols.
Remarks
SettingtheListIndexpropertycausesthespecifiedcontroltoselectthegivenitemandexecutetheappropriateactionintheapplication.
Example
ThisexampleusestheListIndexpropertytodeterminethecorrectsubroutinetorun,basedontheselectioninthecomboboxonthecommandbarnamed“MyCustomBar.”BecausetheprocedureusesListIndex,thetextinthecomboboxcanbeanything.
SubprocessSelection()
DimuserChoiceAsLong
userChoice=CommandBars("MyCustomBar").Controls(1).ListIndex
SelectCaseuserChoice
Case1
chartcourse
Case2
displaygraph
CaseElse
MsgBox("Invalidchoice.Pleasechooseagain.")
EndSelect
EndSub
ShowAll
LocationPropertyReturnsthelocationofthescriptanchorinthespecifiedHTMLdocument.Read-onlyMsoScriptLocation.
MsoScriptLocationcanbeoneoftheseMsoScriptLocationconstants.msoScriptLocationInBodymsoScriptLocationInHead
Remarks
ScripttagsinanHTMLdocumentcanappearanywherebetweenthe<HTML>tagsinthedocument.InMicrosoftWord,Excel,orPowerPoint,onlythescriptanchorslocatedbetweenthe<BODY>tagsarevisible.AdditionalHTMLscriptthatappearsbeforeorafterthe<BODY>tagsisstoredinbutisn’tvisibletotheuser.
TheScriptscollectioncontainsallofthescriptanchorsthatappearinthedocument,whetherinsideoroutsideofthemainbodyofthedocument.UsingtheLocationargumentoftheAddmethod,youcaninsertscriptanchorswithinthe<HEAD>and<BODY>tagsintheHTMLdocument.YoucanalsousetheLocationpropertytodeterminewhereaparticularscriptanchorisstoredwithinthedocument.
Example
ThisexamplecheckstheLocationpropertyofthefirstscriptinworksheetoneintheactiveworkbookanddisplaysthelocationinamessagebox.
IfActiveWorkbook.Worksheets(1).Scripts(1).Location=1Then
MsgBox"Thescriptinlocatedintheheader."
EndIf
IfActiveWorkbook.Worksheets(1).Scripts(1).Location=2Then
MsgBox"Thescriptinlocatedinthebodyoftheworksheet."
EndIf
LookInPropertyReturnsorsetsthefoldertobesearchedduringthespecifiedfilesearch.Read/writeString.
Example
ThisexamplesearchestheMyDocumentsfoldersforallfilesthatbeginwith"Cmd"anddisplaysthenameandlocationofeachfilethat’sfound.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.FileName="cmd*.*"
If.Execute>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
MaskPropertyReturnsanIPictureDispobjectrepresentingthemaskimageofaCommandBarButtonobject.Themaskimagedetermineswhatpartsofthebuttonimagearetransparent.
expression.Mask
expressionRequired.AnexpressionthatreturnsaCommandBarButtonobject.
Remarks
Whenyoucreateanimagethatyouplanonusingasamaskimage,alloftheareasthatyouwanttobetransparentshouldbewhite,andalloftheareasthatyouwanttoshowshouldbeblack.
AlwayssetthemaskafteryouhavesetthepictureforaCommandBarButtonobject.
Example
ThefollowingexamplesetstheimageandmaskofthefirstCommandBarButtonthatthecodereturns.Tomakethiswork,createamaskimageandabuttonimageandsustitutethepathsinthesamplewiththepathstoyourimages.
SubChangeButtonImage()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
SetpicPicture=stdole.StdFunctions.LoadPicture(_
"c:\images\picture.bmp")
SetpicMask=stdole.StdFunctions.LoadPicture(_
"c:\images\mask.bmp")
'Referencethefirstbuttononthefirstcommandbar
'usingaWith...EndWithblock.
WithApplication.CommandBars.FindControl(msoControlButton)
'Changethebuttonimage.
.Picture=picPicture
'Usethesecondimagetodefinetheareaofthe
'buttonthatshouldbetransparent.
.Mask=picMask
EndWith
EndSub
ThefollowingexamplegetstheimageandmaskofthefirstCommandBarButtonthatthecodereturnsandoutputseachofthemtoafile.Tomakethiswork,specifyapathfortheoutputfiles.
SubGetButtonImageAndMask()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
WithApplication.CommandBars.FindControl(msoControlButton)
'GetthebuttonimageandmaskofthisCommandBarButtonobject
SetpicPicture=.Picture
SetpicMask=.Mask
EndWith
'Savethebuttonimageandmaskinafolder.
stdole.SavePicturepicPicture,"c:\image.bmp"
stdole.SavePicturepicMask,"c:\mask.bmp"
EndSub
MatchAllWordFormsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Trueifthefilesearchisexpandedtoincludeallformsofthespecifiedwordcontainedinthebodyofthefile,orinthefile'sproperties.Read/writeBoolean.
Remarks
ThispropertyisavailableonlyifthefileMswds_en.lexhasbeeninstalledandregistered.Notethatthisfileisn'tinstalledaspartofaTypicalsetup.
Example
Thisexamplereturnsallfilesthatcontaintheword"run,""running,""runs,"or"ran"inthebodyofthefile,orinthepropertiesofthefile.TheTextOrPropertypropertysetsthewordtobematched,andlimitsthesearchtoeitherthebodyofthefileorthefileproperties.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.TextOrProperty="run"
.MatchAllWordForms=True
.FileType=msoFileTypeAllFiles
EndWith
MatchTextExactlyPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Trueifthespecifiedfilesearchwillfindonlyfileswhosebodytextorfilepropertiescontaintheexactwordorphrasethatyou'vespecified.Read/writeBoolean.
Example
ThisexamplesearchestheC:\MyDocumentsfolderandreturnsallfilesthatcontaintheword"Run"eitherinthebodytextorinthefileproperties.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.TextOrProperty="Run"
.MatchTextExactly=True
.FileType=msoFileTypeAllFiles
EndWith
MembersPropertyReturnsaSharedWorkspaceMemberscollectionthatrepresentsthelistofmembersinthecurrentsharedworkspace.Read-only.
expression.Members()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Example
Thefollowingexampleliststhemembersinthecurrentsharedworkspace.
DimswsMembersAsOffice.SharedWorkspaceMembers
SetswsMembers=ActiveWorkbook.SharedWorkspace.Members
MsgBox"Thereare"&swsMembers.Count&_
"member(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsMembers=Nothing
ShowAll
MenuAnimationStylePropertyReturnsorsetsthewayacommandbarisanimated.Read/writeMsoMenuAnimation.
MsoMenuAnimationcanbeoneoftheseMsoMenuAnimationconstants.msoMenuAnimationNonemsoMenuAnimationRandommsoMenuAnimationSlidemsoMenuAnimationUnfold
Example
ThisexamplesetsoptionsforallcommandbarsinMicrosoftOffice.
WithCommandBars
.LargeButtons=True
.DisplayTooltips=True
.DisplayKeysInTooltips=True
.MenuAnimationStyle=msoMenuAnimationUnfold
EndWith
ShowAll
ModePropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsthemodalbehavioroftheOfficeAssistantballoon.WhenyoucreateaBalloonobject,thispropertyisinitiallysettomsoModeModal.Read/writeMsoModeType.
MsoModeTypecanbeoneoftheseMsoModeTypeconstants.msoModeAutoDownmsoModeModalmsoModeModeless
Remarks
IftheModepropertyforaballoonissettomsoModeModeless,theusercanworkintheapplicationwhiletheballoonisvisible.IfthepropertyissettomsoModeModal,theusermustdismisstheballoonbeforecontinuingtoworkintheapplication.IfthepropertyissettomsoModeAutoDown,theballoonisdismissedwhentheuserclicksanywhereonthescreen.
IftheModepropertyforaballoonissettomsoModeModelessandavaluefortheCallbackpropertyisnotsupplied,anerroroccurs.TheClosemethodcanonlybeusedintheprocedurespecifiedbytheCallbackpropertywhentheModepropertyissettomsoModeModeless.
Example
Thisexamplecreatesaballoonwithanalerticonthatinstructstheusertoselectaprinter.Becausetheballoonismodeless,theuserhasaccesstoprintercommandswhiletheballoonisvisible.WhentheuserclickstheOKbutton,theprocedurespecifiedintheCallbackpropertyisrun.
WithAssistant.NewBalloon
.Heading="SelectAPrinter"
.Text="Youmustselectaprinterbeforeprinting."
.Icon=msoIconAlert
.CheckBoxes(1).Text="Localprinter"
.CheckBoxes(2).Text="Networkprinter"
.Mode=msoModeModeless
.Callback="ProcessPrinter"
.Show
EndWith
ModifiedPropertyReturnsthedateandtimeatwhichthespecifiedversionoftheshareddocumentwaslastsavedtotheserver.Read-onlyVariant.
expression.Modified
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
Remarks
Anewversioniscreatedontheservereachtimeauseropensthedocumentandisupdatedwhentheusersaveschanges;additionalversionsarenotcreatedeachtimetheusersaveschangestotheopendocument.TheModifiedpropertyoftheactivedocumentversionrepresentsthelasttimetheusersavedchangestotheopendocument.
Example
ThefollowingexampledisplaystheModifieddateandtimealongwithotherpropertiesofeachversionofashareddocument.
DimdlvVersionsAsOffice.DocumentLibraryVersions
DimdlvVersionAsOffice.DocumentLibraryVersion
DimstrVersionInfoAsString
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
strVersionInfo="Thisdocumenthas"&_
dlvVersions.Count&"versions:"&vbCrLf
ForEachdlvVersionIndlvVersions
strVersionInfo=strVersionInfo&_
"-Version#:"&dlvVersion.Index&vbCrLf&_
"-Modifiedby:"&dlvVersion.ModifiedBy&vbCrLf&_
"-Modifiedon:"&dlvVersion.Modified&vbCrLf&_
"-Comments:"&dlvVersion.Comments&vbCrLf
Next
Else
strVersionInfo="Versioningnotenabledforthisdocument."
EndIf
MsgBoxstrVersionInfo,vbInformation+vbOKOnly,"VersionInformation"
SetdlvVersion=Nothing
SetdlvVersions=Nothing
ShowAll
ModifiedByPropertyAsitappliestotheDocumentLibraryVersionobject.
Returnsthenameoftheuserwholastsavedthespecifiedversionoftheshareddocumenttotheserver.Read-onlyString.
expression.ModifiedBy
expressionRequired.AnexpressionthatreturnsaDocumentLibraryVersionobject.
AsitappliestotheSharedWorkspaceFile,SharedWorkspaceLink,andSharedWorkspaceTaskobjects.
Returnsthenameoftheuserwholastmodifiedtheobject.Read-onlyString.
expression.ModifiedBy
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFile,SharedWorkspaceLink,orSharedWorkspaceTaskobject.
Remarks
Forsharedworkspaceobjects,theModifiedBypropertyreturnsthefriendlynamestoredintheNamepropertyoftheDWSMemberobject.
TheSharedWorkspaceFolderandSharedWorkspaceMemberobjectsdonothaveaModifiedByproperty.
Example
AsitappliestotheDocumentLibraryVersionobject.
ThefollowingexampledisplaystheModifiedBynamealongwithotherpropertiesofeachversionofashareddocument.
DimdlvVersionsAsOffice.DocumentLibraryVersions
DimdlvVersionAsOffice.DocumentLibraryVersion
DimstrVersionInfoAsString
SetdlvVersions=ActiveDocument.DocumentLibraryVersions
IfdlvVersions.IsVersioningEnabledThen
strVersionInfo="Thisdocumenthas"&_
dlvVersions.Count&"versions:"&vbCrLf
ForEachdlvVersionIndlvVersions
strVersionInfo=strVersionInfo&_
"-Version#:"&dlvVersion.Index&vbCrLf&_
"-Modifiedby:"&dlvVersion.ModifiedBy&vbCrLf&_
"-Modifiedon:"&dlvVersion.Modified&vbCrLf&_
"-Comments:"&dlvVersion.Comments&vbCrLf
Next
Else
strVersionInfo="Versioningnotenabledforthisdocument."
EndIf
MsgBoxstrVersionInfo,vbInformation+vbOKOnly,"VersionInformation"
SetdlvVersion=Nothing
SetdlvVersions=Nothing
AsitappliestotheSharedWorkspaceFile,SharedWorkspaceLink,andSharedWorkspaceTaskobjects.
Thefollowingexampleliststhefilesinasharedworkspacethatwerelastmodifiedbyusersotherthanthecreatoroftheworkspace.
DimswsFileAsOffice.SharedWorkspaceFile
DimswsOwnerAsOffice.SharedWorkspaceMember
DimstrMemberFilesAsString
SetswsOwner=ActiveWorkbook.SharedWorkspace.Members(1)
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
IfswsFile.ModifiedBy<>swsOwner.NameThen
strMemberFiles=strMemberFiles&swsFile.URL&vbCrLf
EndIf
Next
MsgBox"Thesefileswerelastmodifiedbyotherusers:"&_
vbCrLf&strMemberFiles,_
vbInformation+vbOKOnly,"FilesModifiedbyOtherUsers"
SetswsOwner=Nothing
SetswsFile=Nothing
ModifiedDatePropertyReturnsthedateandtimewhenthesharedworkspaceobjectwaslastmodified.Read-onlyVariant.
expression.ModifiedDate
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheSharedWorkspaceFolderandSharedWorkspaceMemberobjectsdonothaveaModifiedDateproperty.
Example
Thefollowingexamplereturnsalistofsharedworkspacefileswhosedateandtimelastmodifiedisearlierthantoday.
DimswsFileAsOffice.SharedWorkspaceFile
DimdtmMidnightAsDate
DimdtmFileDateAsDate
DimstrOlderFilesAsString
dtmMidnight=CDate(FormatDateTime(Now,vbShortDate)&"12:00:00am")
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
dtmFileDate=swsFile.ModifiedDate
IfdtmFileDate<dtmMidnightThen
strOlderFiles=strOlderFiles&swsFile.URL&vbCrLf
EndIf
Next
MsgBox"Filesnotmodifiedtoday:"&vbCrLf&strOlderFiles,_
vbInformation+vbOKOnly,"OlderFiles"
SetswsFile=Nothing
MouseTipsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantprovidessuggestionsforusingthemouseeffectively.Read/writeBoolean.
Remarks
TheMouseTipspropertycorrespondstotheUsingthemousemoreeffectivelyoptionunderShowtipsaboutontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexamplesetstheOfficeAssistanttoprovidesuggestionsforusingthemouseeffectively.
Assistant.MouseTips=True
MoveWhenInTheWayPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantwindowautomaticallymoveswhenit'sinthewayoftheuser'sworkarea.Forexample,theAssistantwillmoveifit'sinthewayofdraggingordroppingorinthewayofkeystrokeentries.Read/writeBoolean.
Remarks
ThedefaultvalueisTrue.TheMoveWhenInTheWaypropertycorrespondstotheMovewheninthewayoptionintheUsetheOfficeAssistantsectionontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexampledisplaystheOfficeAssistantinaspecificlocationanditsetsseveraloptionsbeforemakingtheAssistantvisibleandactive.
WithAssistant
.On=True
.Visible=True
.Left=400
IfNotMoveWhenInTheWayThenMoveWhenInTheWay=True
.Animation=msoAnimationGetAttentionMajor
EndWith
ShowAll
NamePropertyReturnsorsetsthenameofthespecifiedobject.Read/writeStringfortheCommandBar,DocumentProperty,andSharedWorkspaceobjects;read-onlyStringforallotherobjects.
Remarks
NamepropertyasitappliestotheCommandBarobject.
Thelocalnameofabuilt-incommandbarisdisplayedinthetitlebar(whenthecommandbarisn'tdocked)andinthelistofavailablecommandbars—whereverthatlistisdisplayedinthecontainerapplication.
Forabuilt-incommandbar,theNamepropertyreturnsthecommandbar'sU.S.Englishname.UsetheNameLocalpropertytoreturnthelocalizedname.
IfyouchangethevalueoftheLocalNamepropertyforacustomcommandbar,thevalueofNamechangesaswell,andviceversa.
NamepropertyasitappliestotheSharedWorkspaceMemberobject.
TheNamepropertyoftheSharedWorkspaceMemberobjectreturnsthefriendlynameforthesharedworkspacemember,asspecifiedintheDisplayNameargumentoftheAddmethodoftheSharedWorkspaceMemberscollection.TheSharedWorkspaceMemberobjecthasotherpropertiesthatreturnthemember'sDomainNameorEmail.
Example
AsitappliestotheCommandBarobject.
Thisexamplesearchesthecollectionofcommandbarsforthecommandbarnamed"Custom."Ifthiscommandbarisfound,theexamplemakesitvisible.
foundFlag=False
ForEachbarInCommandBars
Ifbar.Name="Custom"Then
foundFlag=True
bar.Visible=True
EndIf
Next
IfNotfoundFlagThen
MsgBox"'Custom'barisn'tincollection."
Else
MsgBox"'Custom'barisnowvisible."
EndIf
AsitappliestotheDocumentPropertyobject.
Thisexampledisplaysthename,type,andvalueofadocumentproperty.YoumustpassavalidDocumentPropertyobjecttotheprocedure.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
ShowAll
NameLocalPropertyReturnsthenameofabuilt-incommandbarasit'sdisplayedinthelanguageversionofthecontainerapplication,orreturnsorsetsthenameofacustomcommandbar.Read/writeString.
NoteIfyouattempttosetthispropertyforabuilt-incommandbar,anerroroccurs.
Remarks
Thelocalnameofabuilt-incommandbarisdisplayedinthetitlebar(whenthecommandbarisn'tdocked)andinthelistofavailablecommandbars,whereverthatlistisdisplayedinthecontainerapplication.
IfyouchangethevalueoftheLocalNamepropertyforacustomcommandbar,thevalueofNamechangesaswell,andviceversa.
Example
Thisexampledisplaysthenameandlocalizednameofthefirstcommandbarinthecontainerapplication.
WithCommandBars(1)
MsgBox"Thenameofthecommandbaris"&.Name
MsgBox"Thelocalizednameofthecommandbaris"&.NameLocal
EndWith
NewBalloonPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
CreatesanOfficeAssistantballoon.ReturnsaBalloonobject.Read-only.
Example
Thisexamplecreatesaballoonwithaheading,text,andthreeregionchoices,andthendisplaysit.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectoneormoreregions"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
NotesPropertyReturnsorsetstheoptionalnotesassociatedwithasharedworkspacelink.Read/writeString.
expression.Notes
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceLinkobject.
Thefollowingexamplecreatesalistofallthesharedworkspacelinksthatcontaintheword"building"intheNotesfield.
DimstrBuildingLinksAsString
DimswsLinkAsOffice.SharedWorkspaceLink
ForEachswsLinkInActiveWorkbook.SharedWorkspace.Links
IfInStr(swsLink.Notes,"building",vbTextCompare)>0Then
strBuildingLinks=strBuildingLinks&swsLink.Description&vbCrLf
EndIf
Next
MsgBox"BuildingLinks:"&vbCrLf&strBuildingLinks,_
vbInformation+vbOKOnly,"BuildingLinksinSharedWorkspace"
ObjectPropertySetsorreturnstheobjectthatisthebasisforthespecifiedCOMAddInobject.Read/writeObject.
Remarks
ThispropertyisprimarilyusedforenablingoneCOMAddIntocommunicatewithanotherCOMAddIn.
Example
ThefollowingexamplereturnstheobjectassociatedwiththeCOMaddinmsodraa9.ShapeSelect.
DimobjBaseObjectAsObject
SetobjBaseObject=_
Application.COMAddIns.Item("msodraa9.ShapeSelect")._
Object
ShowAll
OLEMenuGroupPropertyReturnsorsetsthemenugroupthatthespecifiedcommandbarpop-upcontrolbelongstowhenthemenugroupsoftheOLEserveraremergedwiththemenugroupsofanOLEclient(thatis,whenanobjectofthecontainerapplicationtypeisembeddedinanotherapplication).Read/writeMsoOLEMenuGroup.
MsoOLEMenuGroupcanbeoneoftheseMsoOLEMenuGroupconstants.msoOLEMenuGroupContainermsoOLEMenuGroupEditmsoOLEMenuGroupFilemsoOLEMenuGroupHelpmsoOLEMenuGroupNonemsoOLEMenuGroupObjectmsoOLEMenuGroupWindow
NoteThispropertyisread-onlyforbuilt-incontrols.
Remarks
Thispropertyisintendedtoallowadd-inapplicationstospecifyhowtheircommandbarcontrolswillberepresentedintheOfficeapplication.Ifeitherthecontainerortheserverdoesnotimplementcommandbars,normalOLEmenumergingwilloccur:themenubarwillbemerged,aswellasallthetoolbarsfromtheserver,andnoneofthetoolbarsfromthecontainer.Thispropertyisrelevantonlyforpop-upcontrolsonthemenubarbecausemenusaremergedonthebasisoftheirmenugroupcategory.
Ifbothofthemergingapplicationsimplementcommandbars,commandbarcontrolsaremergedaccordingtotheOLEUsageproperty.
Example
ThisexamplecheckstheOLEMenuGrouppropertyofanewcustompop-upcontrolonthecommandbarnamed“Custom”andsetsthepropertytomsoOLEMenuGroupNone.
SetmyControl=CommandBars("Custom").Controls_
.Add(Type:=msoControlPopup,Temporary:=False)
myControl.OLEMenuGroup=msoOLEMenuGroupNone
ShowAll
OLEUsagePropertyReturnsorsetstheOLEclientandOLEserverrolesinwhichacommandbarcontrolwillbeusedwhentwoMicrosoftOfficeapplicationsaremerged.Read/writeMsoControlOLEUsage.
MsoControlOLEUsagecanbeoneoftheseMsoControlOLEUsageconstants.msoControlOLEUsageBothmsoControlOLEUsageClientmsoControlOLEUsageNeithermsoControlOLEUsageServer
Remarks
Thispropertyisintendedtoallowyoutospecifyhowindividualadd-inapplications'commandbarcontrolswillberepresentedinoneOfficeapplicationwhenitismergedwithanotherOfficeapplication.Ifboththeclientandserverimplementcommandbars,thecommandbarcontrolsareembeddedintheclientcontrolbycontrol.Customcontrolsmarkedasclient-only(orneitherclientnorserver)aredroppedfromtheserver,andcontrolsmarkedasserver-only(orneitherservernorclient)aredroppedfromtheclient.Theremainingcontrolsaremerged.
Ifoneofthemergingapplicationsisn'tanOfficeapplication,normalOLEmenumergingisused,whichiscontrolledbytheOLEMenuGroupproperty.
Example
ThisexampleaddsanewbuttontothecommandbarnamedTools,andsetsitsOLEUsageproperty.
SetmyControl=CommandBars("Tools").Controls_
.Add(Type:=msoControlButton,Temporary:=True)
myControl.OLEUsage=msoControlOLEUsageNeither
OnPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantisenabled.Read/writeBoolean.
Example
ThisexampledisablestheOfficeAssistant,displaysamessageboxthataskstheuserwhethertheAssistantshouldbeenabled,andenablestheAssistantiftheuserclicksYes.IftheusersenablestheAssistant,theAssistantappearsandperformstheanimationmsoAnimationGreeting.
Assistant.On=False
IfMsgBox("EnableOfficeAssistant?",_
vbYesNo,"AssistantisOff")=vbYesThen
Assistant.On=True
Assistant.Visible=True
Assistant.Animation=_
msoAnimationGetAttentionMajor
EndIf
ShowAll
OnActionPropertyReturnsorsetsthenameofaVisualBasicprocedurethatwillrunwhentheuserclicksorchangesthevalueofacommandbarcontrol.Read/writeString.
NoteThecontainerapplicationdetermineswhetherthevalueisavalidmacroname.
Example
Thisexampleaddsacommandbarcontroltothecommandbarnamed"Custom".Theprocedurenamed"MySub"willruneachtimethecontrolisclicked.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls_
.Add(Type:=msocontrolButton)
WithmyControl
.FaceId=2
.OnAction="MySub"
EndWith
myBar.Visible=True
Thisexampleaddsacommandbarcontroltothecommandbarnamed"Custom".TheCOMaddinnamed"FinanceAddIn"willruneachtimethecontrolisclicked.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls_
.Add(Type:=msocontrolButton)
WithmyControl
.FaceId=2
.OnAction="!<FinanceAddIn>"
EndWith
myBar.Visible=True
ParameterPropertyReturnsorsetsastringthatanapplicationcanusetoexecuteacommand.Read/writeString.
Remarks
Ifthespecifiedparameterissetforabuilt-incontrol,theapplicationcanmodifyitsdefaultbehaviorifitcanparseandusethenewvalue.Iftheparameterissetforcustomcontrols,itcanbeusedtosendinformationtoVisualBasicprocedures,oritcanbeusedtoholdinformationaboutthecontrol(similartoasecondTagpropertyvalue).
Example
Thisexampleassignsanewparametertoacontrolandsetsthefocustothenewbutton.
SetmyControl=CommandBars("Custom").Controls(4)
WithmyControl
.Copy,1
.Parameter="2"
.SetFocus
EndWith
ParentPropertyReturnstheParentobjectforthespecifiedobject.Read-only.
Example
Thisexampledisplaysthenameoftheparentobjectforadocumentproperty.YoumustpassavalidDocumentPropertyobjecttotheprocedure.
SubDisplayParent(dpasDocumentProperty)
MsgBoxdp.Parent.Name
EndSub
PathPropertyReturnsaStringindicatingthefullpathofaScopeFolderobject.Read-only.
expression.Path
expressionRequired.AnexpressionthatreturnsaScopeFolderobject.
Example
ThefollowingexampledisplaystherootpathofeachdirectoryinMyComputer.Toretrievethisinformation,theexamplefirstgetstheScopeFolderobjectattherootofMyComputer.ThepathofthisScopeFolderwillalwaysbe"*".AswithallScopeFolderobjects,therootobjectcontainsaScopeFolderscollection.ThisexampleloopsthroughthisScopeFolderscollectionanddisplaysthepathofeachScopeFolderobjectinit.ThepathsoftheseScopeFolderobjectswillbe"A:\","C:\",etc.
SubDisplayRootScopeFolders()
'Declarevariablesthatreferencea
'SearchScopeandaScopeFolderobject.
DimssAsSearchScope
DimsfAsScopeFolder
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection
'anddisplayalloftherootScopeFolderscollectionsin
'theMyComputerscope.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
'LoopthrougheachScopeFoldercollectionsin
'theScopeFolderscollectionofthe
'SearchScopeobjectanddisplaythepath.
ForEachsfInss.ScopeFolder.ScopeFolders
MsgBox"Path:"&sf.Path
Nextsf
CaseElse
EndSelect
Nextss
EndWith
EndSub
ShowAll
PermissionPropertyReturnsorsetsaLongvaluerepresentingthepermissionsontheactivedocumentassignedtotheuserassociatedwiththespecifiedUserPermissionobject.Read/writeLong.ThePermissionpropertycanbeoneoracombinationofMsoPermissionconstants.
MsoPermissioncanbeoneofthefollowingmsoPermissionconstants.msoPermissionView(1)msoPermissionRead(1)msoPermissionEdit(2)msoPermissionSave(4)msoPermissionExtract(8)msoPermissionChange(15)msoPermissionPrint(16)msoPermissionObjectModel(32)msoPermissionFullControl(64)
expression.Permission
expressionRequired.AnexpressionthatreturnsaUserPermissionobject.
Remarks
TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.ThePermissionpropertyreturnsthesetofuserpermissionsdeterminedbythespecifiedUserPermissionobject.Whilesomepermissionsgrantedthroughtheuserinterface(suchasmsoPermissionPrint)applytoallusers,youcanusetheUserPermissionobjecttoassignthemonaper-userbasiswithper-userexpirationdates.
ThemsoPermissionViewormsoPermissionReadoptioncorrespondstotheRead...optionintheuserinterface.ThemsoPermissionExtractoptioncorrespondstotheAllowuserswithreadaccesstocopycontentoptionintheuserinterface.ThemsoPermissionChangeoptioncorrespondstotheChange...optionintheuserinterface.ThemsoPermissionChangeoptionrepresentsthesumofmsoPermissionView+msoPermissionEdit+msoPermissionSave+msoPermissionExtractandallowsuserstoview,edit,copy,andsave,butnotprint,thedocument.ThemsoPermissionPrintoptioncorrespondstothePrintcontentoptionintheuserinterface.ThemsoPermissionObjectModeloptioncorrespondstotheAccesscontentprogrammaticallyoptionintheuserinterfaceandallowsuserstoaccessthedocumentprogrammaticallythroughitsobjectmodel.UserswithoutmsoPermissionObjectModelcannotusetheobjectmodeltodeterminetheirownrights,sinceprogrammaticaccessisdisabled.
Example
ThefollowingexampleusesthebitwiseAndoperatorwiththePermissionpropertyandanmsoPermissionconstanttodeterminewhethertheseconduserhaspermissiontosavetheactivedocument.
DimirmPermissionAsOffice.Permission
DimirmUserPermAsOffice.UserPermission
SetirmPermission=ActiveWorkbook.Permission
SetirmUserPerm=irmPermission.Item(2)
IfirmUserPerm.PermissionAndOffice.msoPermissionSaveThen
MsgBox"User"&irmUserPerm.UserId&_
"haspermissiontosavethisdocument.",_
vbInformation+vbOKOnly,"IRMInformation"
Else
MsgBox"User"&irmUserPerm.UserId&_
"doesNOThavepermissiontosavethisdocument.",_
vbInformation+vbOKOnly,"IRMInformation"
EndIf
SetirmUserPerm=Nothing
SetirmPermission=Nothing
PermissionFromPolicyPropertyReturnsaBooleanvaluethatindicateswhetherapermissionpolicyhasbeenappliedtotheactivedocument.Read-onlyBoolean.
expression.PermissionFromPolicy
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
MicrosoftOffice2003InformationRightsManagementsupportstheuseofadministrativepermissionpolicieswhichlistusersandgroupsandtheirdocumentpermissions.ThePermissionFromPolicypropertyreturnsaBooleanvaluethatindicateswhetherapermissionpolicywasappliedtotheactivedocumentthelasttimepermissionswereenabledonthedocument.
ThePermissionFromPolicypropertyalwaysreturnsFalsewhencheckedbyanon-ownerofthedocument,evenwhentheuserhasobjectmodelpermissions.
Example
Thefollowingexampledisplayspermissionpolicyinformationabouttheactivedocument.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."&vbCrLf&_
"Defaultpolicyname:"&irmPermission.PolicyName&vbCrLf&_
"Defaultpolicydescription:"&irmPermission.PolicyDescription
EndIf
Else
strIRMInfo="PermissionareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
PicturePropertyReturnsanIPictureDispobjectrepresentingtheimageofaCommandBarButtonobject.
expression.Picture
expressionRequired.AnexpressionthatreturnsaCommandBarButtonobject.
Remarks
Whenyouchangetheimageonabutton,youwillalsowanttousetheMaskpropertytosetamaskimage.Themaskimagedetermineswhichpartsofthebuttonimagearetransparent.AlwayssetthemaskafteryouhavesetthepictureforaCommandBarButtonobject.
NoteTheimagesfortheViewMicrosoftApplicationandInsertItembuttonsontheStandardtoolbarintheVisualBasicEditorcannotbechanged.
Example
ThefollowingexamplesetstheimageandmaskofthefirstCommandBarButtonthatthecodereturns.Tomakethiswork,createamaskimageandabuttonimageandsubstitutethepathsinthesamplewiththepathstoyourimages.
SubChangeButtonImage()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
SetpicPicture=stdole.StdFunctions.LoadPicture(_
"c:\images\picture.bmp")
SetpicMask=stdole.StdFunctions.LoadPicture(_
"c:\images\mask.bmp")
'Referencethefirstbuttononthefirstcommandbar
'usingaWith...EndWithblock.
WithApplication.CommandBars.FindControl(msoControlButton)
'Changethebuttonimage.
.Picture=picPicture
'Usethesecondimagetodefinetheareaofthe
'buttonthatshouldbetransparent.
.Mask=picMask
EndWith
EndSub
ThefollowingexamplegetstheimageandmaskofthefirstCommandBarButtonthatthecodereturnsandoutputseachofthemtoafile.Tomakethiswork,specifyapathfortheoutputfiles.
SubGetButtonImageAndMask()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
WithApplication.CommandBars.FindControl(msoControlButton)
'GetthebuttonimageandmaskofthisCommandBarButtonobject.
SetpicPicture=.Picture
SetpicMask=.Mask
EndWith
'Savethebuttonimageandmaskinafolder.
stdole.SavePicturepicPicture,"c:\image.bmp"
stdole.SavePicturepicMask,"c:\mask.bmp"
EndSub
PolicyDescriptionPropertyReturnsthedescriptionofthepermissionspolicyappliedtotheactivedocument.Read-onlyString.
expression.PolicyDescription()
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
MicrosoftOfficeInformationRightsManagementsupportstheuseofadministrativepermissionpolicieswhichlistusersandgroupsandtheirdocumentpermissions.ThePolicyDescriptionpropertyreturnsthedescriptionofthepolicyappliedtotheactivedocument,oradefaultvalueifapolicywasnotused.
Example
Thefollowingexampledisplayspermissionpolicyinformationabouttheactivedocument.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."&vbCrLf&_
"Defaultpolicyname:"&irmPermission.PolicyName&vbCrLf&_
"Defaultpolicydescription:"&irmPermission.PolicyDescription
EndIf
Else
strIRMInfo="PermissionareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
PolicyNamePropertyReturnsthenameofthepermissionspolicyappliedtotheactivedocument.Read-onlyString.
expression.PolicyName
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
MicrosoftOfficeInformationRightsManagementsupportstheuseofadministrativepermissionpolicieswhichlistusersandgroupsandtheirdocumentpermissions.ThePolicyNamepropertyreturnsthenameofthepolicyappliedtotheactivedocument,oradefaultvalueifapolicywasnotused.
Example
Thefollowingexampledisplayspermissionpolicyinformationabouttheactivedocument.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."&vbCrLf&_
"Defaultpolicyname:"&irmPermission.PolicyName&vbCrLf&_
"Defaultpolicydescription:"&irmPermission.PolicyDescription
EndIf
Else
strIRMInfo="PermissionareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
ShowAll
PositionPropertyReturnsorsetsthepositionofacommandbar.Read/writeMsoBarPosition.
MsoBarPositioncanbeoneoftheseMsoBarPositionconstants.msoBarBottommsoBarFloatingmsoBarLeftmsoBarMenuBarmsoBarPopupmsoBarRightmsoBarTop
Example
Thisexamplestepsthroughthecollectionofcommandbars,dockingthecustomcommandbarsatthebottomoftheapplicationwindowanddockingthebuilt-incommandbarsatthetopofthewindow.
ForEachbarInCommandBars
Ifbar.Visible=TrueThen
Ifbar.BuiltInThen
bar.Position=msoBarTop
Else
bar.Position=msoBarBottom
EndIf
EndIf
Next
ShowAll
PriorityPropertyAsitappliestotheCommandBarButton,CommandBarComboBox,
andCommandBarControlobjects.
Returnsorsetsthepriorityofacommandbarcontrol.Acontrol'sprioritydetermineswhetherthecontrolcanbedroppedfromadockedcommandbarifthecommandbarcontrolscan'tfitinasinglerow.Controlsthatcan'tfitinasinglerowdropoffcommandbarsfromrighttoleft.Read/writeLong.
Remarks
Validprioritynumbersare0(zero)through7andthedefaultvalueis3.Apriorityof1meansthatthecontrolcannotbedroppedfromatoolbar.Otherpriorityvaluesareignored.
ThePrioritypropertyisnotusedbycommandbarcontrolsthataremenuitems.
AsitappliestotheSharedWorkspaceTaskobject.
Returnsorsetsthestatusofthespecifiedsharedworkspacetask.Read/writemsoSharedWorkspaceTaskPriority.
MsoSharedWorkspaceTaskPrioritycanbeoneofthefollowingmsoSharedWorkspaceTaskPriorityconstants.msoSharedWorkspaceTaskPriorityHigh(1)msoSharedWorkspaceTaskPriorityLow(3)msoSharedWorkspaceTaskPriorityNormal(2)
expression.Priority
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTaskobject.
Remarks
Thesharedworkspacetaskschemaontheservercanbecustomized.CustomizationoftheschemamayaffectthetaskpriorityenumerationwhentheAddorSavemethodiscalled.Prioritypropertyvaluesaremappedasfollows:
Downloadedvalue1ismappedtomsoSharedWorkspaceTaskPriority1(msoSharedWorkspaceTaskPriorityHigh).Downloadedvalues2throughN-1aremappedtomsoSharedWorkspaceTaskPriority2(msoSharedWorkspaceTaskPriorityNormal).DownloadedvalueNismappedtomsoSharedWorkspaceTaskPriority3(msoSharedWorkspaceTaskPriorityLow).Uploadedenumerationvalues1through3aremappedtoschemavalues1through3.Ifauser-specifiedvaluedoesnotmaptoanyvaluedefinedintheschema,theuser-specifiedvalueissilentlyignoredandtheStatuspropertyisnotupdatedontheserver.
Example
AsitappliestotheCommandBarButton,CommandBarComboBox,andCommandBarControlobject.
Thisexamplemovesacontrolandassignsitapriorityof5sothatitwilllikelybedroppedfromthecommandbarifthecontrolsdon'tallfitinonerow.
Setallcontrols=CommandBars("Custom").Controls
ForEachctrlInallControls
Ifctrl.Type=msoControlComboBoxThen
Withctrl
.MoveBefore:=7
.Tag="Selectionbox"
.Priority=5
EndWith
ExitFor
EndIf
Next
AsitappliestotheSharedWorkspaceTaskobject.
Thefollowingexampleraisesthepriorityofeachtaskinthesharedworkspacebyonestep,unlessthetaskpriorityisalreadysettoHigh,anduploadsthechangestotheserver.(Highpriorityisthelowestvalueintheenumeration.)
DimswsTaskAsOffice.SharedWorkspaceTask
DimlngTaskPriorityAsMsoSharedWorkspaceTaskPriority
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
lngTaskPriority=swsTask.Priority
IflngTaskPriority>msoSharedWorkspaceTaskPriorityHighThen
swsTask.Priority=lngTaskPriority-1
swsTask.Save
EndIf
Next
SetswsTask=Nothing
PrivatePropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ReturnsorsetsanintegerthatidentifiestheOfficeAssistantballoonthatinitiatedthecallbackprocedure.Read/writeLong.
Remarks
Thispropertyishelpfulifyourunthesamecallbackprocedurefrommorethanoneballoon.
Example
ThisexampleidentifiestheOfficeAssistantballoonbysettingthePrivatepropertyto129.
SetprinterOrientation=Assistant.NewBalloon
WithprinterOrientation.Heading="Printportraitorlandscape?"
.Text="ClickOKwhenyou'veselectedthe"&_
"printerorientation."
.Labels(1).Text="Portrait"
.Labels(2).Text="Landscape"
.BalloonType=msoBalloonTypeButtons
.Mode=msoModeModeless
.Button=msoButtonSetOK
.Private=129
.Callback="PortraitOrLandscape"
.Show
EndWith
ProgIdPropertyReturnstheprogrammaticidentifier(ProgID)forthespecifiedCOMAddInobject.Read-onlyString.
Example
ThefollowingexampledisplaystheProgIDandGUIDforCOMadd-inoneinamessagebox.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
PropertyTestsPropertyReturnsthePropertyTestscollectionthatrepresentsallthesearchcriteriaforafilesearch.Read-only.
Forinformationaboutreturningasinglememberofacollection,seeReturninganObjectfromaCollection.
Example
Thisexampledisplaysallthesearchcriteriaforthefirstpropertytestinthecollection.
WithApplication.FileSearch.PropertyTests(1)
myString="Thisisthesearchcriteria:"_
&"Thenameis:"&.Name&".Theconditionis:"_
&.Condition
If.Value<>""Then
myString=myString&".Thevalueis:"&.Value
If.SecondValue<>""Then
myString=myString_
&".Thesecondvalueis:"_
&.SecondValue&",andtheconnectoris"_
&.Connector
EndIf
EndIf
MsgBoxmyString
EndWith
ProportionalFontPropertySetsorreturnstheproportionalfontsettinginthehostapplication.Read/writeString.
Remarks
WhenyousettheProportionalFontproperty,thehostapplicationdoesnotcheckthevalueforvalidity.
Example
ThisexamplesetstheproportionalfontandproportionalfontsizefortheEnglish/WesternEuropean/OtherLatinScriptcharactersetintheactiveapplication.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFont="Tahoma"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFontSize=14.5
ProportionalFontSizePropertySetsorreturnstheproportionalfontsizesettinginthehostapplication,inpoints.Read/writeSingle.
Remarks
WhenyousettheProportionalFontSizeproperty,thehostapplicationdoesnotcheckthevalueforvalidity.Ifyouenteraninvalidvalue,suchasanonnumber,thehostapplicationsetsthesizeto0points.Youcanenterhalf-pointsizes;ifyouenterotherfractionalpointsizes,theyareroundedupordowntothenearesthalf-point.
Example
ThisexamplesetstheproportionalfontandproportionalfontsizefortheEnglish/WesternEuropean/OtherLatinScriptcharactersetintheactiveapplication.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFont="Tahoma"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFontSize=14.5
ShowAll
ProtectionPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Returnsorsetsthewayacommandbarisprotectedfromusercustomization.Read/writeMsoBarProtection.
MsoBarProtectioncanbeoneoftheseMsoBarProtectionconstants.msoBarNoChangeDockmsoBarNoChangeVisiblemsoBarNoCustomizemsoBarNoHorizontalDockmsoBarNoMovemsoBarNoProtectionmsoBarNoResizemsoBarNoVerticalDock
Remarks
UsingtheconstantmsoBarNoCustomizepreventsusersfromaccessingtheAddorRemoveButtonsmenu(thismenuenablesuserstocustomizeatoolbar).
Example
Thisexamplestepsthroughthecollectionofcommandbarstofindthecommandbarnamed"Forms."Ifthiscommandbarisfound,it'sdockingstateisprotectedandit'smadevisible.
foundFlag=False
Fori=1ToCommandBars.Count
IfCommandBars(i).Name="Forms"Then
CommandBars(i).Protection=msoBarNoChangeDock
CommandBars(i).Visible=True
foundFlag=True
EndIf
Next
IfNotfoundFlagThen
MsgBox"'Forms'commandbarisnotinthecollection."
EndIf
ReducedPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantwindowappearsinitssmallersize.Read/writeBoolean.
Remarks
ThispropertyisnotusedinMicrosoftOffice.
Example
ThisexampledisplaystheOfficeAssistantinaspecificlocationanditsetsseveraloptionsbeforemakingtheAssistantvisible.
WithAssistant
.Reduced=True
.Left=400
.MoveWhenInTheWay=True
.TipOfDay=True
.Visible=True
.Animation=msoAnimationGreeting
EndWith
RequestPermissionURLPropertyReturnsorsetsthefileorwebsiteURLtovisitortheemailaddresstocontactforuserswhoneedadditionalpermissionsontheactivedocument.Read/writeString.
expression.RequestPermissionURL
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
TheRequestPermissionURLsettingcorrespondstotheUserscanrequestadditionalpermissionsfromoptioninthepermissionsuserinterface.UsetheRequestPermissionURLpropertytospecifyafile,awebsite,oranemailcontactfromwhichuserscanrequest,orlearnhowtorequest,additionalpermissionsontheactivedocument,forexample:
Awebaddress:http://companyserver/request_permissions.aspAfile:\\companyserver\share\requesting_permissions.txtAnemailaddress:mailto:[email protected]?Subject=Request%20permissions
Example
Thefollowingexampledisplaysinformationaboutthepermissionssettingsoftheactivedocument,includingtheRequestPermissionURLsetting.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
strIRMInfo=strIRMInfo&"Viewintrustedbrowser:"&_
irmPermission.EnableTrustedBrowser&vbCrLf&_
"Documentauthor:"&irmPermission.DocumentAuthor&vbCrLf&_
"Userswithpermissions:"&irmPermission.Count&vbCrLf&_
"Cachelicenseslocally:"&irmPermission.StoreLicenses&vbCrLf&_
"RequestpermissionURL:"&irmPermission.RequestPermissionURL&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Defaultpermissionsapplied."
EndIf
Else
strIRMInfo="PermissionsareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
RowCountPropertyReturnsaLongthatrepresentsthenumberofrecordsinthespecifieddatasource.Read-only.
expression.RowCount
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexampleaddsanewfilterthatremovesallrecordswithablankRegionfieldandthenappliesthefiltertotheactivepublication.
SubOfficeFilters()
DimappOfficeAsOfficeDataSourceObject
DimappFiltersAsODSOFilters
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
SetappFilters=appOffice.Filters
MsgBoxappOffice.RowCount
appFilters.AddColumn:="Region",Comparison:=msoFilterComparisonEqual,_
Conjunction:=msoFilterConjunctionAnd,bstrCompareTo:="WA"
appOffice.ApplyFilter
MsgBoxappOffice.RowCount
EndSub
ShowAll
RowIndexPropertyReturnsorsetsthedockingorderofacommandbarinrelationtoothercommandbarsinthesamedockingarea.Canbeanintegergreaterthanzero,oreitherofthefollowingMsoBarRowconstants:msoBarRowFirstormsoBarRowLast.Read/writeLong.
Remarks
Severalcommandbarscansharethesamerowindex,andcommandbarswithlowernumbersaredockedfirst.Iftwoormorecommandbarssharethesamerowindex,thecommandbarmostrecentlyassignedwillbedisplayedfirstinitsgroup.
Example
Thisexampleadjuststhepositionofthecommandbarnamed"Custom"bymovingittotheleft110pixelsmorethanthedefault,anditmakesthiscommandbarthefirsttobedockedbychangingitsrowindextomsoBarRowFirst.
SetmyBar=CommandBars("Custom")
WithmyBar
.RowIndex=msoBarRowFirst
.Left=140
EndWith
UnsupportedLanguageElementYouhaverequestedHelpforalanguageelementthatisnotsupported.
ScopeFolderPropertyReturnsaScopeFolderobject.
expression.ScopeFolder
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaystherootpathofeachdirectoryinMyComputer.Toretrievethisinformation,theexamplefirstgetstheScopeFolderobjectattherootofMyComputer.ThepathofthisScopeFolderwillalwaysbe"*".AswithallScopeFolderobjects,therootobjectcontainsaScopeFolderscollection.ThisexampleloopsthroughthisScopeFolderscollectionanddisplaysthepathofeachScopeFolderobjectinit.ThepathsoftheseScopeFolderobjectswillbe"A:\","C:\",etc.
SubDisplayRootScopeFolders()
'Declarevariablesthatreferencea
'SearchScopeandaScopeFolderobject.
DimssAsSearchScope
DimsfAsScopeFolder
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection
'anddisplayalloftherootScopeFolderscollectionsin
'theMyComputerscope.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
'LoopthrougheachScopeFolderobjectin
'theScopeFolderscollectionofthe
'SearchScopeobjectanddisplaythepath.
ForEachsfInss.ScopeFolder.ScopeFolders
MsgBox"Path:"&sf.Path
Nextsf
CaseElse
EndSelect
Nextss
EndWith
EndSub
ScopeFoldersPropertyReturnsaScopeFolderscollection.TheitemsinthiscollectioncorrespondtothesubfoldersoftheparentScopeFolderobject.
expression.ScopeFolders
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaystherootpathofeachdirectoryinMyComputer.Toretrievethisinformation,theexamplefirstgetstheScopeFolderobjectattherootofMyComputer.ThepathofthisScopeFolderwillalwaysbe"*".AswithallScopeFolderobjects,therootobjectcontainsaScopeFolderscollection.ThisexampleloopsthroughthisScopeFolderscollectionanddisplaysthepathofeachScopeFolderobjectinit.ThepathsoftheseScopeFolderobjectswillbe"A:\","C:\",etc.
SubDisplayRootScopeFolders()
'Declarevariablesthatreferencea
'SearchScopeandaScopeFolderobject.
DimssAsSearchScope
DimsfAsScopeFolder
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection
'anddisplayalloftherootScopeFolderscollectionsin
'theMyComputerscope.
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
'LoopthrougheachScopeFolderobjectin
'theScopeFolderscollectionofthe
'SearchScopeobjectanddisplaythepath.
ForEachsfInss.ScopeFolder.ScopeFolders
MsgBox"Path:"&sf.Path
Nextsf
CaseElse
EndSelect
Nextbss
EndWith
EndSub
ScriptTextPropertySetsorreturnsthetextcontainedinablockofscript.Read/writeString.
Remarks
TheMicrosoftOfficehostapplicationdoesn’tcheckthesyntaxofthescript.TheScriptTextpropertyisthedefaultpropertyfortheScriptobject.
Example
Thisexamplesetsthetextofthefirstscriptinworksheetoneintheactiveworkbook.
ActiveWorkbook.Worksheets(1).Scripts(1).ScriptText=_
"MsgBox""NewScriptText"""
SearchFoldersPropertyReturnsaSearchFolderscollection.
expression.SearchFolders
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysthecurrentnumberofScopeFolderobjectsintheSearchFolderscollection.SeetheSearchFolderscollectiontopicforamoredetailedexample.
MsgBox"NumberofScopeFolderobjectsintheSearchFolderscollection:"&_
Application.FileSearch.SearchFolders.Count
SearchScopesPropertyReturnsaSearchScopescollection.
expression.SearchScopes
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysallofthecurrentlyavailableSearchScopeobjectsintheSearchScopescollection.
SubDisplayAvailableScopes()
'Declareavariablethatreferencesa
'SearchScopeobject.
DimssAsSearchScope
'UseaWith...EndWithblocktoreferencethe
'FileSearchobject.
WithApplication.FileSearch
'LoopthroughtheSearchScopescollection
ForEachssIn.SearchScopes
SelectCasess.Type
CasemsoSearchInMyComputer
MsgBox"MyComputerisanavailablesearchscope."
CasemsoSearchInMyNetworkPlaces
MsgBox"MyNetworkPlacesisanavailablesearchscope."
CasemsoSearchInOutlook
MsgBox"Outlookisanavailablesearchscope."
CasemsoSearchInCustom
MsgBox"Acustomsearchscopeisavailable."
CaseElse
MsgBox"Can'tdeterminesearchscope."
EndSelect
Nextss
EndWith
EndSub
SearchSubFoldersPropertyTrueifthesearchincludesallthesubfoldersinthefolderspecifiedbytheLookInproperty.Read/writeBoolean.
Example
ThisexamplesearchestheMyDocumentsfolderandallofitssubfoldersforallfileswhosenamesbeginwith"Cmd."Theexamplealsodisplaysthenameandlocationofeachfilethat'sfound.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.FileName="cmd*"
If.Execute()>0Then
MsgBox"Therewere"&.FoundFiles.Count&_
"file(s)found."
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
Nexti
Else
MsgBox"Therewerenofilesfound."
EndIf
EndWith
SearchWhenProgrammingPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantdisplaysapplicationandprogrammingHelpwhiletheuserisworkinginVisualBasic.Read/writeBoolean.
Remarks
ThedefaultvalueisFalse.SearchWhenProgrammingpropertycorrespondstotheSearchforbothproductandprogramminghelpwhenprogrammingoptionintheUsetheOfficeAssistantsectionontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexampleallowstheusertosearchbothapplicationandprogramminghelpwhileworkinginVisualBasic.
Assistant.SearchWhenProgramming=True
SecondValuePropertyReturnsanoptionalsecondvaluepropertytest(asinarange)forthefilesearch.Read-onlyVariant.
Remarks
Thispropertyisintendedtobeusedtospecifyarange,anditcanonlybeusedwiththeMsoConditionconstantmsoConditionAnyTimeBetweenormsoConditionAnyNumberBetween.
Example
Thisexampledisplaysthesecondvalueofthesearchcriteria(ifitexists)inadialogbox.Ifthesecondvaluedoesn'texist,theexampledisplaysanothermessage.
WithApplication.FileSearch.PropertyTests(1)
If.SecondValue=""Then
MsgBox"Youhaven'tspecifiedasecondvalue."
Else
MsgBox"Thesecondvalueyou'vesetis:"_
&.SecondValue
EndIf
EndWith
SelectedItemsPropertyReturnsaFileDialogSelectedItemscollection.ThiscollectioncontainsalistofthepathsofthefilesthatauserselectedfromafiledialogboxdisplayedusingtheShowmethodoftheFileDialogobject.
expression.SelectedItems
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
SubMain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Allowtheusertoselectmultiplefiles.
.AllowMultiSelect=True
'UsetheShowmethodtodisplaytheFilePickerdialogboxandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
Next
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
ShapePropertyReturnsaShapeobjectorInlineShapeobject,dependingontheMicrosoftOfficehostapplication.Read-onlyObject.
Remarks
TheShapepropertyreturnsaShapeobjectinMicrosoftExcelandPowerPoint.InWord,theShapepropertyreturnsaShapeobjectifthescriptanchorisfloating;ifit’saninlineanchor,however,thispropertyreturnsanInlineShapeobject.
Example
ThisexamplegetstheshapeassociatedwiththefirstscriptintheScriptscollectionanddeletesitfromworksheetoneintheactiveworkbook.
DimobjScriptShapeAsObject
SetobjScriptShape=_
ActiveWorkbook.Worksheets(1).Scripts(1).Shape
ObjScriptShape.Delete
ShowAll
ShortcutTextPropertyReturnsorsetstheshortcutkeytextdisplayednexttoabuttoncontrolwhenthebuttonappearsonamenu,submenu,orshortcutmenu.Read/writeString.
Remarks
YoucansetthispropertyonlyforcommandbarbuttonsthatcontainanOnActionmacro.
Example
ThisexampledisplaystheshortcuttextfortheOpencommand(Filemenu)ontheMicrosoftExcelWorksheetmenubarinamessagebox.
MsgBox(CommandBars("WorksheetMenuBar")._
Controls("File").Controls("New...).ShortcutText)
SignDatePropertyReturnsaVariantrepresentingthedateandtimethatthedigitalcertificatecorrespondingtotheSignatureobjectwasattachedtothedocument.Read-only.
expression.SignDate
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandcallthisfunction.Thefunctionwilltesttomakesurethatthedigitalsignaturethattheuserselectswillnotexpireinlessthan12months.Ifitwillexpire,thecertificateisn'tattached.
FunctionAddSignature()AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TesttomakesurethatthenewSignatureobject
'doesn'texpiretoosoon.Thisexpressioncalculates
'thenumberofmonthsuntiltheSignatureobjectexpires.
IfDateDiff("m",sig.SignDate,sig.ExpireDate)<12Then
MsgBox"Thiscertificatewillexpireinlessthan1year."&vbCrLf&_
"Pleaseuseanewercertificate."
AddSignature=False
sig.Delete
Else
AddSignature=True
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
SignerPropertyReturnsaStringrepresentingthenameofthepersonwhoattachedthedigitalcertificatethatcorrespondstotheSignatureobjecttothedocument.Read-only.
expression.Signer
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThefollowingexamplepromptstheusertoselectadigitalsignaturewithwhichtosigntheactivedocumentinMicrosoftWord.Tousethisexample,openadocumentinWordandpassthisfunctionthenameofacertificateissuerandthenameofacertificatesignerthatmatchtheIssuedByandIssuedTofieldsofadigitalcertificateintheDigitalCertificatesdialogbox.Thisexamplewilltesttomakesurethatthedigitalsignaturethattheuserselectsmeetscertaincriteria,suchasnothavingexpired,beforethenewsignatureiscommittedtothedisk.
FunctionAddSignature(ByValstrIssuerAsString,_
strSignerAsString)AsBoolean
OnErrorGoToError_Handler
DimsigAsSignature
'Displaythedialogboxthatletsthe
'userselectadigitalsignature.
'Iftheuserselectsasignature,then
'itisaddedtotheSignatures
'collection.Iftheuserdoesn't,then
'anerrorisreturned.
Setsig=ActiveDocument.Signatures.Add
'TestseveralpropertiesbeforecommitingtheSignatureobjecttodisk.
Ifsig.Issuer=strIssuerAnd_
sig.Signer=strSignerAnd_
sig.IsCertificateExpired=FalseAnd_
sig.IsCertificateRevoked=FalseAnd_
sig.IsValid=TrueThen
MsgBox"Signed"
AddSignature=True
'Otherwise,removetheSignatureobjectfromtheSignatureSetcollection.
Else
sig.Delete
MsgBox"Notsigned"
AddSignature=False
EndIf
'CommitallsignaturesintheSignatureSetcollectiontothedisk.
ActiveDocument.Signatures.Commit
ExitFunction
Error_Handler:
AddSignature=False
MsgBox"Actioncancelled."
EndFunction
SolutionIDPropertyReturnsorsetstheID,oftenagloballyuniqueidentifier(GUID),whichidentifiestheXMLexpansionpackattachedtotheactiveMicrosoftOfficeWord2003documentorMicrosoftOfficeExcel2003workbook.Read/writeString.
expression.SolutionID
expressionRequired.AnexpressionthatreturnsaSmartDocumentobject.
Remarks
TheSolutionIDpropertyreturnsanemptystringor"None"whennoXMLexpansionpackisattachedtotheactivedocument.
ProvideappropriatevaluesfortheSolutionIDandSolutionUrlpropertiestoattachanavailableXMLexpansionpacktotheactivedocumenttotransformitintoasmartdocumentwithoutusingthePickSolutionmethod.SettheSolutionIDandSolutionUrlpropertiestoemptystringstoremovetheattachedXMLexpansionpack.
Example
ThefollowingexampledetermineswhetheranXMLexpansionpackisattachedtotheactiveExcelworkbookbycheckingtheSolutionIDproperty.
DimobjSmartDocAsOffice.SmartDocument
SetobjSmartDoc=ActiveWorkbook.SmartDocument
IfobjSmartDoc.SolutionID="None"OrobjSmartDoc.SolutionID=""Then
MsgBox"NoXMLexpansionpackattached."
Else
MsgBox"SmartdocumentSolutionID:"&_
objSmartDoc.SolutionID
EndIf
SetobjSmartDoc=Nothing
ShowAll
SolutionURLPropertyReturnsorsetsanabsoluteURLwhichprovidesthecompletepathtotheXMLexpansionpackfileattachedtotheactiveMicrosoftOfficeWord2003documentorMicrosoftOfficeExcel2003workbook.Read/writeString.
expression.SolutionURL
expressionRequired.AnexpressionthatreturnsaSmartDocumentobject.
Remarks
TheSolutionUrlpropertyreturnsanemptystringwhennoXMLexpansionpackisattachedtotheactivedocument.
ProvideappropriatevaluesfortheSolutionIDandSolutionUrlpropertiestoattachanavailableXMLexpansionpacktotheactivedocumentandtransformitintoasmartdocumentwithoutusingthePickSolutionmethod.SettheSolutionIDandSolutionUrlpropertiestoemptystringstoremovetheattachedXMLexpansionpack
Example
ThefollowingexampledetermineswhetheranXMLexpansionpackisattachedtotheactiveWorddocument,thendisplaysthesmartdocument'sSolutionURL.
DimobjSmartDocAsOffice.SmartDocument
SetobjSmartDoc=ActiveDocument.SmartDocument
IfobjSmartDoc.SolutionID="None"OrobjSmartDoc.SolutionID=""Then
MsgBox"NoXMLexpansionpackattached."
Else
MsgBox"SmartdocumentSolutionURL:"&_
objSmartDoc.SolutionURL
EndIf
SetobjSmartDoc=Nothing
SoundsPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantproducesthesoundsthatcorrespondtoanimations.Read/writeBoolean.
Remarks
ThedefaultvalueisTrue.TheSoundspropertycorrespondstotheMakesoundsoptionunderUsetheOfficeAssistantontheOptionstabintheOfficeAssistantdialogbox.Ifasoundcardisnotinstalled,thispropertyhasnoeffect.
Example
ThisexampledisplaysandanimatestheOfficeAssistantandallowssound.
WithAssistant
.Visible=True
.On=True
IfNotSoundsThenSounds=True
.Animation=msoAnimationGreeting
EndWith
SourceURLPropertyDesignatesthelocationofthepubliccopyofashareddocumenttowhichchangesshouldbepublishedbackafterthedocumenthasbeenrevisedinaseparatedocumentworkspace.Read-onlyString.
expression.SourceURL
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
TheMicrosoftWindowsSharePointServicesuserinterfaceallowsuserstocopyapublicshareddocumentfromadocumentlibrarytoaseparatedocumentworkspacefortemporarycollaborationpurposes,thenpublishchangesbacktotheoriginalsourcelocation.TheSourceURLpropertyindicatestheoriginalsourcelocationofadocumentcopystoredinatemporaryworkspace.
ShowAll
StatePropertyStatepropertyasitappliestotheCommandBarButtonobject.
Returnsorsetstheappearanceofacommandbarbuttoncontrol.Read/writeMsoButtonState.HowevertheStatepropertyofbuilt-incommandbarbuttonsisread-only.
MsoButtonStatecanbeoneoftheseMsoButtonStateconstants.msoButtonDownmsoButtonMixedmsoButtonUp
expression.State
expressionRequired.AnexpressionthatreturnsaCommandBarButtonobject.
StatepropertyasitappliestotheHTMLProjectobject.
ReturnsthecurrentstateofanHTMLProjectobject.Read-onlyMsoHTMLProjectState.
MsoHTMLProjectStatecanbeoneoftheseMsoHTMLProjectStateconstants.msoHTMLProjectStateDocumentLockedmsoHTMLProjectStateDocumentProjectUnlockedmsoHTMLProjectStateProjectLocked
expression.State
expressionRequired.AnexpressionthatreturnsanHTMLProjectobject.
Example
AsitappliestotheCommandBarButtonobject.
ThisexamplecreatesacommandbarnamedCustomandaddstwobuttonstoit.TheexamplethensetsthebuttononthelefttomsoButtonUpandsetsthebuttonontherighttomsoButtonDown.
DimmyBarAsOffice.CommandBar
DimimgSourceAsOffice.CommandBarButton
DimmyControl1AsOffice.CommandBarButton
DimmyControl2AsOffice.CommandBarButton
'Addnewcommandbar.
SetmyBar=CommandBars.Add(Name:="Custom",Position:=msoBarTop,Temporary:=True)
'Add2buttonstonewcommandbar.
WithmyBar
.Controls.AddType:=msoControlButton
.Controls.AddType:=msoControlButton
.Visible=True
EndWith
'PasteBoldbuttonfaceandsetStateoffirstbutton.
SetmyControl1=myBar.Controls(1)
SetimgSource=CommandBars.FindControl(msoControlButton,113)
imgSource.CopyFace
WithmyControl1
.PasteFace
.State=msoButtonUp
EndWith
'PasteItalicsbuttonfaceandsetStateofsecondbutton.
SetmyControl2=myBar.Controls(2)
SetimgSource=CommandBars.FindControl(msoControlButton,114)
imgSource.CopyFace
WithmyControl2
.PasteFace
.State=msoButtonDown
EndWith
ShowAll
StatusPropertyStatuspropertyasitappliestotheSharedWorkspaceTaskobject.
Returnsorsetsthestatusofthespecifiedsharedworkspacetask.Read/writemsoSharedWorkspaceTaskStatus.
MsoSharedWorkspaceTaskStatuscanbeoneofthesemsoSharedWorkspaceTaskStatusconstants.msoSharedWorkspaceTaskStatusComplete(3)msoSharedWorkspaceTaskStatusDeferred(2)msoSharedWorkspaceTaskStatusInProgress(1)msoSharedWorkspaceTaskStatusNotStarted(4)msoSharedWorkspaceTaskStatusWaiting(5)
expression.Status
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTaskobject.
Remarks
Thesharedworkspacetaskschemaontheservercanbecustomized.CustomizationoftheschemamayaffectthetaskstatusenumerationwhentheAddorSavemethodiscalled.Statuspropertyvaluesaremappedasfollows:
Downloadedvalues1through5aremappedtomsoSharedWorkspaceTaskStatusenumerationvalues1through5.Schemavaluesbeyond5aremappedtoenumerationvalue1(msoSharedWorkspaceTaskStatusInProgress).Uploadedenumerationvalues1through5aremappedtoschemavalues1through5.Ifauser-specifiedvaluedoesnotmaptoanyvaluedefinedintheschema,theuser-specifiedvalueissilentlyignoredandtheStatuspropertyisnotupdatedontheserver.
StatuspropertyasitappliestotheSyncobject.
Returnsthestatusofthesynchronizationofthelocalcopyoftheactivedocumentwiththeservercopy.Read-onlyMsoSyncStatusType.
MsoSyncStatusTypecanbeoneofthefollowingmsoSyncStatusTypeconstants.msoSyncStatusConflict(4)msoSyncStatusError(6)msoSyncStatusLatest(1)msoSyncStatusLocalChanges(3)msoSyncStatusNewerAvailable(2)msoSyncStatusNoSharedWorkspace(0)msoSyncStatusSuspended(5)
expression.Status
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
UsetheStatuspropertytodeterminewhetherthelocalcopyoftheactivedocumentissynchronizedwiththesharedservercopy.UsetheGetUpdatemethodtorefreshthestatus.Usethefollowingmethodsandpropertieswhenappropriatetorespondtovariousstatusconditions:
msoSyncStatusConflict-Truewhenboththelocalandtheservercopieshavechanges.UsetheResolveConflictmethodtoresolvethedifferences.msoSyncStatusError-ChecktheErrorTypeproperty.msoSyncStatusLocalChanges-Truewhenonlythelocalcopyhaschanges.UsethePutUpdatemethodtosavelocalchangestotheservercopy.msoSyncStatusNewerAvailable-Truewhenonlytheservercopyhaschanges.Closeandre-openthedocumenttoworkwiththelatestcopyfromtheserver.msoSyncStatusSuspended-UsetheUnsuspendmethodtoresumesynchronization.
TheStatuspropertyreturnsasingleconstantfromthelistinthefollowingorderofprecedence:
1. msoSyncStatusNoSharedWorkspace2. msoSyncStatusError3. msoSyncStatusSuspended4. msoSyncStatusConflict5. msoSyncStatusNewerAvailable6. msoSyncStatusLocalChanges7. msoSyncStatusLatest
Example
AsitappliestotheSharedWorkspaceTaskobject.
ThefollowingexampledisplaysalistofalltasksinthecurrentsharedworkspacewhosestatusisnotsettoComplete.
DimswsTaskAsOffice.SharedWorkspaceTask
DimstrTaskStatusAsString
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
IfswsTask.Status<>msoSharedWorkspaceTaskStatusCompletedThen
strTaskStatus=strTaskStatus&swsTask.Title&vbCrLf
EndIf
Next
MsgBox"Thefollowingtaskshavenotbeencompleted:"&vbCrLf&_
strTaskStatus,vbInformation+vbOKOnly,"IncompleteTasks"
SetswsTask=Nothing
AsitappliestotheSyncobject.
ThefollowingexampleexaminestheStatuspropertyandtakesanappropriateactiontosynchronizethelocalandservercopiesofthedocumentifnecessary.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status>msoSyncStatusNoSharedWorkspaceThen
SelectCaseobjSync.Status
CasemsoSyncStatusConflict
objSync.ResolveConflictmsoSyncConflictMerge
ActiveDocument.Save
objSync.ResolveConflictmsoSyncConflictClientWins
strStatus="Conflictresolvedbymergingchanges."
CasemsoSyncStatusError
strStatus="Lasterrortype:"&objSync.ErrorType
CasemsoSyncStatusLatest
strStatus="Documentcopiesalreadyinsync."
CasemsoSyncStatusLocalChanges
objSync.PutUpdate
strStatus="Localchangessavedtoserver."
CasemsoSyncStatusNewerAvailable
strStatus="Newercopyavailableontheserver."
CasemsoSyncStatusSuspended
objSync.Unsuspend
strStatus="Synchronizationresumed."
EndSelect
Else
strStatus="Notasharedworkspacedocument."
EndIf
MsgBoxstrStatus,vbInformation+vbOKOnly,"SyncInformation"
SetobjSync=Nothing
StoreLicensesPropertyReturnsaBooleanvaluethatindicateswhethertheuser'slicensetoviewtheactivedocumentshouldbecachedtoallowofflineviewingwhentheusercannotconnecttoarightsmanagementserver.Read/writeBoolean.DefaultisTrue.
expression.StoreLicenses
expressionRequired.AnexpressionthatreturnsaPermissionobject.
Remarks
TheStoreLicensespropertycorrespondsto(anditsvalueistheoppositeof)theRequireaconnectiontoverifyauser'spermissionoptioninthepermissionsuserinterface.WhenStoreLicensesisFalse,usersotherthanthedocumentownermustconnecttotherightsmanagementserverandacquirethelicensetoworkwiththedocumenteachtimetheyopenit.
WhencontentisprotectedusingtheMicrosoftOffice2003InformationRightsManagementservice,theStoreLicensespropertyisalwaysTrueandcannotbesettoFalse.
Example
Thefollowingexampledisplaysinformationaboutthepermissionssettingsoftheactivedocument,includingtheStoreLicensessetting.
DimirmPermissionAsOffice.Permission
DimstrIRMInfoAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
strIRMInfo="Permissionsarerestrictedonthisdocument."&vbCrLf
strIRMInfo=strIRMInfo&"Viewintrustedbrowser:"&_
irmPermission.EnableTrustedBrowser&vbCrLf&_
"Documentauthor:"&irmPermission.DocumentAuthor&vbCrLf&_
"Userswithpermissions:"&irmPermission.Count&vbCrLf&_
"Cachelicenseslocally:"&irmPermission.StoreLicenses&vbCrLf&_
"RequestpermissionURL:"&irmPermission.RequestPermissionURL&vbCrLf
IfirmPermission.PermissionFromPolicyThen
strIRMInfo=strIRMInfo&"Permissionsappliedfrompolicy:"&vbCrLf&_
"Policyname:"&irmPermission.PolicyName&vbCrLf&_
"Policydescription:"&irmPermission.PolicyDescription
Else
strIRMInfo=strIRMInfo&"Custompermissionsapplied."
EndIf
Else
strIRMInfo="PermissionsareNOTrestrictedonthisdocument."
EndIf
MsgBoxstrIRMInfo,vbInformation+vbOKOnly,"IRMInformation"
SetirmPermission=Nothing
ShowAll
StylePropertyStylepropertyasitappliestotheCommandBarButtonobject.
Returnsorsetsthewayacommandbarbuttoncontrolisdisplayed.Read/writeMsoButtonStyle.
MsoButtonStylecanbeoneoftheseMsoButtonStyleconstants.msoButtonAutomaticmsoButtonCaptionmsoButtonIconmsoButtonIconAndCaptionmsoButtonIconAndCaptionBelowmsoButtonIconAndWrapCaptionmsoButtonIconAndWrapCaptionBelowmsoButtonWrapCaption
StylepropertyasitappliestotheCommandBarComboBoxobject.
Returnsorsetsthewayacommandbarcomboboxcontrolisdisplayed.CanbeeitherofthefollowingMsoComboStyleconstants:msoComboLabelormsoComboNormal.Read/writeMsoComboStyle.
MsoComboStylecanbeoneoftheseMsoComboStyleconstants.msoComboLabelmsoComboNormal
Example
Thisexamplecreatesashortcutmenucontainingabuttoncontrolandacomboboxcontrolandsetsthestyleofeach.
SetmyBar=CommandBars_
.Add(Name:="Custom1",Position:=msoBarPopup,Temporary:=False)
WithmyBar
.Controls.AddType:=msoControlButton,Id:=3
.Controls(1).Style=msoButtonCaption
.Controls.AddType:=msoControlComboBox
With.Controls(2)
.Style=msoComboLabel
.AddItem"vanilla"
.AddItem"chocolate"
.AddItem"cookiedough"
EndWith
EndWith
myBar.ShowPopup
TablePropertyReturnsaStringthatrepresentsthenameofthetablewithinthedatasourcefilethatcontainsthemailmergerecords.Thereturnedvaluemaybeblankifthetablenameisunknownornotapplicabletothecurrentdatasource.Read-only.
expression.Table
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
Thisexamplesetsthenameofthetableifthetablenameiscurrentlyblank.
SubOfficeTest()
DimappOfficeAsOfficeDataSourceObject
SetappOffice=Application.OfficeDataSourceObject
appOffice.OpenbstrConnect:="DRIVER=SQLServer;SERVER=ServerName;"&_
"UID=user;PWD=;DATABASE=Northwind",bstrTable:="Employees"
IfappOffice.Table=""Then
appOffice.Table="Employees"
EndIf
EndSub
ShowAll
TagPropertyReturnsorsetsinformationaboutthecommandbarcontrol,suchasdatathatcanbeusedasanargumentinprocedures,orinformationthatidentifiesthecontrol.Read/writeString.
expression.Tag
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
Toavoidduplicatecallsofthesameclasswhentiggeredwithevents,definetheTagpropertyuniquetotheevents.Thefollowingexampledemonstratesthisconceptwithtwomodules.
PublicWithEventsoBtnAsCommandBarButton
PrivateSuboBtn_click(ByValctrlAsOffice.CommandBarButton,CancelDefaultAsBoolean)
MsgBox"Clicked"&ctrl.Caption
EndSub
DimoBtnsAsNewCollection
SubUse_Tag()
DimoEvtAsCBtnEvent
SetoBtns=Nothing
Fori=1To5
SetoEvt=NewCBtnEvent
SetoEvt.oBtn=Application.CommandBars("WorksheetMenuBar").Controls.Add(msoControlButton)
WithoEvt.oBtn
.Caption="Btn"&i
.Style=msoButtonCaption
.Tag="Hello"&i
EndWith
oBtns.AddoEvt
Next
EndSub
Example
Thisexamplesetsthetagforthebuttononthecustomcommandbarto"SpellingButton"anddisplaysthetaginamessagebox.
CommandBars("Custom").Controls(1).Tag="SpellingButton"
MsgBox(CommandBars("Custom").Controls(1).Tag)
TasksPropertyReturnsaSharedWorkspaceTaskscollectionthatrepresentsthelistoftasksinthecurrentsharedworkspace.Read-only.
expression.Tasks()
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Example
Thefollowingexampleliststhetasksinthecurrentsharedworkspace.
DimswsTasksAsOffice.SharedWorkspaceTasks
SetswsTasks=ActiveWorkbook.SharedWorkspace.Tasks
MsgBox"Thereare"&swsTasks.Count&_
"task(s)inthecurrentsharedworkspace.",_
vbInformation+vbOKOnly,_
"CollectionInformation"
SetswsTasks=Nothing
ShowAll
TextPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
BalloonLabelorBalloonCheckboxobject:ReturnsorsetsthetextdisplayednexttoacheckboxorlabelintheOfficeAssistantballoon.Read/writeString.
Balloonobject:ReturnsorsetsthetextdisplayedaftertheheadingbutbeforethelabelsorcheckboxesintheOfficeAssistantballoon.Read/writeString.
CommandBarComboBoxobject:Returnsorsetsthetextinthedisplayoreditportionofthecommandbarcomboboxcontrol.Read/writeString.
HTMLProjectItemobject:ReturnsorsetstheHTMLtextintheHTMLeditor.Read/writeString.
expression.Text
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
FortheBalloon,BalloonLabel,andBalloonCheckboxobjects,youcanspecifythataparticulargraphicbedisplayedbyusingthefollowingsyntax:{typelocationsizing_factor},wheretypeisbmp(bitmap)orwmf(Windowsmetafile);locationistheresourceIDorthepathandfilename;andsizing_factordenotesthewidthofthe.wmffile(sizing_factorisomittedfor.bmpfiles).
TheBalloonobjectalsosupportsunderlinedtextandtextthathasoneofthe16systempalettecolorsappliedtoit.Todisplayunderlinedtext,usethesyntax{ul}or{ul1};use{ul0}toturnunderliningoff.Tochangethecoloroftext,precedethetextstringwiththecharactersequence{cfnumber},wherenumberisoneofthesystemcolornumberslistedinthefollowingtable.
Systemcolornumber Color0 Black1 Darkred2 Darkgreen3 Darkyellow4 Darkblue5 Darkmagenta6 Darkcyan7 Lightgray248 Mediumgray249 Red250 Green251 Yellow252 Blue253 Magenta254 Cyan255 White
Ifyouspecifyanumberotherthanoneoftheprecedingsystemcolornumbers,thetextintheOfficeAssistantballoonisblack.
Example
Thisexamplecreatesanewcommandbarnamed"Custom"andaddstoitacomboboxthatcontainsfourlistitems.TheexamplethenusestheTextpropertytosetItem3asthedefaultlistitem.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlComboBox,ID:=1
.Visible=True
EndWith
SettestComboBox=CommandBars("Custom").Controls(1)
WithtestComboBox
.AddItem"Item1",1
.AddItem"Item2",2
.AddItem"Item3",3
.AddItem"Item4",4
.Text="Item3"
EndWith
ThisexamplecreatesanewOfficeAssistantballoonwithaheading,text,andthreeregionchoices.TheexampleusestheTextpropertytoprovideballoon-relatedinstructionstotheuserandalabelforeachtextbox.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
ThisexamplecreatesanewOfficeAssistantballoonthatcontainsunderlinedheadingtext,redtext,andbluetextthatisalsounderlined.
WithAssistant.NewBalloon
.Heading="Underlined{ul1}Heading{ul0}"
.Text="Some{cf249}Red{cf0}textandsome"&_
"underlined{cf252}{ul1}Blue{ul0}{cf0}text."
.Show
EndWith
ThisexamplecreatesanewOfficeAssistantballoonthatcontainsaWindowsmetafile.
WithAssistant.NewBalloon
.Heading="Underlined{ul1}Heading{ul0}"
.Text="{WMF""C:\Favorites\MyPicture.WMF""}"
.Show
EndWith
TextOrPropertyPropertyReturnsorsetsthewordorphrasetobesearchedfor,ineitherthebodyofafileorthefile'sproperties,duringthefilesearch.Thewordorphrasecanincludethe*(asterisk)or?(questionmark)wildcardcharacter.Read/writeString.
Remarks
Usethequestionmarkwildcardcharactertomatchanysinglecharacter.Forexample,typegr?ytofindallfilesthatcontainatleastoneinstanceofeither"gray"or"grey."
Usetheasteriskwildcardcharactertomatchanynumberofcharacters.Forexample,typeSan*toreturnallfilesthatcontainatleastonewordthatbeginswith"San."
Example
ThisexamplesearchestheC:\MyDocumentsfolderandallofitssubfoldersandreturnsallfileswhosebodytextorfilepropertiescontainanywordsthatbeginwith"San."TheTextOrPropertypropertysetsthewordtobesearchedforandlimitsthesearchtoeitherthebodyofthefileorthefileproperties.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.TextOrProperty="San*"
.FileType=msoFileTypeAllFiles
EndWith
TipOfDayPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
TrueiftheOfficeAssistantdisplaysaspecialtipeachtimetheOfficeapplicationisopened.Read/writeBoolean.
Remarks
ThedefaultvalueisFalse.TipOfDaypropertycorrespondstotheShowtheTipoftheDayatstartupoptionunderShowtipsaboutontheOptionstabintheOfficeAssistantdialogbox.
Example
ThisexampledisplaystheOfficeAssistantinaspecificlocationanditsetsseveraloptionsbeforemakingtheAssistantvisible.
WithAssistant
.On=True
.Visible=True
.Left=400
.MoveWhenInTheWay=True
IfNotTipOfDayThenTipOfDay=True
.Animation=msoAnimationGreeting
EndWith
ShowAll
TitlePropertyAsitappliestotheFileDialogobject.
SetsorreturnsthetitleofafiledialogboxdisplayedusingtheFileDialogobject.Read/writeString.
expression.Title
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
AsitappliestotheSharedWorkspaceTaskobject.
SetsorreturnsthetitleofaSharedWorkspaceTaskobject.Read/writeString.
expression.Title
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceTaskobject.
Remarks
TheTitlepropertyisthesinglerequiredpropertyofasharedworkspacetask.UsetheoptionalDescriptionpropertytoprovideorreturnadditionalinformationaboutthetask.
Example
AsitappliestotheFileDialogobject.
ThefollowingexampledisplaysaFilePickerdialogboxusingtheFileDialogobjectanddisplayseachselectedfileinamessagebox.
Submain()
'DeclareavariableasaFileDialogobject.
DimfdAsFileDialog
'CreateaFileDialogobjectasaFilePickerdialogbox.
Setfd=Application.FileDialog(msoFileDialogFilePicker)
'Declareavariabletocontainthepath
'ofeachselecteditem.EventhoughthepathisaString,
'thevariablemustbeaVariantbecauseForEach...Next
'routinesonlyworkwithVariantsandObjects.
DimvrtSelectedItemAsVariant
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Changethetitleofthedialog
.Title="Archive"
'UsetheShowmethodtodisplaythefilepickerdialogandreturntheuser'saction.
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'StepthrougheachstringintheFileDialogSelectedItemscollection.
ForEachvrtSelectedItemIn.SelectedItems
'vrtSelectedItemisaStringthatcontainsthepathofeachselecteditem.
'YoucanuseanyfileI/Ofunctionsthatyouwanttoworkwiththispath.
'Thisexamplesimplydisplaysthepathinamessagebox.
MsgBox"Selecteditem'spath:"&vrtSelectedItem
NextvrtSelectedItem
'IftheuserpressesCancel...
Else
EndIf
EndWith
'SettheobjectvariabletoNothing.
Setfd=Nothing
EndSub
AsitappliestotheSharedWorkspaceTaskobject.
Thefollowingexampledisplaysalistofthetitlesofalltasksinthecurrentsharedworkspace.
DimswsTaskAsOffice.SharedWorkspaceTask
DimstrTasksAsString
ForEachswsTaskInActiveWorkbook.SharedWorkspace.Tasks
strTasks=strTasks&swsTask.Title&vbCrLf
Next
MsgBoxstrTasks,vbInformation+vbOKOnly,_
"TasksinSharedWorkspace"
SetswsTask=Nothing
TooltipTextPropertyReturnsorsetsthetextdisplayedinacommandbarcontrol'sScreenTip.Read/writeString.
Remarks
Bydefault,thevalueoftheCaptionpropertyisusedastheScreenTip.
Example
ThisexampleaddsaScreenTiptothelastcontrolontheactivemenubar.
SetmyMenuBar=CommandBars.ActiveMenuBar
SetlastCtrl=myMenuBar_
.Controls(myMenuBar.Controls.Count)
lastCtrl.BeginGroup=True
lastCtrl.TooltipText="ClickforhelponUIfeature"
ShowAll
TopPropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
ToppropertyasitappliestotheAssistantandCommandBarobjects.
Setsorreturnsthedistance(inpoints)fromthetopoftheOfficeAssistant,orfromthetopedgeofthespecifiedcommandbar,tothetopedgeofthescreen.Fordockedcommandbars,thispropertyreturnsorsetsthedistancefromthecommandbartothetopofthedockingarea.Read/writeLong.
expression.Top
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
ToppropertyasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
Returnsthedistance(inpixels)fromthetopedgeofthespecifiedcommandbarcontroltothetopedgeofthescreen.Read-onlyLong.
expression.Top
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
Example
AsitappliestotheAssistantandCommandBarobjects.
ThisexamplemovestheOfficeAssistanttoanothercoordinateandsetsitsToppropertyforsubsequentappearances.
WithAssistant
.On=True
.Visible=True
.Sounds=True
.Animation=msoAnimationBeginSpeaking
EndWith
Assistant.Top=100
MsgBox"ClickOKtomovetheAssistanttoa"&_
"newlocation."
Assistant.Top=500
Thisexamplepositionstheupper-leftcornerofthefloatingcommandbarnamedCustom140pixelsfromtheleftedgeofthescreenand100pixelsfromthetopofthescreen.
SetmyBar=CommandBars("Custom")
myBar.Position=msoBarFloating
WithmyBar
.Left=140
.Top=100
EndWith
ShowAll
TypePropertyTypepropertyasitappliestotheCommandBarobject.
Returnsthetypeofcommandbar.Read-onlyMsoBarType.
MsoBarTypecanbeoneoftheseMsoBarTypeconstants.msoBarTypeMenuBarmsoBarTypeNormalmsoBarTypePopup
expression.Type
expressionRequired.AnexpressionthatreturnsaCommandBarobject.
TypepropertyasitappliestotheCommandBarButton,CommandBarComboBox,CommandBarControl,andCommandBarPopupobjects.
Returnsthetypeofcommandbarcontrol.Read-onlyMsoControlType.
MsoControlTypecanbeoneoftheseMsoControlTypeconstants.msoControlActiveXmsoControlAutoCompleteCombomsoControlButtonmsoControlButtonDropdownmsoControlButtonPopupmsoControlComboBoxmsoControlCustommsoControlDropdownmsoControlEditmsoControlExpandingGridmsoControlGauge
msoControlGenericDropdownmsoControlGraphicCombomsoControlGraphicDropdownmsoControlGraphicPopupmsoControlGridmsoControlLabelmsoControlLabelExmsoControlOCXDropdownmsoControlPanemsoControlPopupmsoControlSpinnermsoControlSplitButtonMRUPopupmsoControlSplitButtonPopupmsoControlSplitDropdownmsoControlSplitExpandingGridmsoControlWorkPane
expression.Type
expressionRequired.Anexpressionthatreturnsoneoftheaboveobjects.
TypepropertyasitappliestotheSearchScopeobject.
ReturnsavaluethatcorrespondstothetypeofSearchScopeobject.ThetypeindicatestheareainwhichtheExecutemethodoftheFileSearchobjectwillsearchforfiles.Read-onlyMsoSearchIn.
MsoSearchIncanbeoneoftheseMsoSearchInconstants.msoSearchInCustommsoSearchInMyComputermsoSearchInMyNetworkPlacesmsoSearchInOutlook
expression.Type
expressionRequired.AnexpressionthatreturnsaSearchScopeobject.
TypepropertyasitappliestotheDocumentPropertyobject.
Returnsorsetsthedocumentpropertytype.Read-onlyforbuilt-indocumentproperties;read/writeforcustomdocumentproperties.
expression.Type
expressionRequired.AnexpressionthatreturnsaDocumentPropertyobject.
Remarks
ThereturnvaluewillbeaMsoDocPropertiesconstant.
MsoDocPropertiescanbeoneoftheseMsoDocPropertiesconstants.msoPropertyTypeBooleanmsoPropertyTypeDatemsoPropertyTypeFloatmsoPropertyTypeNumbermsoPropertyTypeString
Example
AsitappliestotheCommandBarobject.
ThisexamplefindsthefirstcontrolonthecommandbarnamedCustom.UsingtheTypeproperty,theexampledetermineswhetherthecontrolisabutton.Ifthecontrolisabutton,theexamplecopiesthefaceoftheCopybutton(ontheStandardtoolbar)andthenpastesitontothecontrol.
SetoldCtrl=CommandBars("Custom").Controls(1)
IfoldCtrl.Type=msoControlButtonThen
SetnewCtrl=CommandBars.FindControl(Type:=_
MsoControlButton,ID:=_
CommandBars("Standard").Controls("Copy").ID)
NewCtrl.CopyFace
OldCtrl.PasteFace
EndIf
AsitappliestotheDocumentPropertyobject.
Thisexampledisplaysthename,type,andvalueofadocumentproperty.YoumustpassavalidDocumentPropertyobjecttotheprocedure.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
ShowAll
URLPropertyAsitappliestotheSharedWorkspaceobject.
Returnsthetop-levelUniformResourceLocator(URL)ofthesharedworkspace.Read-onlyString.
expression.URL
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceobject.
Remarks
TheURLpropertyreturnstheaddressofthesharedworkspaceinthisformat:http://server/sites/user/workspace/.
TheURLpropertyreturnsaURL-encodedstring.Forexample,aspaceinthefoldernameisrepresentedby%20.Useasimplefunctionlikethefollowingexampletoreplacethisescapedcharacterwithaspace.
PrivateFunctionURLDecode(URLtoDecodeAsString)AsString
URLDecode=Replace(URLtoDecode,"%20","")
EndFunction
AsitappliestotheSharedWorkspaceFileobject.
ReturnsthefullUniformResourceLocator(URL)andfilenameofthesharedworkspacefile.Read-onlyString.
expression.URL
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceFileobject.
Remarks
TheURLpropertyreturnstheaddressofthesharedworkspacefileinthisformat:http://server/sites/user/workspace/Shared%Documents/MyWorkbook.xls.
TheURLpropertyreturnsaURL-encodedstring.Forexample,aspaceinthefoldernameisrepresentedby%20.
TheSharedWorkspaceFileobjectdoesnothaveaNameorFileNameproperty.ThefilenamemustbeextractedfromtheURLproperty.UsesimplefunctionsasinthefollowingexampletoextractthefilenameandtodecodespacesintheURL.
PrivateFunctionFilenameFromURL(FileURLAsString)AsString
DimintLastSeparatorAsInteger
FileURL=URLDecode(FileURL)
intLastSeparator=InStrRev(FileURL,"/")
FilenameFromURL=Right(FileURL,Len(FileURL)-intLastSeparator)
EndFunction
PrivateFunctionURLDecode(URLtoDecodeAsString)AsString
URLDecode=Replace(URLtoDecode,"%20","")
EndFunction
AsitappliestotheSharedWorkspaceLinkobject.
ReturnsorsetstheUniformResourceLocator(URL)ofthelinksavedinthesharedworkspace.Read/writeString.
expression.URL
expressionRequired.AnexpressionthatreturnsaSharedWorkspaceLinkobject.
Remarks
UsetheURLpropertyoftheSharedWorkspaceLinkobjecttoretrievethewebaddresssavedinthesharedworkspacelink.UsetheoptionalDescriptionandNotespropertiestoretrieveadditionalinformationaboutthelink.
TheURLpropertyreturnsaURL-encodedstring.Forexample,aspaceinthefoldernameisrepresentedby%20.Useasimplefunctionlikethefollowingexampletoreplacethisescapedcharacterwithaspace.
PrivateFunctionURLDecode(URLtoDecodeAsString)AsString
URLDecode=Replace(URLtoDecode,"%20","")
EndFunction
Example
AsitappliestotheSharedWorkspaceobject.
ThefollowingexampledisplaysthebaseURLofthesharedworkspace.
MsgBox"URL:"&ActiveWorkbook.SharedWorkspace.URL,_
vbInformation+vbOKOnly,"SharedWorkspaceURL"
AsitappliestotheSharedWorkspaceFileobject.
ThefollowingexamplelocatesallMicrosoftExcelworkbooksintheSharedWorkspaceFilescollectionbyexaminingtheURLpropertyofeachfileforthe"xls"fileextension.
DimstrExcelFilesAsString
DimswsFileAsOffice.SharedWorkspaceFile
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
IfRight(swsFile.URL,3)="xls"Then
strExcelFiles=strExcelFiles&swsFile.URL&vbCrLf
EndIf
Next
MsgBox"ExcelFiles:"&vbCrLf&strExcelFiles,_
vbInformation+vbOKOnly,"ExcelFilesinSharedWorkspace"
Thefollowingexamplelistsallfilesinthesharedworkspace,usingsupportingfunctionstoextracttheirfilenamesfromtheURLandtoconvertURL-encodedspacesfrom%20toaspacecharacter.
DimswsFileAsOffice.SharedWorkspaceFile
DimstrFileListAsString
ForEachswsFileInActiveWorkbook.SharedWorkspace.Files
strFileList="Filename:"&FilenameFromURL(swsFile.URL)&_
vbCrLf&"URL:"&URLDecode(swsFile.URL)&vbCrLf
Next
MsgBoxstrFileList,vbInformation+vbOKOnly,"FilesinSharedWorkspace"
SetswsFile=Nothing
PrivateFunctionFilenameFromURL(FileURLAsString)AsString
DimintLastSeparatorAsInteger
FileURL=URLDecode(FileURL)
intLastSeparator=InStrRev(FileURL,"/")
FilenameFromURL=Right(FileURL,Len(FileURL)-intLastSeparator)
EndFunction
PrivateFunctionURLDecode(URLtoDecodeAsString)AsString
URLDecode=Replace(URLtoDecode,"%20","")
EndFunction
AsitappliestotheSharedWorkspaceLinkobject.
ThefollowingexamplelocatesalllinkstotheMicrosoftDeveloperNetwork(MSDN)websiteintheSharedWorkspaceLinkscollectionbyexaminingtheURLpropertyofeachlinkforthestring"msdn".
DimstrMSDNLinksAsString
DimswsLinkAsOffice.SharedWorkspaceLink
ForEachswsLinkInActiveWorkbook.SharedWorkspace.Links
IfInStr(swsLink.URL,"msdn",vbTextCompare)>0Then
strMSDNLinks=strMSDNLinks&swsLink.URL&vbCrLf
EndIf
Next
MsgBox"MSDNLinks:"&vbCrLf&strMSDNLinks,_
vbInformation+vbOKOnly,"MSDNLinksinSharedWorkspace"
UserIdPropertyReturnstheemailnameoftheuserwhosepermissionsontheactivedocumentaredeterminedbythespecifiedUserPermissionobject.Read-onlyString.
expression.UserId
expressionRequired.AnexpressionthatreturnsaUserPermissionobject.
Remarks
TheUserPermissionobjectassociatesasetofpermissionsontheactivedocumentwithasingleuserandanoptionalexpirationdate.TheUserIDpropertyreturnsthenameinemailformoftheuserwhosepermissionsaredeterminedbythespecifiedUserPermissionobject.
Example
Thefollowingexampleliststheuserswhohavepermissionsontheactivedocument.
DimirmPermissionAsOffice.Permission
DimirmUserPermAsOffice.UserPermission
DimstrUsersAsString
SetirmPermission=ActiveWorkbook.Permission
IfirmPermission.EnabledThen
ForEachirmUserPermInirmPermission
strUsers=strUsers&irmUserPerm.UserId&vbCrLf
Next
MsgBoxstrUsers,_
vbInformation+vbOKOnly,"IRMInformation"
Else
MsgBox"Permissionsarenotenabledforthisdocument.",_
vbInformation+vbOKOnly,"IRMInformation"
EndIf
SetirmUserPerm=Nothing
SetirmPermission=Nothing
ShowAll
ValuePropertyValuepropertyasitappliestotheDocumentPropertyobject.
Returnsorsetsthevalueofadocumentproperty.Read/writeVariant.
expression.Value
expressionRequired.AnexpressionthatreturnsaDocumentPropertyobject.
Remarks
Ifthecontainerapplicationdoesn'tdefineavalueforoneofthebuilt-indocumentproperties,readingtheValuepropertyforthatdocumentpropertycausesanerror.
ValuepropertyasitappliestothePropertyTestobject.
Returnsthevalueofapropertytestforafilesearch.Read-onlyVariant.
expression.Value
expressionRequired.AnexpressionthatreturnsaPropertyTestobject.
Example
AsitappliestotheDocumentPropertyobject.
Thisexampledisplaysthename,type,andvalueofadocumentproperty.Fortheexampletowork,dpmustbeavalidDocumentPropertyobject.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
AsitappliestothePropertyTestobject.
Thisexampledisplaysthevalueofthesearchcriteria(ifitexists)inamessagebox.Ifthesecondvaluedoesn'texist,theexampledisplaysanothermessage.
WithApplication.FileSearch.PropertyTests(1)
If.Value=""Then
MsgBox"Youhaven'tspecifiedavalue."
Else
MsgBox"Thevalueyou'vesetis:"_
&.Value
EndIf
EndWith
VisiblePropertySomeofthecontentinthistopicmaynotbeapplicabletosomelanguages.
Trueifthespecifiedobjectisvisible.Read/writeBoolean.
expression.Visible
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Remarks
TheVisiblepropertyfornewlycreatedcustomcommandbarsisFalsebydefault.
TheEnabledpropertyforacommandbarmustbesettoTruebeforethevisiblepropertyissettoTrue.
Example
ThisexamplestepsthroughthecollectionofcommandbarstofindtheFormscommandbar.IftheFormscommandbarisfound,theexamplemakesitvisibleandprotectsitsdockingstate.
foundFlag=False
ForEachcmdbarInCommandBars
Ifcmdbar.Name="Forms"Then
cmdbar.Protection=msoBarNoChangeDock
cmdbar.Visible=True
foundFlag=True
EndIf
Next
IfNotfoundFlagThen
MsgBox"'Forms'commandbarisnotinthecollection."
EndIf
ThisexamplemakestheOfficeAssistantvisibleandsetsitsanimation.
WithApplication.Assistant
.Visible=True
.Sounds=True
.Animation=msoAnimationBeginSpeaking
EndWith
ShowAll
WidthPropertyReturnsorsetsthewidth(inpixels)ofthespecifiedcommandbarorcommandbarcontrol.Read/writeInteger.
expression.Width
expressionRequired.AnexpressionthatreturnsoneoftheobjectsintheAppliesTolist.
Example
ThisexampleaddsacustomcontroltothecommandbarnamedCustom.Theexamplesetstheheightofthecustomcontroltotwicetheheightofthecommandbarandsetsitswidthto50pixels.Noticehowthecommandbarautomaticallyresizesitselftoaccommodatethecontrol.
SetmyBar=CommandBars("Custom")
barHeight=myBar.Height
SetmyControl=myBar.Controls_
.Add(Type:=msoControlButton,_
Id:=CommandBars("Standard").Controls("Save").Id,_
Temporary:=True)
WithmyControl
.Height=barHeight*2
.Width=50
EndWith
myBar.Visible=True
WorkspaceLastChangedByPropertyDisplaysthefriendlynameoftheuserwholastsavedchangestotheservercopyofashareddocument.Read-onlyString.
expression.WorkspaceLastChangedBy
expressionRequired.AnexpressionthatreturnsaSyncobject.
Remarks
Iftheactivedocumentisnotconfiguredforsynchronizationbetweenthelocalcopyandtheservercopy,theWorkspaceLastChangedBypropertyraisesarun-timeerror.
Example
Thefollowingexamplechecksforaconflictbetweenthelocalandtheservercopiesoftheshareddocumentandreportsthenameoftheuserwholastsavedchangestotheservercopy.
DimobjSyncAsOffice.Sync
DimstrStatusAsString
SetobjSync=ActiveDocument.Sync
IfobjSync.Status=msoSyncStatusConflictThen
strStatus="Theservercopyhasbeenchanged."&vbCrLf&_
"Changeshavebeenmadeby:"&_
objSync.WorkspaceLastChangedBy
MsgBoxstrStatus,vbInformation+vbOKOnly,"ServerCopyChanged"
EndIf
SetobjSync=Nothing
ChangeEventOccurswhentheenduserchangestheselectioninacommandbarcombobox.
PrivateSubCommandBarComboBox_Change
(ByValCtrlAsCommandBarComboBox)
Remarks
TheChangeeventisrecognizedbytheCommandBarComboBoxobject.ToreturntheChangeeventforaparticularCommandBarComboBoxcontrol,usetheWithEventskeywordtodeclareavariable,andthensetthevariabletotheCommandBarComboBoxcontrol.WhentheChangeeventistriggered,itexecutesthemacroorcodethatyouspecifiedwiththeOnActionpropertyofthecontrol.
Example
ThefollowingexamplecreatesacommandbarwithaCommandBarComboBoxcontrolcontainingfourselections.ThecomboboxrespondstouserinteractionthroughtheCommandBarComboBox_Changeevent.
PrivatectlComboBoxHandlerAsNewComboBoxHandler
SubAddComboBox()
SetHostApp=Application
DimnewBarAsOffice.CommandBar
SetnewBar=HostApp.CommandBars.Add(Name:="TestCommandBar",Temporary:=True)
DimnewComboAsOffice.CommandBarComboBox
SetnewCombo=newBar.Controls.Add(msoControlComboBox)
WithnewCombo
.AddItem"FirstClass",1
.AddItem"BusinessClass",2
.AddItem"CoachClass",3
.AddItem"Standby",4
.DropDownLines=5
.DropDownWidth=75
.ListHeaderCount=0
EndWith
ctlComboBoxHandler.SyncBoxnewCombo
newBar.Visible=True
EndSub
Theprecedingexamplereliesonthefollowingcode,whichisstoredinaclassmoduleintheVBAproject.
PrivateWithEventsComboBoxEventAsOffice.CommandBarComboBox
PublicSubSyncBox(boxAsOffice.CommandBarComboBox)
SetComboBoxEvent=box
IfNotboxIsNothingThen
MsgBox"Synced"&box.Caption&"ComboBoxevents."
EndIf
EndSub
PrivateSubClass_Terminate()
SetComboBoxEvent=Nothing
EndSub
PrivateSubComboBoxEvent_Change(ByValCtrlAsOffice.CommandBarComboBox)
DimstComboTextAsString
stComboText=Ctrl.Text
SelectCasestComboText
Case"FirstClass"
FirstClass
Case"BusinessClass"
BusinessClass
Case"CoachClass"
CoachClass
Case"Standby"
Standby
EndSelect
EndSub
PrivateSubFirstClass()
MsgBox"YouselectedFirstClassreservations"
EndSub
PrivateSubBusinessClass()
MsgBox"YouselectedBusinessClassreservations"
EndSub
PrivateSubCoachClass()
MsgBox"YouselectedCoachClassreservations"
EndSub
PrivateSubStandby()
MsgBox"Youchosetoflystandby"
EndSub
ClickEventOccurswhentheuserclicksaCommandBarButtonobject.
PrivateSubCommandBarButton_Click
(ByValCtrlAsCommandBarButton,
ByValCancelDefaultAsBoolean)
ThesyntaxfortheClickeventincludesthetwoargumentsdescribedinthefollowingtable.
Argument Description
Ctrl RequiredCommandBarButton.DenotestheCommandBarButtoncontrolthatinitiatedtheevent.
CancelDefaultRequiredBoolean.FalseifthedefaultbehaviorassociatedwiththeCommandBarButtoncontroloccurs,unlessit’scanceledbyanotherprocessoradd-in.
Remarks
TheClickeventisrecognizedbytheCommandBarButtonobject.ToreturntheClickeventforaparticularCommandBarButtoncontrol,usetheWithEventskeywordtodeclareavariable,andthensetthevariabletothecontrol.
Example
ThefollowingexamplecreatesanewcommandbarbuttonontheFilemenuofthehostapplicationthatenablestheusertosaveaworkbookasacomma-separatedvaluefile.(Thisexampleworksinallapplications,butthecontextofsavingasCSVisapplicabletoMicrosoftExcel.)
PrivateHostAppAsObject
SubcreateAndSynch()
DimiIndexAsInteger
DimiCountAsInteger
DimfBtnExistsAsBoolean
DimobCmdBtnAsObject
DimbtnSaveAsCSVHandlerasnewClass1
OnErrorGoToerrHandler
SetHostApp=Application
DimbarHelpAsOffice.CommandBar
SetbarHelp=Application.CommandBars("File")
fBtnExists=False
iCount=barHelp.Controls.Count
ForiIndex=1ToiCount
IfbarHelp.Controls(iIndex).Caption="SaveAsCSV(CommaDelimited)"ThenfBtnExists=True
Next
DimbtnSaveAsCSVAsOffice.CommandBarButton
IffBtnExistsThen
SetbtnSaveAsCSV=barHelp.Controls("SaveAsCSV(CommaDelimited)")
Else
SetbtnSaveAsCSV=barHelp.Controls.Add(msoControlButton)
btnSaveAsCSV.Caption="SaveAsCSV(CommaDelimited)"
EndIf
btnSaveAsCSV.Tag="btn1"
btnSaveAsCSVHandler.SyncButtonbtnSaveAsCSV
ExitSub
errHandler:
'Inserterrorhandlingcodehere
EndSub
EnvelopeHideEventOccurswhentheuserinterface(UI)thatcorrespondstotheMsoEnvelopeobjectishidden.
PrivateSubobject_EnvelopHide()
objectAvariablewhichreferencesanobjectoftypeMsoEnvelopedeclaredwitheventsinaclassmodule.
Example
Thefollowingexamplesetsupevent-handlingroutinesfortheMsoEnvelopeobject.
PublicWithEventsenvAsMsoEnvelope
PrivateSubClass_Initialize()
Setenv=Application.ActiveDocument.MailEnvelope
EndSub
PrivateSubenv_EnvelopeShow()
MsgBox"TheMsoEnvelopeUIisshowing."
EndSub
PrivateSubenv_EnvelopeHide()
MsgBox"TheMsoEnvelopeUIishidden."
EndSub
EnvelopeShowEventOccurswhentheuserinterface(UI)thatcorrespondstotheMsoEnvelopeobjectisdisplayed.
PrivateSubobject_EnvelopShow()
objectAvariablewhichreferencesanobjectoftypeMsoEnvelopedeclaredwitheventsinaclassmodule.
Example
Thefollowingexamplesetsupevent-handlingroutinesfortheMsoEnvelopeobject.
PublicWithEventsenvAsMsoEnvelope
PrivateSubClass_Initialize()
Setenv=Application.ActiveDocument.MailEnvelope
EndSub
PrivateSubenv_EnvelopeShow()
MsgBox"TheMsoEnvelopeUIisshowing."
EndSub
PrivateSubenv_EnvelopeHide()
MsgBox"TheMsoEnvelopeUIishidden."
EndSub
OnUpdateEventOccurswhenanychangeismadetoacommandbar.
PrivateSubCommandBars_OnUpdate()
Remarks
TheOnUpdateeventisrecognizedbytheCommandBarobjectandallcommandbarcontrols.Theeventistriggeredbyanychangetoacommandbarorcommandbarcontroloranychangetothestateofacommandbarorcommandbarcontrol.Thesechangescanoccurduetoatextorcellselection,forexample.SincealargenumberofOnUpdateeventscanoccurduringnormalusage,developersshouldexercisecautionwhenusingthisevent.ItisstronglyrecommendedthatthiseventbeusedprimarilyforcheckingthatacustomcommandbarhasbeenaddedorremovedbyaCOMAddIn.
ShowAll
MicrosoftOfficeEnumeratedConstantsThistopicprovidesalistofallenumeratedconstantsintheMicrosoftOfficeobjectmodel.
MailFormat
Constant ValuemfHTML 2mfPlainText 1mfRTF 3
MsoAlertButtonType
Constant ValuemsoAlertButtonAbortRetryIgnore 2msoAlertButtonOK 0msoAlertButtonOKCancel 1msoAlertButtonRetryCancel 5msoAlertButtonYesAllNoCancel 6msoAlertButtonYesNo 4msoAlertButtonYesNoCancel 3
MsoAlertCancelType
Constant ValuemsoAlertCancelDefault -1msoAlertCancelFifth 4msoAlertCancelFirst 0msoAlertCancelFourth 3msoAlertCancelSecond 1
msoAlertCancelThird 2
MsoAlertDefaultType
Constant ValuemsoAlertDefaultFifth 4msoAlertDefaultFirst 0msoAlertDefaultFourth 3msoAlertDefaultSecond 1msoAlertDefaultThird 2
MsoAlertIconType
Constant ValuemsoAlertIconCritical 1msoAlertIconInfo 4msoAlertIconNoIcon 0msoAlertIconQuery 2msoAlertIconWarning 3
MsoAlignCmd
Constant ValuemsoAlignBottoms 5msoAlignCenters 1msoAlignLefts 0msoAlignMiddles 4msoAlignRights 2msoAlignTops 3
MsoAnimationType
Constant ValuemsoAnimationAppear 32
msoAnimationBeginSpeaking 4msoAnimationCharacterSuccessMajor 6msoAnimationCheckingSomething 103msoAnimationDisappear 31msoAnimationEmptyTrash 116msoAnimationGestureDown 113msoAnimationGestureLeft 114msoAnimationGestureRight 19msoAnimationGestureUp 115msoAnimationGetArtsy 100msoAnimationGetAttentionMajor 11msoAnimationGetAttentionMinor 12msoAnimationGetTechy 101msoAnimationGetWizardy 102msoAnimationGoodbye 3msoAnimationGreeting 2msoAnimationIdle 1msoAnimationListensToComputer 26msoAnimationLookDown 104msoAnimationLookDownLeft 105msoAnimationLookDownRight 106msoAnimationLookLeft 107msoAnimationLookRight 108msoAnimationLookUp 109msoAnimationLookUpLeft 110msoAnimationLookUpRight 111msoAnimationPrinting 18msoAnimationRestPose 5msoAnimationSaving 112msoAnimationSearching 13msoAnimationSendingMail 25msoAnimationThinking 24msoAnimationWorkingAtSomething 23
msoAnimationWritingNotingSomething 22
MsoAppLanguageID
Constant ValuemsoLanguageIDExeMode 4msoLanguageIDHelp 3msoLanguageIDInstall 1msoLanguageIDUI 2msoLanguageIDUIPrevious 5
MsoArrowheadLength
Constant ValuemsoArrowheadLengthMedium 2msoArrowheadLengthMixed -2msoArrowheadLong 3msoArrowheadShort 1
MsoArrowheadStyle
Constant ValuemsoArrowheadDiamond 5msoArrowheadNone 1msoArrowheadOpen 3msoArrowheadOval 6msoArrowheadStealth 4msoArrowheadStyleMixed -2msoArrowheadTriangle 2
MsoArrowheadWidth
Constant ValuemsoArrowheadNarrow 1
msoArrowheadWide 3msoArrowheadWidthMedium 2msoArrowheadWidthMixed -2
MsoAutomationSecurity
Constant ValuemsoAutomationSecurityByUI 2msoAutomationSecurityForceDisable 3msoAutomationSecurityLow 1
MsoAutoShapeType
Constant ValuemsoShape16pointStar 94msoShape24pointStar 95msoShape32pointStar 96msoShape4pointStar 91msoShape5pointStar 92msoShape8pointStar 93msoShapeActionButtonBackorPrevious 129msoShapeActionButtonBeginning 131msoShapeActionButtonCustom 125msoShapeActionButtonDocument 134msoShapeActionButtonEnd 132msoShapeActionButtonForwardorNext 130msoShapeActionButtonHelp 127msoShapeActionButtonHome 126msoShapeActionButtonInformation 128msoShapeActionButtonMovie 136msoShapeActionButtonReturn 133msoShapeActionButtonSound 135msoShapeArc 25msoShapeBalloon 137
msoShapeBentArrow 41msoShapeBentUpArrow 44msoShapeBevel 15msoShapeBlockArc 20msoShapeCan 13msoShapeChevron 52msoShapeCircularArrow 60msoShapeCloudCallout 108msoShapeCross 11msoShapeCube 14msoShapeCurvedDownArrow 48msoShapeCurvedDownRibbon 100msoShapeCurvedLeftArrow 46msoShapeCurvedRightArrow 45msoShapeCurvedUpArrow 47msoShapeCurvedUpRibbon 99msoShapeDiamond 4msoShapeDonut 18msoShapeDoubleBrace 27msoShapeDoubleBracket 26msoShapeDoubleWave 104msoShapeDownArrow 36msoShapeDownArrowCallout 56msoShapeDownRibbon 98msoShapeExplosion1 89msoShapeExplosion2 90msoShapeFlowchartAlternateProcess 62msoShapeFlowchartCard 75msoShapeFlowchartCollate 79msoShapeFlowchartConnector 73msoShapeFlowchartData 64msoShapeFlowchartDecision 63msoShapeFlowchartDelay 84
msoShapeFlowchartDirectAccessStorage 87msoShapeFlowchartDisplay 88msoShapeFlowchartDocument 67msoShapeFlowchartExtract 81msoShapeFlowchartInternalStorage 66msoShapeFlowchartMagneticDisk 86msoShapeFlowchartManualInput 71msoShapeFlowchartManualOperation 72msoShapeFlowchartMerge 82msoShapeFlowchartMultidocument 68msoShapeFlowchartOffpageConnector 74msoShapeFlowchartOr 78msoShapeFlowchartPredefinedProcess 65msoShapeFlowchartPreparation 70msoShapeFlowchartProcess 61msoShapeFlowchartPunchedTape 76msoShapeFlowchartSequentialAccessStorage 85msoShapeFlowchartSort 80msoShapeFlowchartStoredData 83msoShapeFlowchartSummingJunction 77msoShapeFlowchartTerminator 69msoShapeFoldedCorner 16msoShapeHeart 21msoShapeHexagon 10msoShapeHorizontalScroll 102msoShapeIsoscelesTriangle 7msoShapeLeftArrow 34msoShapeLeftArrowCallout 54msoShapeLeftBrace 31msoShapeLeftBracket 29msoShapeLeftRightArrow 37msoShapeLeftRightArrowCallout 57msoShapeLeftRightUpArrow 40
msoShapeLeftUpArrow 43msoShapeLightningBolt 22msoShapeLineCallout1 109msoShapeLineCallout1AccentBar 113msoShapeLineCallout1BorderandAccentBar 121msoShapeLineCallout1NoBorder 117msoShapeLineCallout2 110msoShapeLineCallout2AccentBar 114msoShapeLineCallout2BorderandAccentBar 122msoShapeLineCallout2NoBorder 118msoShapeLineCallout3 111msoShapeLineCallout3AccentBar 115msoShapeLineCallout3BorderandAccentBar 123msoShapeLineCallout3NoBorder 119msoShapeLineCallout4 112msoShapeLineCallout4AccentBar 116msoShapeLineCallout4BorderandAccentBar 124msoShapeLineCallout4NoBorder 120msoShapeMixed -2msoShapeMoon 24msoShapeNoSymbol 19msoShapeNotchedRightArrow 50msoShapeNotPrimitive 138msoShapeOctagon 6msoShapeOval 9msoShapeOvalCallout 107msoShapeParallelogram 2msoShapePentagon 51msoShapePlaque 28msoShapeQuadArrow 39msoShapeQuadArrowCallout 59msoShapeRectangle 1msoShapeRectangularCallout 105
msoShapeRegularPentagon 12msoShapeRightArrow 33msoShapeRightArrowCallout 53msoShapeRightBrace 32msoShapeRightBracket 30msoShapeRightTriangle 8msoShapeRoundedRectangle 5msoShapeRoundedRectangularCallout 106msoShapeSmileyFace 17msoShapeStripedRightArrow 49msoShapeSun 23msoShapeTrapezoid 3msoShapeUpArrow 35msoShapeUpArrowCallout 55msoShapeUpDownArrow 38msoShapeUpDownArrowCallout 58msoShapeUpRibbon 97msoShapeUTurnArrow 42msoShapeVerticalScroll 101msoShapeWave 103
MsoBalloonButtonType
Constant ValuemsoBalloonButtonAbort -8msoBalloonButtonBack -5msoBalloonButtonCancel -2msoBalloonButtonClose -12msoBalloonButtonIgnore -9msoBalloonButtonNext -6msoBalloonButtonNo -4msoBalloonButtonNull 0msoBalloonButtonOK -1
msoBalloonButtonOptions -14msoBalloonButtonRetry -7msoBalloonButtonSearch -10msoBalloonButtonSnooze -11msoBalloonButtonTips -13msoBalloonButtonYes -3msoBalloonButtonYesToAll -15
MsoBalloonErrorType
Constant ValuemsoBalloonErrorBadCharacter 8msoBalloonErrorBadPictureRef 4msoBalloonErrorBadReference 5msoBalloonErrorButtonlessModal 6msoBalloonErrorButtonModeless 7msoBalloonErrorCharNotTopmostForModal 10msoBalloonErrorCOMFailure 9msoBalloonErrorNone 0msoBalloonErrorOther 1msoBalloonErrorOutOfMemory 3msoBalloonErrorTooBig 2msoBalloonErrorTooManyControls 11
MsoBalloonType
Constant ValuemsoBalloonTypeBullets 1msoBalloonTypeButtons 0msoBalloonTypeNumbers 2
MsoBarPosition
Constant Value
msoBarBottom 3msoBarFloating 4msoBarLeft 0msoBarMenuBar 6msoBarPopup 5msoBarRight 2msoBarTop 1
MsoBarProtection
Constant ValuemsoBarNoChangeDock 16msoBarNoChangeVisible 8msoBarNoCustomize 1msoBarNoHorizontalDock 64msoBarNoMove 4msoBarNoProtection 0msoBarNoResize 2msoBarNoVerticalDock 32
MsoBarRow
Constant ValuemsoBarRowFirst 0msoBarRowLast -1
MsoBarType
Constant ValuemsoBarTypeMenuBar 1msoBarTypeNormal 0msoBarTypePopup 2
MsoBlackWhiteMode
Constant ValuemsoBlackWhiteAutomatic 1msoBlackWhiteBlack 8msoBlackWhiteBlackTextAndLine 6msoBlackWhiteDontShow 10msoBlackWhiteGrayOutline 5msoBlackWhiteGrayScale 2msoBlackWhiteHighContrast 7msoBlackWhiteInverseGrayScale 4msoBlackWhiteLightGrayScale 3msoBlackWhiteMixed -2msoBlackWhiteWhite 9
MsoButtonSetType
Constant ValuemsoButtonSetAbortRetryIgnore 10msoButtonSetBackClose 6msoButtonSetBackNextClose 8msoButtonSetBackNextSnooze 12msoButtonSetCancel 2msoButtonSetNextClose 7msoButtonSetNone 0msoButtonSetOK 1msoButtonSetOkCancel 3msoButtonSetRetryCancel 9msoButtonSetSearchClose 11msoButtonSetTipsOptionsClose 13msoButtonSetYesAllNoCancel 14msoButtonSetYesNo 4msoButtonSetYesNoCancel 5
MsoButtonState
Constant ValuemsoButtonDown -1msoButtonMixed 2msoButtonUp 0
MsoButtonStyle
Constant ValuemsoButtonAutomatic 0msoButtonCaption 2msoButtonIcon 1msoButtonIconAndCaption 3msoButtonIconAndCaptionBelow 11msoButtonIconAndWrapCaption 7msoButtonIconAndWrapCaptionBelow 15msoButtonWrapCaption 14
MsoCalloutAngleType
Constant ValuemsoCalloutAngle30 2msoCalloutAngle45 3msoCalloutAngle60 4msoCalloutAngle90 5msoCalloutAngleAutomatic 1msoCalloutAngleMixed -2
MsoCalloutDropType
Constant ValuemsoCalloutDropBottom 4msoCalloutDropCenter 3msoCalloutDropCustom 1msoCalloutDropMixed -2
msoCalloutDropTop 2
MsoCalloutType
Constant ValuemsoCalloutFour 4msoCalloutMixed -2msoCalloutOne 1msoCalloutThree 3msoCalloutTwo 2
MsoCharacterSet
Constant ValuemsoCharacterSetArabic 1msoCharacterSetCyrillic 2msoCharacterSetEnglishWesternEuropeanOtherLatinScript 3msoCharacterSetGreek 4msoCharacterSetHebrew 5msoCharacterSetJapanese 6msoCharacterSetKorean 7msoCharacterSetMultilingualUnicode 8msoCharacterSetSimplifiedChinese 9msoCharacterSetThai 10msoCharacterSetTraditionalChinese 11msoCharacterSetVietnamese 12
MsoColorType
Constant ValuemsoColorTypeCMS 4msoColorTypeCMYK 3msoColorTypeInk 5msoColorTypeMixed -2
msoColorTypeRGB 1msoColorTypeScheme 2
MsoComboStyle
Constant ValuemsoComboLabel 1msoComboNormal 0
MsoCommandBarButtonHyperlinkType
Constant ValuemsoCommandBarButtonHyperlinkInsertPicture 2msoCommandBarButtonHyperlinkNone 0msoCommandBarButtonHyperlinkOpen 1
MsoCondition
Constant ValuemsoConditionAnyNumberBetween 34msoConditionAnytime 25msoConditionAnytimeBetween 26msoConditionAtLeast 36msoConditionAtMost 35msoConditionBeginsWith 11msoConditionDoesNotEqual 33msoConditionEndsWith 12msoConditionEquals 32msoConditionEqualsCompleted 66msoConditionEqualsDeferred 68msoConditionEqualsHigh 60msoConditionEqualsInProgress 65msoConditionEqualsLow 58msoConditionEqualsNormal 59
msoConditionEqualsNotStarted 64msoConditionEqualsWaitingForSomeoneElse 67msoConditionFileTypeAllFiles 1msoConditionFileTypeBinders 6msoConditionFileTypeCalendarItem 45msoConditionFileTypeContactItem 46msoConditionFileTypeDatabases 7msoConditionFileTypeDataConnectionFiles 51msoConditionFileTypeDesignerFiles 56msoConditionFileTypeDocumentImagingFiles 54msoConditionFileTypeExcelWorkbooks 4msoConditionFileTypeJournalItem 48msoConditionFileTypeMailItem 44msoConditionFileTypeNoteItem 47msoConditionFileTypeOfficeFiles 2msoConditionFileTypeOutlookItems 43msoConditionFileTypePhotoDrawFiles 50msoConditionFileTypePowerPointPresentations 5msoConditionFileTypeProjectFiles 53msoConditionFileTypePublisherFiles 52msoConditionFileTypeTaskItem 49msoConditionFileTypeTemplates 8msoConditionFileTypeVisioFiles 55msoConditionFileTypeWebPages 57msoConditionFileTypeWordDocuments 3msoConditionFreeText 42msoConditionIncludes 9msoConditionIncludesFormsOf 41msoConditionIncludesNearEachOther 13msoConditionIncludesPhrase 10msoConditionInTheLast 31msoConditionInTheNext 30msoConditionIsExactly 14
msoConditionIsNo 40msoConditionIsNot 15msoConditionIsYes 39msoConditionLastMonth 22msoConditionLastWeek 19msoConditionLessThan 38msoConditionMoreThan 37msoConditionNextMonth 24msoConditionNextWeek 21msoConditionNotEqualToCompleted 71msoConditionNotEqualToDeferred 73msoConditionNotEqualToHigh 63msoConditionNotEqualToInProgress 70msoConditionNotEqualToLow 61msoConditionNotEqualToNormal 62msoConditionNotEqualToNotStarted 69msoConditionNotEqualToWaitingForSomeoneElse 72msoConditionOn 27msoConditionOnOrAfter 28msoConditionOnOrBefore 29msoConditionThisMonth 23msoConditionThisWeek 20msoConditionToday 17msoConditionTomorrow 18msoConditionYesterday 16
MsoConnector
Constant ValuemsoConnectorAnd 1msoConnectorOr 2
MsoConnectorType
Constant ValuemsoConnectorCurve 3msoConnectorElbow 2msoConnectorStraight 1msoConnectorTypeMixed -2
MsoControlOLEUsage
Constant ValuemsoControlOLEUsageBoth 3msoControlOLEUsageClient 2msoControlOLEUsageNeither 0msoControlOLEUsageServer 1
MsoControlType
Constant ValuemsoControlActiveX 22msoControlAutoCompleteCombo 26msoControlButton 1msoControlButtonDropdown 5msoControlButtonPopup 12msoControlComboBox 4msoControlCustom 0msoControlDropdown 3msoControlEdit 2msoControlExpandingGrid 16msoControlGauge 19msoControlGenericDropdown 8msoControlGraphicCombo 20msoControlGraphicDropdown 9msoControlGraphicPopup 11msoControlGrid 18msoControlLabel 15
msoControlLabelEx 24msoControlOCXDropdown 7msoControlPane 21msoControlPopup 10msoControlSpinner 23msoControlSplitButtonMRUPopup 14msoControlSplitButtonPopup 13msoControlSplitDropdown 6msoControlSplitExpandingGrid 17msoControlWorkPane 25
MsoDiagramNodeType
Constant ValuemsoDiagramAssistant 2msoDiagramNode 1
MsoDiagramType
Constant ValuemsoDiagramCycle 2msoDiagramMixed -2msoDiagramOrgChart 1msoDiagramPyramid 4msoDiagramRadial 3msoDiagramTarget 6msoDiagramVenn 5
MsoDistributeCmd
Constant ValuemsoDistributeHorizontally 0msoDistributeVertically 1
MsoDocProperties
Constant ValuemsoPropertyTypeBoolean 2msoPropertyTypeDate 3msoPropertyTypeFloat 5msoPropertyTypeNumber 1msoPropertyTypeString 4
MsoEditingType
Constant ValuemsoEditingAuto 0msoEditingCorner 1msoEditingSmooth 2msoEditingSymmetric 3
MsoEncoding
Constant ValuemsoEncodingArabic 1256msoEncodingArabicASMO 708msoEncodingArabicAutoDetect 51256msoEncodingArabicTransparentASMO 720msoEncodingAutoDetect 50001msoEncodingBaltic 1257msoEncodingCentralEuropean 1250msoEncodingCyrillic 1251msoEncodingCyrillicAutoDetect 51251msoEncodingEBCDICArabic 20420msoEncodingEBCDICDenmarkNorway 20277msoEncodingEBCDICFinlandSweden 20278msoEncodingEBCDICFrance 20297msoEncodingEBCDICGermany 20273
msoEncodingEBCDICGreek 20423msoEncodingEBCDICGreekModern 875msoEncodingEBCDICHebrew 20424msoEncodingEBCDICIcelandic 20871msoEncodingEBCDICInternational 500msoEncodingEBCDICItaly 20280msoEncodingEBCDICJapaneseKatakanaExtended 20290msoEncodingEBCDICJapaneseKatakanaExtendedAndJapanese 50930msoEncodingEBCDICJapaneseLatinExtendedAndJapanese 50939msoEncodingEBCDICKoreanExtended 20833msoEncodingEBCDICKoreanExtendedAndKorean 50933msoEncodingEBCDICLatinAmericaSpain 20284msoEncodingEBCDICMultilingualROECELatin2 870msoEncodingEBCDICRussian 20880msoEncodingEBCDICSerbianBulgarian 21025msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese 50935msoEncodingEBCDICThai 20838msoEncodingEBCDICTurkish 20905msoEncodingEBCDICTurkishLatin5 1026msoEncodingEBCDICUnitedKingdom 20285msoEncodingEBCDICUSCanada 37msoEncodingEBCDICUSCanadaAndJapanese 50931msoEncodingEBCDICUSCanadaAndTraditionalChinese 50937msoEncodingEUCChineseSimplifiedChinese 51936msoEncodingEUCJapanese 51932msoEncodingEUCKorean 51949msoEncodingEUCTaiwaneseTraditionalChinese 51950msoEncodingEuropa3 29001msoEncodingExtAlphaLowercase 21027msoEncodingGreek 1253msoEncodingGreekAutoDetect 51253msoEncodingHebrew 1255msoEncodingHZGBSimplifiedChinese 52936
msoEncodingIA5German 20106msoEncodingIA5IRV 20105msoEncodingIA5Norwegian 20108msoEncodingIA5Swedish 20107msoEncodingISCIIAssamese 57006msoEncodingISCIIBengali 57003msoEncodingISCIIDevanagari 57002msoEncodingISCIIGujarati 57010msoEncodingISCIIKannada 57008msoEncodingISCIIMalayalam 57009msoEncodingISCIIOriya 57007msoEncodingISCIIPunjabi 57011msoEncodingISCIITamil 57004msoEncodingISCIITelugu 57005msoEncodingISO2022CNSimplifiedChinese 50229msoEncodingISO2022CNTraditionalChinese 50227msoEncodingISO2022JPJISX02011989 50222msoEncodingISO2022JPJISX02021984 50221msoEncodingISO2022JPNoHalfwidthKatakana 50220msoEncodingISO2022KR 50225msoEncodingISO6937NonSpacingAccent 20269msoEncodingISO885915Latin9 28605msoEncodingISO88591Latin1 28591msoEncodingISO88592CentralEurope 28592msoEncodingISO88593Latin3 28593msoEncodingISO88594Baltic 28594msoEncodingISO88595Cyrillic 28595msoEncodingISO88596Arabic 28596msoEncodingISO88597Greek 28597msoEncodingISO88598Hebrew 28598msoEncodingISO88599Turkish 28599msoEncodingJapaneseAutoDetect 50932msoEncodingJapaneseShiftJIS 932
msoEncodingKOI8R 20866msoEncodingKOI8U 21866msoEncodingKorean 949msoEncodingKoreanAutoDetect 50949msoEncodingKoreanJohab 1361msoEncodingMacArabic 10004msoEncodingMacCroatia 10082msoEncodingMacCyrillic 10007msoEncodingMacGreek1 10006msoEncodingMacHebrew 10005msoEncodingMacIcelandic 10079msoEncodingMacJapanese 10001msoEncodingMacKorean 10003msoEncodingMacLatin2 10029msoEncodingMacRoman 10000msoEncodingMacRomania 10010msoEncodingMacSimplifiedChineseGB2312 10008msoEncodingMacTraditionalChineseBig5 10002msoEncodingMacTurkish 10081msoEncodingMacUkraine 10017msoEncodingOEMArabic 864msoEncodingOEMBaltic 775msoEncodingOEMCanadianFrench 863msoEncodingOEMCyrillic 855msoEncodingOEMCyrillicII 866msoEncodingOEMGreek437G 737msoEncodingOEMHebrew 862msoEncodingOEMIcelandic 861msoEncodingOEMModernGreek 869msoEncodingOEMMultilingualLatinI 850msoEncodingOEMMultilingualLatinII 852msoEncodingOEMNordic 865msoEncodingOEMPortuguese 860
msoEncodingOEMTurkish 857msoEncodingOEMUnitedStates 437msoEncodingSimplifiedChineseAutoDetect 50936msoEncodingSimplifiedChineseGBK 936msoEncodingT61 20261msoEncodingTaiwanCNS 20000msoEncodingTaiwanEten 20002msoEncodingTaiwanIBM5550 20003msoEncodingTaiwanTCA 20001msoEncodingTaiwanTeleText 20004msoEncodingTaiwanWang 20005msoEncodingThai 874msoEncodingTraditionalChineseAutoDetect 50950msoEncodingTraditionalChineseBig5 950msoEncodingTurkish 1254msoEncodingUnicodeBigEndian 1201msoEncodingUnicodeLittleEndian 1200msoEncodingUSASCII 20127msoEncodingUTF7 65000msoEncodingUTF8 65001msoEncodingVietnamese 1258msoEncodingWestern 1252
MsoExtraInfoMethod
Constant ValuemsoMethodGet 0msoMethodPost 1
MsoExtrusionColorType
Constant ValuemsoExtrusionColorAutomatic 1msoExtrusionColorCustom 2
msoExtrusionColorTypeMixed -2
MsoFarEastLineBreakLanguageID
Constant ValueMsoFarEastLineBreakLanguageJapanese 1041MsoFarEastLineBreakLanguageKorean 1042MsoFarEastLineBreakLanguageSimplifiedChinese 2052MsoFarEastLineBreakLanguageTraditionalChinese 1028
MsoFeatureInstall
Constant ValuemsoFeatureInstallNone 0msoFeatureInstallOnDemand 1msoFeatureInstallOnDemandWithUI 2
MsoFileDialogType
Constant ValuemsoFileDialogFilePicker 3msoFileDialogFolderPicker 4msoFileDialogOpen 1msoFileDialogSaveAs 2
MsoFileDialogView
Constant ValuemsoFileDialogViewDetails 2msoFileDialogViewLargeIcons 6msoFileDialogViewList 1msoFileDialogViewPreview 4msoFileDialogViewProperties 3msoFileDialogViewSmallIcons 7
msoFileDialogViewThumbnail 5msoFileDialogViewTiles 9msoFileDialogViewWebView 8
MsoFileFindListBy
Constant ValuemsoListbyName 1msoListbyTitle 2
MsoFileFindOptions
Constant ValuemsoOptionsAdd 2msoOptionsNew 1msoOptionsWithin 3
MsoFileFindSortBy
Constant ValuemsoFileFindSortbyAuthor 1msoFileFindSortbyDateCreated 2msoFileFindSortbyDateSaved 4msoFileFindSortbyFileName 5msoFileFindSortbyLastSavedBy 3msoFileFindSortbySize 6msoFileFindSortbyTitle 7
MsoFileFindView
Constant ValuemsoViewFileInfo 1msoViewPreview 2msoViewSummaryInfo 3
MsoFileNewAction
Constant ValuemsoCreateNewFile 1msoEditFile 0msoOpenFile 2
MsoFileNewSection
Constant ValuemsoBottomSection 4msoNew 1msoNewfromExistingFile 2msoNewfromTemplate 3msoOpenDocument 0
MsoFileType
Constant ValuemsoFileTypeAllFiles 1msoFileTypeBinders 6msoFileTypeCalendarItem 11msoFileTypeContactItem 12msoFileTypeDatabases 7msoFileTypeDataConnectionFiles 17msoFileTypeDesignerFiles 22msoFileTypeDocumentImagingFiles 20msoFileTypeExcelWorkbooks 4msoFileTypeJournalItem 14msoFileTypeMailItem 10msoFileTypeNoteItem 13msoFileTypeOfficeFiles 2msoFileTypeOutlookItems 9msoFileTypePhotoDrawFiles 16
msoFileTypePowerPointPresentations 5msoFileTypeProjectFiles 19msoFileTypePublisherFiles 18msoFileTypeTaskItem 15msoFileTypeTemplates 8msoFileTypeVisioFiles 21msoFileTypeWebPages 23msoFileTypeWordDocuments 3
MsoFillType
Constant ValuemsoFillBackground 5msoFillGradient 3msoFillMixed -2msoFillPatterned 2msoFillPicture 6msoFillSolid 1msoFillTextured 4
MsoFilterComparison
Constant ValuemsoFilterComparisonContains 8msoFilterComparisonEqual 0msoFilterComparisonGreaterThan 3msoFilterComparisonGreaterThanEqual 5msoFilterComparisonIsBlank 6msoFilterComparisonIsNotBlank 7msoFilterComparisonLessThan 2msoFilterComparisonLessThanEqual 4msoFilterComparisonNotContains 9msoFilterComparisonNotEqual 1
MsoFilterConjunction
Constant ValuemsoFilterConjunctionAnd 0msoFilterConjunctionOr 1
MsoFlipCmd
Constant ValuemsoFlipHorizontal 0msoFlipVertical 1
MsoGradientColorType
Constant ValuemsoGradientColorMixed -2msoGradientOneColor 1msoGradientPresetColors 3msoGradientTwoColors 2
MsoGradientStyle
Constant ValuemsoGradientDiagonalDown 4msoGradientDiagonalUp 3msoGradientFromCenter 7msoGradientFromCorner 5msoGradientFromTitle 6msoGradientHorizontal 1msoGradientMixed -2msoGradientVertical 2
MsoHorizontalAnchor
Constant ValuemsoAnchorCenter 2msoAnchorNone 1msoHorizontalAnchorMixed -2
MsoHTMLProjectOpen
Constant ValuemsoHTMLProjectOpenSourceView 1msoHTMLProjectOpenTextView 2
MsoHTMLProjectState
Constant ValuemsoHTMLProjectStateDocumentLocked 1msoHTMLProjectStateDocumentProjectUnlocked 3msoHTMLProjectStateProjectLocked 2
MsoHyperlinkType
Constant ValuemsoHyperlinkInlineShape 2msoHyperlinkRange 0msoHyperlinkShape 1
MsoIconType
Constant ValuemsoIconAlert 2msoIconAlertCritical 7msoIconAlertInfo 4msoIconAlertQuery 6msoIconAlertWarning 5msoIconNone 0
msoIconTip 3
MsoLanguageID
Constant ValuemsoLanguageIDAfrikaans 1078msoLanguageIDAlbanian 1052msoLanguageIDAmharic 1118msoLanguageIDArabic 1025msoLanguageIDArabicAlgeria 5121msoLanguageIDArabicBahrain 15361msoLanguageIDArabicEgypt 3073msoLanguageIDArabicIraq 2049msoLanguageIDArabicJordan 11265msoLanguageIDArabicKuwait 13313msoLanguageIDArabicLebanon 12289msoLanguageIDArabicLibya 4097msoLanguageIDArabicMorocco 6145msoLanguageIDArabicOman 8193msoLanguageIDArabicQatar 16385msoLanguageIDArabicSyria 10241msoLanguageIDArabicTunisia 7169msoLanguageIDArabicUAE 14337msoLanguageIDArabicYemen 9217msoLanguageIDArmenian 1067msoLanguageIDAssamese 1101msoLanguageIDAzeriCyrillic 2092msoLanguageIDAzeriLatin 1068msoLanguageIDBasque 1069msoLanguageIDBelgianDutch 2067msoLanguageIDBelgianFrench 2060msoLanguageIDBengali 1093msoLanguageIDBosnian 4122
msoLanguageIDBrazilianPortuguese 1046msoLanguageIDBulgarian 1026msoLanguageIDBurmese 1109msoLanguageIDByelorussian 1059msoLanguageIDCatalan 1027msoLanguageIDCherokee 1116msoLanguageIDChineseHongKong 3076msoLanguageIDChineseHongKongSAR 3076msoLanguageIDChineseMacao 5124msoLanguageIDChineseMacaoSAR 5124msoLanguageIDChineseSingapore 4100msoLanguageIDCroatian 1050msoLanguageIDCzech 1029msoLanguageIDDanish 1030msoLanguageIDDivehi 1125msoLanguageIDDutch 1043msoLanguageIDDzongkhaBhutan 2129msoLanguageIDEdo 1126msoLanguageIDEnglishAUS 3081msoLanguageIDEnglishBelize 10249msoLanguageIDEnglishCanadian 4105msoLanguageIDEnglishCaribbean 9225msoLanguageIDEnglishIndonesia 14345msoLanguageIDEnglishIreland 6153msoLanguageIDEnglishJamaica 8201msoLanguageIDEnglishNewZealand 5129msoLanguageIDEnglishPhilippines 13321msoLanguageIDEnglishSouthAfrica 7177msoLanguageIDEnglishTrinidad 11273msoLanguageIDEnglishTrinidadTobago 11273msoLanguageIDEnglishUK 2057msoLanguageIDEnglishUS 1033msoLanguageIDEnglishZimbabwe 12297
msoLanguageIDEstonian 1061msoLanguageIDFaeroese 1080msoLanguageIDFarsi 1065msoLanguageIDFilipino 1124msoLanguageIDFinnish 1035msoLanguageIDFrench 1036msoLanguageIDFrenchCameroon 11276msoLanguageIDFrenchCanadian 3084msoLanguageIDFrenchCotedIvoire 12300msoLanguageIDFrenchHaiti 15372msoLanguageIDFrenchLuxembourg 5132msoLanguageIDFrenchMali 13324msoLanguageIDFrenchMonaco 6156msoLanguageIDFrenchMorocco 14348msoLanguageIDFrenchReunion 8204msoLanguageIDFrenchSenegal 10252msoLanguageIDFrenchWestIndies 7180msoLanguageIDFrenchZaire 9228msoLanguageIDFrisianNetherlands 1122msoLanguageIDFulfulde 1127msoLanguageIDGaelicIreland 2108msoLanguageIDGaelicScotland 1084msoLanguageIDGalician 1110msoLanguageIDGeorgian 1079msoLanguageIDGerman 1031msoLanguageIDGermanAustria 3079msoLanguageIDGermanLiechtenstein 5127msoLanguageIDGermanLuxembourg 4103msoLanguageIDGreek 1032msoLanguageIDGuarani 1140msoLanguageIDGujarati 1095msoLanguageIDHausa 1128msoLanguageIDHawaiian 1141
msoLanguageIDHebrew 1037msoLanguageIDHindi 1081msoLanguageIDHungarian 1038msoLanguageIDIbibio 1129msoLanguageIDIcelandic 1039msoLanguageIDIgbo 1136msoLanguageIDIndonesian 1057msoLanguageIDInuktitut 1117msoLanguageIDItalian 1040msoLanguageIDJapanese 1041msoLanguageIDKannada 1099msoLanguageIDKanuri 1137msoLanguageIDKashmiri 1120msoLanguageIDKashmiriDevanagari 2144msoLanguageIDKashmiriIndia 2144msoLanguageIDKazakh 1087msoLanguageIDKhmer 1107msoLanguageIDKirghiz 1088msoLanguageIDKonkani 1111msoLanguageIDKorean 1042msoLanguageIDKyrgyz 1088msoLanguageIDLao 1108msoLanguageIDLatin 1142msoLanguageIDLatvian 1062msoLanguageIDLithuanian 1063msoLanguageIDMacedonian 1071msoLanguageIDMalayalam 1100msoLanguageIDMalayBruneiDarussalam 2110msoLanguageIDMalaysian 1086msoLanguageIDMaltese 1082msoLanguageIDManipuri 1112msoLanguageIDMaori 1153msoLanguageIDMarathi 1102
msoLanguageIDMexicanSpanish 2058msoLanguageIDMixed -2msoLanguageIDMongolian 1104msoLanguageIDNepali 1121msoLanguageIDNone 0msoLanguageIDNoProofing 1024msoLanguageIDNorwegianBokmol 1044msoLanguageIDNorwegianNynorsk 2068msoLanguageIDOriya 1096msoLanguageIDOromo 1138msoLanguageIDPashto 1123msoLanguageIDPolish 1045msoLanguageIDPortuguese 2070msoLanguageIDPunjabi 1094msoLanguageIDRhaetoRomanic 1047msoLanguageIDRomanian 1048msoLanguageIDRomanianMoldova 2072msoLanguageIDRussian 1049msoLanguageIDRussianMoldova 2073msoLanguageIDSamiLappish 1083msoLanguageIDSanskrit 1103msoLanguageIDSerbianCyrillic 3098msoLanguageIDSerbianLatin 2074msoLanguageIDSesotho 1072msoLanguageIDSimplifiedChinese 2052msoLanguageIDSindhi 1113msoLanguageIDSindhiPakistan 2137msoLanguageIDSinhalese 1115msoLanguageIDSlovak 1051msoLanguageIDSlovenian 1060msoLanguageIDSomali 1143msoLanguageIDSorbian 1070msoLanguageIDSpanish 1034
msoLanguageIDSpanishArgentina 11274msoLanguageIDSpanishBolivia 16394msoLanguageIDSpanishChile 13322msoLanguageIDSpanishColombia 9226msoLanguageIDSpanishCostaRica 5130msoLanguageIDSpanishDominicanRepublic 7178msoLanguageIDSpanishEcuador 12298msoLanguageIDSpanishElSalvador 17418msoLanguageIDSpanishGuatemala 4106msoLanguageIDSpanishHonduras 18442msoLanguageIDSpanishModernSort 3082msoLanguageIDSpanishNicaragua 19466msoLanguageIDSpanishPanama 6154msoLanguageIDSpanishParaguay 15370msoLanguageIDSpanishPeru 10250msoLanguageIDSpanishPuertoRico 20490msoLanguageIDSpanishUruguay 14346msoLanguageIDSpanishVenezuela 8202msoLanguageIDSutu 1072msoLanguageIDSwahili 1089msoLanguageIDSwedish 1053msoLanguageIDSwedishFinland 2077msoLanguageIDSwissFrench 4108msoLanguageIDSwissGerman 2055msoLanguageIDSwissItalian 2064msoLanguageIDSyriac 1114msoLanguageIDTajik 1064msoLanguageIDTamazight 1119msoLanguageIDTamazightLatin 2143msoLanguageIDTamil 1097msoLanguageIDTatar 1092msoLanguageIDTelugu 1098msoLanguageIDThai 1054
msoLanguageIDTibetan 1105msoLanguageIDTigrignaEritrea 2163msoLanguageIDTigrignaEthiopic 1139msoLanguageIDTraditionalChinese 1028msoLanguageIDTsonga 1073msoLanguageIDTswana 1074msoLanguageIDTurkish 1055msoLanguageIDTurkmen 1090msoLanguageIDUkrainian 1058msoLanguageIDUrdu 1056msoLanguageIDUzbekCyrillic 2115msoLanguageIDUzbekLatin 1091msoLanguageIDVenda 1075msoLanguageIDVietnamese 1066msoLanguageIDWelsh 1106msoLanguageIDXhosa 1076msoLanguageIDYi 1144msoLanguageIDYiddish 1085msoLanguageIDYoruba 1130msoLanguageIDZulu 1077
MsoLastModified
Constant ValuemsoLastModifiedAnyTime 7msoLastModifiedLastMonth 5msoLastModifiedLastWeek 3msoLastModifiedThisMonth 6msoLastModifiedThisWeek 4msoLastModifiedToday 2msoLastModifiedYesterday 1
MsoLineDashStyle
Constant ValuemsoLineDash 4msoLineDashDot 5msoLineDashDotDot 6msoLineDashStyleMixed -2msoLineLongDash 7msoLineLongDashDot 8msoLineRoundDot 3msoLineSolid 1msoLineSquareDot 2
MsoLineStyle
Constant ValuemsoLineSingle 1msoLineStyleMixed -2msoLineThickBetweenThin 5msoLineThickThin 4msoLineThinThick 3msoLineThinThin 2
MsoMenuAnimation
Constant ValuemsoMenuAnimationNone 0msoMenuAnimationRandom 1msoMenuAnimationSlide 3msoMenuAnimationUnfold 2
MsoMixedType
Constant ValuemsoIntegerMixed 32768msoSingleMixed -2147483648
MsoModeType
Constant ValuemsoModeAutoDown 1msoModeModal 0msoModeModeless 2
MsoMoveRow
Constant ValuemsoMoveRowFirst -4msoMoveRowNbr -1msoMoveRowNext -2msoMoveRowPrev -3
MsoOLEMenuGroup
Constant ValuemsoOLEMenuGroupContainer 2msoOLEMenuGroupEdit 1msoOLEMenuGroupFile 0msoOLEMenuGroupHelp 5msoOLEMenuGroupNone -1msoOLEMenuGroupObject 3msoOLEMenuGroupWindow 4
MsoOrgChartLayoutType
Constant ValuemsoOrgChartLayoutBothHanging 2msoOrgChartLayoutLeftHanging 3msoOrgChartLayoutMixed -2msoOrgChartLayoutRightHanging 4msoOrgChartLayoutStandard 1
MsoOrgChartOrientation
Constant ValuemsoOrgChartOrientationMixed -2msoOrgChartOrientationVertical 1
MsoOrientation
Constant ValuemsoOrientationHorizontal 1msoOrientationMixed -2msoOrientationVertical 2
MsoPatternType
Constant ValuemsoPattern10Percent 2msoPattern20Percent 3msoPattern25Percent 4msoPattern30Percent 5msoPattern40Percent 6msoPattern50Percent 7msoPattern5Percent 1msoPattern60Percent 8msoPattern70Percent 9msoPattern75Percent 10msoPattern80Percent 11msoPattern90Percent 12msoPatternDarkDownwardDiagonal 15msoPatternDarkHorizontal 13msoPatternDarkUpwardDiagonal 16msoPatternDarkVertical 14msoPatternDashedDownwardDiagonal 28msoPatternDashedHorizontal 32
msoPatternDashedUpwardDiagonal 27msoPatternDashedVertical 31msoPatternDiagonalBrick 40msoPatternDivot 46msoPatternDottedDiamond 24msoPatternDottedGrid 45msoPatternHorizontalBrick 35msoPatternLargeCheckerBoard 36msoPatternLargeConfetti 33msoPatternLargeGrid 34msoPatternLightDownwardDiagonal 21msoPatternLightHorizontal 19msoPatternLightUpwardDiagonal 22msoPatternLightVertical 20msoPatternMixed -2msoPatternNarrowHorizontal 30msoPatternNarrowVertical 29msoPatternOutlinedDiamond 41msoPatternPlaid 42msoPatternShingle 47msoPatternSmallCheckerBoard 17msoPatternSmallConfetti 37msoPatternSmallGrid 23msoPatternSolidDiamond 39msoPatternSphere 43msoPatternTrellis 18msoPatternWave 48msoPatternWeave 44msoPatternWideDownwardDiagonal 25msoPatternWideUpwardDiagonal 26msoPatternZigZag 38
MsoPermission
Constant ValuemsoPermissionChange 15msoPermissionEdit 2msoPermissionExtract 8msoPermissionFullControl 64msoPermissionObjModel 32msoPermissionPrint 16msoPermissionRead 1msoPermissionSave 4msoPermissionView 1
MsoPictureColorType
Constant ValuemsoPictureAutomatic 1msoPictureBlackAndWhite 3msoPictureGrayscale 2msoPictureMixed -2msoPictureWatermark 4
MsoPresetExtrusionDirection
Constant ValuemsoExtrusionBottom 2msoExtrusionBottomLeft 3msoExtrusionBottomRight 1msoExtrusionLeft 6msoExtrusionNone 5msoExtrusionRight 4msoExtrusionTop 8msoExtrusionTopLeft 9msoExtrusionTopRight 7msoPresetExtrusionDirectionMixed -2
MsoPresetGradientType
Constant ValuemsoGradientBrass 20msoGradientCalmWater 8msoGradientChrome 21msoGradientChromeII 22msoGradientDaybreak 4msoGradientDesert 6msoGradientEarlySunset 1msoGradientFire 9msoGradientFog 10msoGradientGold 18msoGradientGoldII 19msoGradientHorizon 5msoGradientLateSunset 2msoGradientMahogany 15msoGradientMoss 11msoGradientNightfall 3msoGradientOcean 7msoGradientParchment 14msoGradientPeacock 12msoGradientRainbow 16msoGradientRainbowII 17msoGradientSapphire 24msoGradientSilver 23msoGradientWheat 13msoPresetGradientMixed -2
MsoPresetLightingDirection
Constant ValuemsoLightingBottom 8
msoLightingBottomLeft 7msoLightingBottomRight 9msoLightingLeft 4msoLightingNone 5msoLightingRight 6msoLightingTop 2msoLightingTopLeft 1msoLightingTopRight 3msoPresetLightingDirectionMixed -2
MsoPresetLightingSoftness
Constant ValuemsoLightingBright 3msoLightingDim 1msoLightingNormal 2msoPresetLightingSoftnessMixed -2
MsoPresetMaterial
Constant ValuemsoMaterialMatte 1msoMaterialMetal 3msoMaterialPlastic 2msoMaterialWireFrame 4msoPresetMaterialMixed -2
MsoPresetTextEffect
Constant ValuemsoTextEffect1 0msoTextEffect10 9msoTextEffect11 10msoTextEffect12 11
msoTextEffect13 12msoTextEffect14 13msoTextEffect15 14msoTextEffect16 15msoTextEffect17 16msoTextEffect18 17msoTextEffect19 18msoTextEffect2 1msoTextEffect20 19msoTextEffect21 20msoTextEffect22 21msoTextEffect23 22msoTextEffect24 23msoTextEffect25 24msoTextEffect26 25msoTextEffect27 26msoTextEffect28 27msoTextEffect29 28msoTextEffect3 2msoTextEffect30 29msoTextEffect4 3msoTextEffect5 4msoTextEffect6 5msoTextEffect7 6msoTextEffect8 7msoTextEffect9 8msoTextEffectMixed -2
MsoPresetTextEffectShape
Constant ValuemsoTextEffectShapeArchDownCurve 10msoTextEffectShapeArchDownPour 14
msoTextEffectShapeArchUpCurve 9msoTextEffectShapeArchUpPour 13msoTextEffectShapeButtonCurve 12msoTextEffectShapeButtonPour 16msoTextEffectShapeCanDown 20msoTextEffectShapeCanUp 19msoTextEffectShapeCascadeDown 40msoTextEffectShapeCascadeUp 39msoTextEffectShapeChevronDown 6msoTextEffectShapeChevronUp 5msoTextEffectShapeCircleCurve 11msoTextEffectShapeCirclePour 15msoTextEffectShapeCurveDown 18msoTextEffectShapeCurveUp 17msoTextEffectShapeDeflate 26msoTextEffectShapeDeflateBottom 28msoTextEffectShapeDeflateInflate 31msoTextEffectShapeDeflateInflateDeflate 32msoTextEffectShapeDeflateTop 30msoTextEffectShapeDoubleWave1 23msoTextEffectShapeDoubleWave2 24msoTextEffectShapeFadeDown 36msoTextEffectShapeFadeLeft 34msoTextEffectShapeFadeRight 33msoTextEffectShapeFadeUp 35msoTextEffectShapeInflate 25msoTextEffectShapeInflateBottom 27msoTextEffectShapeInflateTop 29msoTextEffectShapeMixed -2msoTextEffectShapePlainText 1msoTextEffectShapeRingInside 7msoTextEffectShapeRingOutside 8msoTextEffectShapeSlantDown 38
msoTextEffectShapeSlantUp 37msoTextEffectShapeStop 2msoTextEffectShapeTriangleDown 4msoTextEffectShapeTriangleUp 3msoTextEffectShapeWave1 21msoTextEffectShapeWave2 22
MsoPresetTexture
Constant ValuemsoPresetTextureMixed -2msoTextureBlueTissuePaper 17msoTextureBouquet 20msoTextureBrownMarble 11msoTextureCanvas 2msoTextureCork 21msoTextureDenim 3msoTextureFishFossil 7msoTextureGranite 12msoTextureGreenMarble 9msoTextureMediumWood 24msoTextureNewsprint 13msoTextureOak 23msoTexturePaperBag 6msoTexturePapyrus 1msoTextureParchment 15msoTexturePinkTissuePaper 18msoTexturePurpleMesh 19msoTextureRecycledPaper 14msoTextureSand 8msoTextureStationery 16msoTextureWalnut 22msoTextureWaterDroplets 5
msoTextureWhiteMarble 10msoTextureWovenMat 4
MsoPresetThreeDFormat
Constant ValuemsoPresetThreeDFormatMixed -2msoThreeD1 1msoThreeD10 10msoThreeD11 11msoThreeD12 12msoThreeD13 13msoThreeD14 14msoThreeD15 15msoThreeD16 16msoThreeD17 17msoThreeD18 18msoThreeD19 19msoThreeD2 2msoThreeD20 20msoThreeD3 3msoThreeD4 4msoThreeD5 5msoThreeD6 6msoThreeD7 7msoThreeD8 8msoThreeD9 9
MsoRelativeNodePosition
Constant ValuemsoAfterLastSibling 4msoAfterNode 2msoBeforeFirstSibling 3
msoBeforeNode 1
MsoScaleFrom
Constant ValuemsoScaleFromBottomRight 2msoScaleFromMiddle 1msoScaleFromTopLeft 0
MsoScreenSize
Constant ValuemsoScreenSize1024x768 4msoScreenSize1152x882 5msoScreenSize1152x900 6msoScreenSize1280x1024 7msoScreenSize1600x1200 8msoScreenSize1800x1440 9msoScreenSize1920x1200 10msoScreenSize544x376 0msoScreenSize640x480 1msoScreenSize720x512 2msoScreenSize800x600 3
MsoScriptLanguage
Constant ValuemsoScriptLanguageASP 3msoScriptLanguageJava 1msoScriptLanguageOther 4msoScriptLanguageVisualBasic 2
MsoScriptLocation
Constant ValuemsoScriptLocationInBody 2msoScriptLocationInHead 1
MsoSearchIn
Constant ValuemsoSearchInCustom 3msoSearchInMyComputer 0msoSearchInMyNetworkPlaces 2msoSearchInOutlook 1
MsoSegmentType
Constant ValuemsoSegmentCurve 1msoSegmentLine 0
MsoShadowType
Constant ValuemsoShadow1 1msoShadow10 10msoShadow11 11msoShadow12 12msoShadow13 13msoShadow14 14msoShadow15 15msoShadow16 16msoShadow17 17msoShadow18 18msoShadow19 19msoShadow2 2msoShadow20 20
msoShadow3 3msoShadow4 4msoShadow5 5msoShadow6 6msoShadow7 7msoShadow8 8msoShadow9 9msoShadowMixed -2
MsoShapeType
Constant ValuemsoAutoShape 1msoCallout 2msoCanvas 20msoChart 3msoComment 4msoDiagram 21msoEmbeddedOLEObject 7msoFormControl 8msoFreeform 5msoGroup 6msoInk 22msoInkComment 23msoLine 9msoLinkedOLEObject 10msoLinkedPicture 11msoMedia 16msoOLEControlObject 12msoPicture 13msoPlaceholder 14msoScriptAnchor 18msoShapeTypeMixed -2
msoTable 19msoTextBox 17msoTextEffect 15
MsoSharedWorkspaceTaskPriority
Constant ValuemsoSharedWorkspaceTaskPriorityHigh 1msoSharedWorkspaceTaskPriorityLow 3msoSharedWorkspaceTaskPriorityNormal 2
MsoSharedWorkspaceTaskStatus
Constant ValuemsoSharedWorkspaceTaskStatusCompleted 3msoSharedWorkspaceTaskStatusDeferred 4msoSharedWorkspaceTaskStatusInProgress 2msoSharedWorkspaceTaskStatusNotStarted 1msoSharedWorkspaceTaskStatusWaiting 5
MsoSortBy
Constant ValuemsoSortByFileName 1msoSortByFileType 3msoSortByLastModified 4msoSortByNone 5msoSortBySize 2
MsoSortOrder
Constant ValuemsoSortOrderAscending 1msoSortOrderDescending 2
MsoSyncAvailableType
Constant ValuemsoSyncAvailableAnywhere 2msoSyncAvailableNone 0msoSyncAvailableOffline 1
MsoSyncCompareType
Constant ValuemsoSyncCompareAndMerge 0msoSyncCompareSideBySide 1
MsoSyncConflictResolutionType
Constant ValuemsoSyncConflictClientWins 0msoSyncConflictMerge 2msoSyncConflictServerWins 1
MsoSyncErrorType
Constant ValuemsoSyncErrorCouldNotCompare 13msoSyncErrorCouldNotConnect 2msoSyncErrorCouldNotOpen 11msoSyncErrorCouldNotResolve 14msoSyncErrorCouldNotUpdate 12msoSyncErrorFileInUse 6msoSyncErrorFileNotFound 4msoSyncErrorFileTooLarge 5msoSyncErrorNone 0msoSyncErrorNoNetwork 15msoSyncErrorOutOfSpace 3
msoSyncErrorUnauthorizedUser 1msoSyncErrorUnknown 16msoSyncErrorUnknownDownload 10msoSyncErrorUnknownUpload 9msoSyncErrorVirusDownload 8msoSyncErrorVirusUpload 7
MsoSyncEventType
Constant ValuemsoSyncEventDownloadFailed 2msoSyncEventDownloadInitiated 0msoSyncEventDownloadNoChange 6msoSyncEventDownloadSucceeded 1msoSyncEventOffline 7msoSyncEventUploadFailed 5msoSyncEventUploadInitiated 3msoSyncEventUploadSucceeded 4
MsoSyncStatusType
Constant ValuemsoSyncStatusConflict 4msoSyncStatusError 6msoSyncStatusLatest 1msoSyncStatusLocalChanges 3msoSyncStatusNewerAvailable 2msoSyncStatusNoSharedWorkspace 0msoSyncStatusSuspended 5
MsoSyncVersionType
Constant ValuemsoSyncVersionLastViewed 0
msoSyncVersionServer 1
MsoTargetBrowser
Constant ValuemsoTargetBrowserIE4 2msoTargetBrowserIE5 3msoTargetBrowserIE6 4msoTargetBrowserV3 0msoTargetBrowserV4 1
MsoTextEffectAlignment
Constant ValuemsoTextEffectAlignmentCentered 2msoTextEffectAlignmentLeft 1msoTextEffectAlignmentLetterJustify 4msoTextEffectAlignmentMixed -2msoTextEffectAlignmentRight 3msoTextEffectAlignmentStretchJustify 6msoTextEffectAlignmentWordJustify 5
MsoTextOrientation
Constant ValuemsoTextOrientationDownward 3msoTextOrientationHorizontal 1msoTextOrientationHorizontalRotatedFarEast 6msoTextOrientationMixed -2msoTextOrientationUpward 2msoTextOrientationVertical 5msoTextOrientationVerticalFarEast 4
MsoTextureType
Constant ValuemsoTexturePreset 1msoTextureTypeMixed -2msoTextureUserDefined 2
MsoTriState
Constant ValuemsoCTrue 1msoFalse 0msoTriStateMixed -2msoTriStateToggle -3msoTrue -1
MsoVerticalAnchor
Constant ValuemsoAnchorBottom 4msoAnchorBottomBaseLine 5msoAnchorMiddle 3msoAnchorTop 1msoAnchorTopBaseline 2msoVerticalAnchorMixed -2
MsoWizardActType
Constant ValuemsoWizardActActive 1msoWizardActInactive 0msoWizardActResume 3msoWizardActSuspend 2
MsoWizardMsgType
Constant ValuemsoWizardMsgLocalStateOff 2msoWizardMsgLocalStateOn 1msoWizardMsgResuming 5msoWizardMsgShowHelp 3msoWizardMsgSuspending 4
MsoZOrderCmd
Constant ValuemsoBringForward 2msoBringInFrontOfText 4msoBringToFront 0msoSendBackward 3msoSendBehindText 5msoSendToBack 1
ReturninganObjectfromaCollectionTheItempropertyreturnsasingleobjectfromacollection.ThefollowingexamplesetsthecmdbarvariabletoaCommandBarobjectthatrepresentsthefirstcommandbarintheCommandBarscollection.
Setcmdbar=CommandBars.Item(1)
TheItempropertyisthedefaultpropertyformostcollections,soyoucanwritethesamestatementmoreconciselybyomittingtheItemkeyword.
Setcmdbar=CommandBars(1)
Formoreinformationaboutaspecificcollection,seetheHelptopicforthecollectionortheItempropertyforthecollection.