Mostrartodo
ObjetosdeMicrosoftOffice
AnswerWizard AnswerWizardFilesAssistantBalloon BalloonCheckboxes
BalloonCheckbox BalloonLabels BalloonLabel
COMAddInsCOMAddIn
CommandBarButtonCommandBarControl
CommandBarComboBoxCommandBarControl
CommandBarPopupCommandBarControl
DocumentPropertiesDocumentProperty
FileDialogFileDialogFilters FileDialogFilterFileDialogSelectedItems
FileSearchFileTypesFoundFilesPropertyTests PropertyTest
SearchFolders ScopeFolder ScopeFoldersSearchScopes SearchScopes ScopeFolder ScopeFolders
HTMLProjectHTMLProjectItems HTMLProjectItem
LanguageSettingsMsoEnvelopeCommandBars
NewFileOfficeDataSourceObjectODSOColumns ODSOColumnODSOFilters ODSOFilter
ScriptsScript
SignatureSetSignature
WebPageFontsWebPageFont
Leyenda
ObjetoycolecciónSóloobjeto
NovedadesparalosprogramadoresdeMicrosoftOffice
SehanrealizadomuchoscambiosenelmodelodeobjetoVisualBasicdeMicrosoftOfficeafindeaumentarlacompatibilidadconlascaracterísticasnuevasymejoradasdeloscomponentescompartidos.Sehanagregadounagrancantidaddeobjetos,propiedades,métodosyeventos.
VisiteelOfficeDeveloperCenterenMSDNOnlineparaobtenerlainformaciónmásrecientesobreeldesarrollodeMicrosoftOffice,queincluyeartículostécnicosnuevos,descargas,muestras,nuevosproductos,etc.
Elementosdeidiomanuevos
EltemasiguienteofreceunalistadeloselementosdeidiomaquesonnuevosenOffice:
Objetosnuevos
Propiedadesnuevas(porobjetos)
Propiedadesnuevas(porordenalfabético)
Métodosnuevos
Eventosnuevos
Objetosnuevos
VisiteelOfficeDeveloperCenterenMSDNOnlineparaobtenerlainformaciónmásrecientesobreeldesarrollodeMicrosoftOffice,queincluyeartículostécnicosnuevos,descargas,muestras,nuevosproductos,etc.
LosobjetosquesehanagregadoaVisualBasicenMicrosoftOfficeseincluyenenlasiguientetabla.
ObjetosFileDialogFileDialogFilterFileDialogFiltersFileDialogSelectedItemsFileTypesMsoEnvelopeNewFileODSOColumnODSOColumnsODSOFilterODSOFiltersOfficeDataSourceObjectScopeFolderScopeFoldersSearchFoldersSearchScopeSearchScopesSignatureSignatureSet
Eventosnuevos
LoseventosnuevosdeMicrosoftOfficeseincluyenenlasiguientetabla.
EventosEnvelopeHideEnvelopeShow
Métodosnuevos
LosmétodosquesehanañadidoalosobjetosexistentesdeMicrosoftOfficeseincluyenenlatablasiguiente,ordenadosporobjetos.
Objetos MétodosAssistant DoAlertFileSearch RefreshScopes
OfficeDataSourceObjectApplyFilter
SetSortOrder
ScopeFolder AddToSearchFoldersSignatureSet Commit
Propiedadesnuevas(porordenalfabético)
LaspropiedadesquesehanañadidoalosobjetosexistentesdeMicrosoftOfficeseincluyenenlatablasiguiente(porordenalfabético).
PropiedadesAllowMultiSelectAttachCertificateButtonNameColumnColumnsCommandBarsCompareToComparisonConjunctionConnectStringDataSourceDialogTypeDisableAskAQuestionDropdownDisableCustomizeExpireDateExtensionsFileTypesFilterIndexFiltersInitialFileNameInitialViewIntroduction
IsCertificateExpiredIsCertificateRevokedIssuerIsValidMaskPathPictureRowCountScopeFolderScopeFoldersSearchFoldersSearchScopesSelectedItemsSignDateSignerTable
Propiedadesnuevas(porobjeto)
LaspropiedadesquesehanañadidoalosobjetosexistentesdeMicrosoftOfficeseincluyenenlatablasiguiente(ordenadaspornombredeobjeto).
Objetos Propiedades
CommandBarButton MaskPicture
CommandBarsDisableAskAQuestionDropdown
DisableCustomize
FileDialog
AllowMultiSelect
ButtonName
DialogType
FilterIndex
Filters
InitialFileName
InitialView
SelectedItems
FileDialogFilter Extensions
FileSearch
FileTypes
SearchFolders
SearchScopes
MsoEnvelopeCommandBars
Introduction
ODSOFilter
Column
CompareTo
Comparison
Conjunction
OfficeDataSourceObject
Columns
ConnectString
DataSource
Filters
RowCount
Table
ScopeFolderPath
ScopeFolders
SearchScope ScopeFolder
Signature
AttachCertificate
ExpireDate
IsCertificateExpired
IsCertificateRevoked
Issuer
IsValid
SignDate
Signer
ObjetoAnswerWizardAnswerWizard(AnswerWizardFiles)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentaelAsistenteparaAyudadeunaaplicacióndeMicrosoftOffice.SólohayunAsistenteparaAyudaporaplicaciónytodosloscambiosproducidosenlacolecciónAnswerWizardoAnswerWizardFilesafectarándemanerainmediataalaaplicaciónactivadeOffice.
UtilizarelobjetoAnswerWizard
UtiliceelmétodoClearFileListparaquitartodaslasentradasdelalistadearchivosdisponiblesenelAsistenteparaAyudaactual.Siutilizaestemétodo,seasegurarádequeyanosepodráobteneraccesoalosarchivospredeterminadosdisponiblesenlaaplicaciónhostatravésdelAsistenteparaAyuda,talcomoocurrecuandoreemplazaarchivosdelAsistenteparaAyudaconarchivos.AWpredeterminados.ElejemplosiguienteborralalistadearchivosdelAsistenteparaAyudapredeterminadoyañadedosarchivosalAsistenteparaAyudapersonalizado.
customAnswerWizard.ClearFileList
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
customAnswerWizard.Files.Add("c:\awfiles\custom_2.aw")
UtiliceelmétodoResetFileListpararestablecerlalistadearchivosdelAsistenteparaAyudaalalistapredeterminadadearchivosdelaaplicaciónhostdeOffice.TambiénpuedeestablecerunalistadearchivospredeterminadaenelregistrodeWindowsañadiendolosnombresdelosarchivospersonalizadosalaclavederegistroadecuada;losarchivosespecificadosendichaclavederegistroserestableceráncuandoseactiveResetFileList.EsteejemplorestablecelalistadearchivosdelAsistenteparaAyudaactual.
customAnswerWizard.ResetFileList
UtilicelapropiedadFilesparaobtenerlacoleccióndereferenciasaarchivosdel
AsistenteparaAyuda.LapropiedadFilesdevuelveunacoleccióndecadenasqueserefierenaarchivos.AW.ElejemplosiguientedevuelvelacolecciónAnswerWizardFilesymuestraelnúmerodearchivosenuncuadrodemensaje.
DimcustomAnswerWizardFilesAsAnswerWizardFiles
SetcustomAnswerWizardFiles=Application.AnswerWizard.Files
MsgBoxcustomAnswerWizardFiles.Count
ObjetodecolecciónAnswerWizardFilesAnswerWizard(AnswerWizardFiles)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
ColeccióndereferenciasaarchivosdelAsistenteparaAyuda.LacolecciónAnswerWizardFilescontienetodoslosarchivosdelAsistenteparaAyuda(conlaextensióndearchivo.AW)disponiblesenlaaplicaciónactivadeMicrosoftOffice.
UtilizacióndelacolecciónAnswerWizardFiles
UtilicelapropiedadFilesparaobtenerlacoleccióndereferenciasaarchivosdelAsistenteparaAyuda.LapropiedadFilesdevuelveunacoleccióndecadenasqueserefierenaarchivos.AW.ElejemplosiguientedevuelvelacolecciónAnswerWizardFilesymuestraelnúmerodearchivosenuncuadrodemensaje.
DimcustomAnswerWizardFilesAsAnswerWizardFiles
SetcustomAnswerWizardFiles=Application.AnswerWizard.Files
MsgBoxcustomAnswerWizardFiles.Count
UtiliceelmétodoAddparaquehayaarchivosadicionalesdisponiblesenelAsistenteparaAyudaactual.ElejemplosiguienteañadeelarchivoCustom_1.awalalistadearchivosdeAsistenteparaAyudadelaaplicaciónactivadeOffice.
DimcustomAnswerWizardAsAnswerWizard
SetcustomAnswerWizard=Application.AnswerWizard
customAnswerWizard.Files.Add("c:\awfiles\custom_1.aw")
UtilicelapropiedadItemparaobtenerelnombredeunareferenciaaarchivoexistenteenelAsistenteparaAyuda.ElejemplosiguientemuestrauncuadrodemensajequecontieneelnombredelarchivoquellevaelnombredeItem(1).
MsgBoxcustomAnswerWizard.Files.Item(1)
ObjetoAssistantAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentaelAyudantedeOfficedeMicrosoft.
UsodelobjetoAssistant
UtilicelapropiedadAssistantparadevolverelobjetoAssistant.NohayunacolecciónparaelobjetoAssistant;sólopuedehaberunobjetoAssistantactivoalavez.UtilicelapropiedadVisibleparamostrarelAyudanteyutilicelapropiedadOnparahabilitaralAyudante.
Comentarios
ElAyudantepredeterminadoesClipo.ParaseleccionarunAyudantediferenteconellenguajedemacros,utilicelapropiedadFileName.
ElsiguienteejemplomuestraunAyudanteseleccionadoanteriormenteyloanimaconelsonidoasociado.
WithAssistant
.Visible=True
.Animation=msoAnimationGreeting
EndWith
ObjetoBalloonAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentaelglobodondeelAyudantedeOfficemuestralosencabezadosyeltexto.Unglobopuedecontenercontrolescomocasillasdeverificaciónyrótulos.
UsodelobjetoBalloon
UtilicelapropiedadNewBalloonparadevolverunobjetoBalloon.NohayunacolecciónparaelobjetoBalloon;sólopuedehaberunglobovisiblealavez.Sinembargo,esposibledefinirvariosglobosyllamaracualquieradeelloscuandoseanecesario.Paraobtenermásinformación,consulte"Definiciónyreutilizacióndeglobos"másadelanteenestetema.
UtilicelapropiedadShowparamostrarelgloboespecificado.UtilicelapropiedadCallbackparaejecutarlosprocedimientosbasadosenlasseleccionesdeglobossinmodo(globosquepermanecenvisiblesmientrasunusuariotrabajaenlaaplicación).UtiliceelmétodoCloseparacerrarlosglobossinmodo.
Elsiguienteejemplocreaungloboquecontienesugerenciasparaguardarlosdatosintroducidos.
WithAssistant.NewBalloon
.BalloonType=msoBalloonTypeBullets
.Icon=msoIconTip
.Button=msoButtonSetOk
.Heading="TipsforSavingInformation."
.Labels(1).Text="Saveyourworkoften."
.Labels(2).Text="Installasurgeprotector."
.Labels(3).Text="Exityourapplicationproperly."
.Show
EndWith
Definiciónyreutilizacióndeglobos
Puedevolverautilizarlosobjetosdeglobo,asignándolosavariablesdeobjetoyllamándolos,cuandoseanecesario,ensuprocedimiento.Esteejemplodefine"balloon1"y"balloon2"comoglobosindependientes,porloquelosmuestraendiferentespuntosdelprocedimiento.
Setballoon1=Assistant.NewBalloon
balloon1.Heading="Firstballoon"
Setballoon2=Assistant.NewBalloon
balloon2.Heading="Secondballoon"
balloon1.Show
balloon2.Show
balloon1.Heading="Firstballoon,newheading"
balloon1.Show
Tambiénpuedecombinarvariablesdeobjetogloboenunamatrizeindizarlosenella.
ObjetoBalloonCheckBoxAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentaunacasilladeverificaciónenelgloboAyudantedeOffice.ElobjetoBalloonCheckBoxesunmiembrodelacolecciónBalloonCheckBoxes.
UsodelobjetoBalloonCheckbox
UtiliceCheckBoxes(índice),dondeíndiceesunnúmerode1a5,paradevolverunobjetoBalloonCheckBoxindividual.Puedehaberhastacincocasillasdeverificaciónenunglobo;cadacasilladeverificaciónaparececuandoseasignaunvalorasupropiedadText.
Elsiguienteejemplocreaungloboconencabezado,textoytresopcionesderegión.ElusuarioactivaunaomáscasillasdeverificaciónyhaceclicenAceptar.Elejemplollamaalprocedimientooprocedimientosespecificados.
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
Comentarios
Lascasillasdeverificacióndeunglobomuestranlasopcionesdelusuariohastaqueéstecierreelglobo.PuedeutilizarlosrótulosdelgloboparadevolverelnúmerocorrespondientealaeleccióndelusuarioenelmétodoSelect,tanprontocomoelusuariohagaclicenelbotónqueaparecejuntoalrótulo.ParatrasladarvaloresalmétodoSelectapartirdelasopcionesdelusuario,debetenereltipodegloboestablecidoenmsoBalloonTypeButtons.
ObjetodecolecciónBalloonCheckBoxesAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
UnacoleccióndeobjetosBalloonCheckboxquerepresentantodaslascasillasdeverificacióndelgloboAyudantedeOffice.
UsodelacolecciónBalloonCheckboxes
UtilicelapropiedadCheckboxesparadevolverlacolecciónBalloonCheckboxes.
UtiliceCheckBoxes(índice),dondeíndiceesunnúmerode1a5,paradevolverunobjetoBalloonCheckBoxindividual.Puedeespecificarhastacincocasillasdeverificación(ycincoetiquetas),porglobo;cadacasilladeverificaciónaparececuandoseasignaunvalorasupropiedadText.Sihaespecificadomásdecincocasillasdeverificación,apareceráunerrordetiempodeejecución.
Elsiguienteejemplocreaungloboconencabezado,textoytresopcionesderegión.CuandoelusuarioactivaunaomáscasillasdeverificaciónyhaceclicenAceptar,sellamaalprocedimientooprocedimientosespecificados.
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
NopuedeagregaroquitarcasillasdeverificacióndelacolecciónBalloonCheckboxes.
Comentarios
Lascasillasdeverificacióndeunglobomuestranlasopcionesdelusuariohastaqueéstecierreelglobo.PuedeutilizarrótulosdeglobojuntoconelmétodoSelectparadevolverunnúmeroquecorrespondaalnúmerodecasillasdeverificaciónactivadasporelusuariotanprontocomoestehagaclicenelbotónqueseencuentrajuntoalrótulo.ParatrasladarvaloresalmétodoSelectapartirdelasopcionesdelusuario,debetenereltipodegloboestablecidoenmsoBalloonTypeButtons.
ObjetoBalloonLabelAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentaunrótuloenelgloboAyudantedeOffice.ElobjetoBalloonLabelesunmiembrodelacolecciónBalloonLabels.
UsodelobjetoBalloonLabel
UtiliceLabels(índice),dondeíndiceesunnúmerode1a5,paradevolverunobjetoBalloonLabel.Puedehaberhastacincorótulosenunglobo;cadarótuloaparececuandoseasignaunvalorasupropiedadText.
Elsiguienteejemplocreaungloboquepidealusuarioquehagaclicenelrótuloquecorrespondaasuedad.
WithAssistant.NewBalloon
.Heading="CheckYourAgeGroup."
.Labels(1).Text="Under30."
.Labels(2).Text="30to50."
.Labels(3).Text="Over50."
.Text="Whichofthefollowing"_
&.Labels.Count&"choicesapplytoyou?"
.Show
EndWith
Comentarios
Lascasillasdeverificacióndelglobomuestranlaeleccióndelusuariohastaqueésterechazaelglobo.PuedeutilizarlosrótulosdelgloboparadevolverelnúmerocorrespondientealaeleccióndelusuarioenelmétodoSelect,tanprontocomoelusuariohagaclicenelbotónqueaparecejuntoalrótulo.ParapasarvaloresalmétodoSelectapartirdelaeleccióndelusuario,debetenereltipodegloboestablecidoenmsoBalloonTypeButtons.
ObjetodecolecciónBalloonLabelsAssistant Balloon
BalloonCheckBoxes(BalloonCheckBox)BalloonLabels(BalloonLabel)
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
UnacoleccióndeobjetosBalloonLabelquerepresentantodoslosrótulosdelgloboAyudantedeOffice.
UsodelacolecciónBalloonLabels
UtilicelapropiedadLabelsparadevolverlacolecciónBalloonLabels.
UtiliceLabels(índice),dondeíndiceesunnúmerode1a5,paradevolverunobjetoBalloonLabel.Puedeespecificarhastacincorótulos,ycincocasillasdeverificación,porglobo;cadarótuloaparececuandoseasignaunvalorasupropiedadText.Sihaespecificadomásdecincorótulos,apareceráunerrordetiempodeejecución.
Elsiguienteejemplocreaungloboquecontienetresopciones.LavariablereturnValueseestablececonelvalorquedevuelveelmétodoShow,queserá1,2ó3,dependiendodelrótuloqueelusuarioseleccione.ElejemplodevuelveelvalordelavariablereturnValue,valorquepuedetrasladaraotroprocedimiento,outilizarloenunasentenciaSelectCase.
Setb=Assistant.NewBalloon
Withb
.Heading="Thisismyheading"
.Text="Selectoneofthesethings:"
.Labels(1).Text="ChoiceOne"
.Labels(2).Text="ChoiceTwo"
.Labels(3).Text="ChoiceThree"
returnValue=.Show
EndWith
Comentarios
Lascasillasdeverificacióndeunglobomuestranlasopcionesdelusuariohastaqueéstecierreelglobo.PuedeutilizarlosrótulosdelgloboparadevolverelnúmerocorrespondientealaeleccióndelusuarioenelmétodoSelect,tanprontocomoelusuariohagaclicenelbotónqueaparecejuntoalrótulo.ParatrasladarvaloresalmétodoSelectapartirdelasopcionesdelusuario,debetenereltipodegloboestablecidoenmsoBalloonTypeButtons.
ObjetoCOMAddInCOMAddIns(COMAddIn)
RepresentauncomplementoCOMenlaaplicaciónhostdeMicrosoftOffice.ElobjetoCOMAddInformapartedelacolecciónCOMAddIns.
UtilizarelobjetoCOMAddIn
UtiliceCOMAddIns.Item(index),dondeindexesunvalorordinalquedevuelveelcomplementoCOMqueseencuentraendichaposicióndentrodelacolecciónCOMAddIns,obienunvalorStringquerepresentaelProgIDdelcomplementoCOMespecificado.ElejemplosiguientemuestraenuncuadrodemensajeeltextodescriptivodeuncomplementoCOM.
MsgBoxApplication.COMAddIns.Item("msodraa9.ShapeSelect").Description
UtilicelapropiedadProgIDdelobjetoCOMAddinparadevolverelidentificadorprogramáticodeuncomplementoCOM;utilicelapropiedadGuidparadevolverelidentificadorexclusivoglobal(GUID)delcomplemento.ElejemplosiguientemuestraenuncuadrodemensajeelProgIDyelGUIDdelcomplementoCOMuno.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
UtilicelapropiedadConnectparaestablecerodevolverelestadodelaconexiónconuncomplementoCOMespecífico.ElejemplosiguientemuestrauncuadrodemensajequeindicasielcomplementoCOMunoestáregistradoyconectadoactualmente.
IfApplication.COMAddIns(1).ConnectThen
MsgBox"Theadd-inisconnected."
Else
MsgBox"Theadd-inisnotconnected."
EndIf
ObjetodecolecciónCOMAddInsCOMAddIns(COMAddIn)
ColeccióndeobjetosCOMAddInqueproporcionaninformaciónsobreuncomplementoCOMincluidoenelregistrodeWindows.
UtilizarlacolecciónCOMAddIns
UtilicelapropiedadCOMAddInsdelobjetoApplicationparadevolverlacolecciónCOMAddInsdeunaaplicaciónhostdeMicrosoftOffice.EstacoleccióncontienetodosloscomplementosCOMdisponiblesenunaaplicaciónhostdeOfficedeterminada;lapropiedadCountdelacolecciónCOMAddinsdevuelveelnúmerodeloscomplementosCOMdisponibles,talcomoseindicaenelejemplosiguiente.
MsgBoxApplication.COMAddIns.Count
UtiliceelmétodoUpdatedelacolecciónCOMAddinsparaactualizarlalistadecomplementosCOMdelregistrodeWindows,talcomoseindicaenelejemplosiguiente.
Application.COMAddIns.Update
UtiliceCOMAddIns.Item(index),dondeindexesunvalorordinalquedevuelveelcomplementoCOMqueseencuentraendichaposiciónenlacolecciónCOMAddIns,obienunvalorStringquerepresentaelProgIDdelcomplementoCOMespecificado.ElejemplosiguientemuestraenuncuadrodemensajeeltextodescriptivoyelProgIDdeuncomplementoCOM("msodraa9.ShapeSelect").
MsgBoxApplication.COMAddIns.Item("msodraa9.ShapeSelect").Description
Mostrartodo
ObjetoCommandBarCommandBars(CommandBar) CommandBarControls(CommandBarControl)
CommandBarButtonCommandBarComboBoxCommandBarPopup
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Representaunabarradecomandosdelaaplicacióncontenedora.ElobjetoCommandBaresunmiembrodelacolecciónCommandBars.
UsodelobjetoCommandBar
UtiliceCommandBars(index),dondeindexeselnombreonúmerodeíndicedeunabarradecomandos,paradevolverunsoloobjetoCommandBar.Elsiguienteejemplorecorrelacoleccióndebarrasdecomandosparabuscarlabarradecomandosdenominada"Forms".Siseencuentraestabarradecomandos,elejemplolamuestrayprotegeelestadodeacoplamiento.Enesteejemplo,lavariablecbrepresentaunobjetoCommandBar.
foundFlag=False
ForEachcbInCommandBars
Ifcb.Name="Forms"Then
cb.Protection=msoBarNoChangeDock
cb.Visible=True
foundFlag=True
EndIf
Nextcb
IfNotfoundFlagThen
MsgBox"ThecollectiondoesnotcontainaFormscommandbar."
EndIf
Puedeutilizarunnombreonúmerodeíndiceparaespecificarunabarrademenúsodeherramientasdelalistadebarrasdemenúsodeherramientasdisponiblesenlaaplicacióncontenedora.Sinembargo,debeutilizarunnombreparaespecificarunmenú,menúcontextualosubmenú,representadostodospor
objetosCommandBar.EsteejemploagregaunelementonuevoalmenúHerramientas.Alhacerclicenél,elnuevoelementodemenúejecutaelprocedimiento"qtrReport".
SetnewItem=CommandBars("Tools").Controls.Add(Type:=msoControlButton)
WithnewItem
.BeginGroup=True
.Caption="MakeReport"
.FaceID=0
.OnAction="qtrReport"
EndWith
Sidosomásmenúsosubmenúspersonalizadostienenelmismonombre,CommandBars(index)devuelveelprimero.Paraasegurarquedevuelveelmenúosubmenúcorrecto,busqueelcontrolemergentequemuestradichomenú.AcontinuaciónapliquelapropiedadCommandBaralcontrolemergenteparadevolverlabarradecomandosquerepresentadichomenú.
Suponiendoqueeltercercontroldelabarradeherramientas"CustomTools"seauncontrolemergente,esteejemploagregaelcomandoGuardaralbotóndedichomenú.
SetviewMenu=CommandBars("CustomTools").Controls(3)
viewMenu.Controls.AddID:=3'IDofSavecommandis3
Mostrartodo
ObjetoCommandBarButtonCommandBars(CommandBar) CommandBarControls(CommandBarControl) CommandBarButton CommandBarComboBox CommandBarPopup
Representauncontroldebotóndeunabarradecomandos.
UsodelobjetoCommandBarButton
UtiliceControls(index),dondeindexeselnúmerodeíndicedeuncontrol,paradevolverunobjetoCommandBarButton.LapropiedadTypedelcontroldebesermsoControlButton.
Suponiendoqueelsegundocontroldelabarradeherramientas"Custom"seaunbotón,esteejemplocambiaelestilodedichobotón.
Setc=CommandBars("Custom").Controls(2)
Withc
If.Type=msoControlButtonThen
If.Style=msoButtonIconThen
.Style=msoButtonIconAndCaption
Else
.Style=msoButtonIcon
EndIf
EndIf
EndWith
TambiénpuedeutilizarelmétodoFindControlparadevolverunobjetoCommandBarButton.
Mostrartodo
ObjetoCommandBarComboBoxCommandBars(CommandBar) CommandBarControls(CommandBarControl) CommandBarButton CommandBarComboBox CommandBarPopup
Representauncontroldecuadrocombinadodeunabarradecomandos.
UsodelobjetoCommandBarComboBox
UtiliceControls(index),dondeindexeselnúmerodeíndicedeuncontrol,paradevolverunobjetoCommandBarComboBox.LapropiedadTypedelcontroldebesermsoControlEdit,msoControlDropdown,msoControlComboBox,msoControlButtonDropdown,msoControlSplitDropdown,msoControlOCXDropdown,msoControlGraphicComboomsoControlGraphicDropdown.
Elsiguienteejemploagregadoselementosalsegundocontroldelabarradecomandosdenominada"Custom"y,acontinuación,ajustaeltamañodelcontrol.
Setcombo=CommandBars("Custom").Controls(2)
Withcombo
.AddItem"FirstItem",1
.AddItem"SecondItem",2
.DropDownLines=3
.DropDownWidth=75
.ListIndex=0
EndWith
TambiénpuedeutilizarelmétodoFindControlparadevolverunobjetoCommandBarComboBox.ElsiguienteejemplobuscatodaslasbarrasdecomandosdeunobjetoCommandBarComboBoxvisiblecuyorótulosea"sheetassignments".
SetmyControl=CommandBars.FindControl_
(Type:=msoControlComboBox,Tag:="sheetassignments",Visible:=True)
Mostrartodo
ObjetoCommandBarControlCommandBars(CommandBar) CommandBarControls(CommandBarControl) CommandBarButton CommandBarComboBox CommandBarPopup
Representauncontroldebarradecomandos.ElobjetoCommandBarControlesmiembrodelacolecciónCommandBarControls.LaspropiedadesymétodosdelobjetoCommandBarControlestáncompartidasporlosobjetosCommandBarButton,CommandBarComboBoxyCommandBarPopup.
NotaAlescribirelcódigodeVisualBasicparatrabajarconcontrolesdebarradecomandospersonalizadas,seutilizanlosobjetosCommandBarButton,CommandBarComboBoxyCommandBarPopup.Alescribirelcódigoparatrabajarconcontrolesintegradosdelaaplicacióncontenedoraquenopuedanrepresentarseconningunodeesostresobjetos,seutilizaelobjetoCommandBarControl.
UsodelobjetoCommandBarControl
UtiliceControls(index),dondeindexeselnúmerodeíndicedeuncontrol,paradevolverunobjetoCommandBarControl.(LapropiedadTypedelcontroldebesermsoControlLabel,msoControlExpandingGrid,msoControlSplitExpandingGrid,msoControlGridomsoControlGauge.)
NotaLasvariablesdeclaradascomoCommandBarControlpuedentenerelvalorCommandBarButton,CommandBarComboBoxyCommandBarPopup.
TambiénpuedeutilizarelmétodoFindControlparadevolverunobjetoCommandBarControl.ElsiguienteejemplobuscauncontroldeltipomsoControlGauge;siencuentrauno,muestraelnúmerodeíndicedelcontrolyelnombredelabarradecomandosquelocontiene.Enesteejemplo,lavariablelblrepresentaunobjetoCommandBarControl.
Setlbl=CommandBars.FindControl(Type:=msoControlGauge)
IflblIsNothingThen
MsgBox"AcontroloftypemsoControlGaugewasnotfound."
Else
MsgBox"Control"&lbl.Index&"oncommandbar"_
&lbl.Parent.Name&"istypemsoControlGauge"
EndIf
Mostrartodo
ObjetodecolecciónCommandBarControlsCommandBars(CommandBar) CommandBarControls(CommandBarControl)
CommandBarButtonCommandBarComboBoxCommandBarPopup
ColeccióndeobjetosCommandBarControlquerepresentanloscontrolesdebarrasdecomandosdeunabarradecomandos.
UsodelacolecciónCommandBarControls
UtilicelapropiedadControlsparadevolverlacolecciónCommandBarControls.Elsiguienteejemplocambiaeltítulodecadacontroldelabarradecomandosdenominada"Standard"alvaloractualdelapropiedadIdparaesecontrol.
ForEachctlInCommandBars("Standard").Controls
ctl.Caption=CStr(ctl.Id)
Nextctl
UtiliceelmétodoAddparaagregarunnuevocontroldebarradecomandosalacolecciónCommandBarControls.Esteejemploagregaunnuevobotónvacíaalabarradecomandosdenominada"Custom".
SetmyBlankBtn=CommandBars("Custom").Controls.Add
UtiliceControls(index),dondeindexeseltítuloonúmerodeíndicedeuncontrol,paradevolverunobjetoCommandBarControl,CommandBarButton,CommandBarComboBoxoCommandBarPopup.Elsiguienteejemplocopiaelprimercontroldelabarradecomandos"Standard"alabarradecomandos"Custom".
SetmyCustomBar=CommandBars("Custom")
SetmyControl=CommandBars("Standard").Controls(1)
myControl.CopyBar:=myCustomBar,Before:=1
Mostrartodo
ObjetoCommandBarPopupCommandBars(CommandBar) CommandBarControls(CommandBarControl) CommandBarButton CommandBarComboBox CommandBarPopup
Representauncontrolemergentedeunabarradecomandos.
UsodeunobjetoCommandBarPopup
UtiliceControls(index),dondeindexeselnúmerodeíndicedeuncontrol,paradevolverunobjetoCommandBarPopup.LapropiedadTypedelcontroldebesermsoControlPopup,msoControlGraphicPopup,msoControlButtonPopup,msoControlSplitButtonPopupomsoControlSplitButtonMRUPopup.
TambiénpuedeutilizarelmétodoFindControlparadevolverunobjetoCommandBarPopup.ElsiguienteejemplobuscaentodaslasbarrasdecomandosunobjetoCommandBarPopupvisiblecuyorótulosea"Graphics".
SetmyControl=Application.CommandBars.FindControl_
(Type:=msoControlPopup,Tag:="Graphics")
Comentarios
CadacontrolemergentecontieneunobjetoCommandBar.Paradevolverlabarradecomandosdeuncontrolemergente,apliquelapropiedadCommandBaralobjetoCommandBarPopup.
Mostrartodo
ObjetodecolecciónCommandBarsCommandBars(CommandBar) CommandBarControls(CommandBarControl) CommandBarButton CommandBarComboBox CommandBarPopup
ColeccióndeobjetosCommandBarquerepresentalasbarrasdecomandosdelaaplicacióncontenedora.
UsodelacolecciónCommandBars
UtilicelapropiedadCommandBarsparadevolverlacolecciónCommandBars.Elsiguienteejemplomuestra,enlaventanaImmediate,elnombreyelnombrelocaldecadabarrademenúsydeherramientas,ymuestraunvalorqueindicasilabarrademenúsodeherramientasestávisible.
ForEachcbarinCommandBars
Debug.Printcbar.Name,cbar.NameLocal,cbar.Visible
Next
UtiliceelmétodoAddparaagregarunanuevabarradecomandosalacolección.Elsiguienteejemplocreaunabarradeherramientaspersonalizadadenominada"Custom1"ylamuestracomobarradeherramientasflotante.
Setcbar1=CommandBars.Add(Name:="Custom1",Position:=msoBarFloating)
cbar1.Visible=True
UtiliceCommandBars(index),dondeindexeselnombreonúmerodeíndicedeunabarradecomandos,paradevolverunsoloobjetoCommandBar.Elsiguienteejemploacoplalabarradeherramientasdenominada"Custom1"enlaparteinferiordelaventanadeaplicación.
CommandBars("Custom1").Position=msoBarBottom
NotaPuedeutilizarelnombreoelnúmerodeíndiceparaespecificarunabarrademenúsodeherramientasdelalistadebarrasdemenúsodeherramientasdisponiblesenlaaplicacióncontenedora.Sinembargo,debeutilizarelnombreparaespecificarunmenú,menúcontextualosubmenú,representadostodosporobjetosCommandBar.
Sidosomásmenúsosubmenúspersonalizadostienenelmismonombre,CommandBars(index)devuelveelprimero.Paraasegurarquedevuelveelmenúosubmenúcorrecto,busqueelcontrolemergentequemuestradichomenú.AcontinuaciónapliquelapropiedadCommandBaralcontrolemergenteparadevolverlabarradecomandosquerepresentadichomenú.
ObjetodecolecciónDocumentProperties
ColeccióndeobjetosDocumentProperty.CadaobjetoDocumentPropertyrepresentaunapropiedadintegradaopersonalizadadeundocumentocontenedor.
UsodelacolecciónDocumentProperties
UtiliceelmétodoAddparacrearunanuevapropiedadpersonalizadayagregarlaalacolecciónDocumentProperties.NoesposibleutilizarelmétodoAddparacrearunapropiedaddedocumentointegrada.
UtiliceBuiltinDocumentProperties(index),dondeindexeselnúmerodeíndicedelapropiedaddedocumentointegrada,paradevolverunúnicoobjetoDocumentPropertyquerepresentaunapropiedaddedocumentointegradaespecífica.UtiliceCustomDocumentProperties(index),dondeindexeselnúmerodelapropiedaddedocumentopersonalizada,paradevolverunobjetoDocumentPropertyquerepresentaunapropiedaddedocumentopersonalizadaespecífica.
ObjetoDocumentProperty
Representaunapropiedaddedocumentointegradaopersonalizadadeundocumentocontenedor.ElobjetoDocumentPropertyesunmiembrodelacolecciónDocumentProperties.
UsodelobjetoDocumentProperty
UtiliceBuiltinDocumentProperties(index),dondeindexeselnombreonúmerodeíndicelapropiedaddedocumentointegrada,paradevolverunúnicoobjetoDocumentPropertyquerepresentaunapropiedaddedocumentointegradaespecífica.UtiliceCustomDocumentProperties(index),dondeindexeselnombreonúmerodeíndicedelapropiedaddedocumentopersonalizada,paradevolverunobjetoDocumentPropertyquerepresentaunapropiedaddedocumentopersonalizadaespecífica.
Lasiguientelistacontienelosnombresdetodaslaspropiedadesdedocumentointegradasdisponibles.
Título
Subject
Autor
Palabrasclave
Observaciones
Plantilla
Últimoautor
Númeroderevisión
Nombredelaaplicación
Últimafechadeimpresión
Fechadecreación
Horaenqueseguardóporúltimavez
Tiempototaldeedición
Númerodepalabras
Númerodecaracteres
Seguridad
Categoría
Formato
Administrador
Organización
Númerodebytes
Númerodelíneas
Númerodepárrafos
Númerodediapositivas
Númerodenotas
Númerodediapositivasocultas
Númerodepáginas Númerodesecuenciasmultimedia
Lasaplicacionescontenedorasnodefinennecesariamenteunvalorparacadapropiedaddedocumentointegrada.Siunaaplicacióndeterminadanodefineunvalorparaunadelaspropiedadesdedocumentointegradas,aldevolverlapropiedadValuedeesedocumentoseproduceunerror.
ObjetoFileDialogFileDialog Variosobjetos
ProporcionafuncionesdecuadrosdediálogodearchivossimilaresalasdeloscuadrosdediálogoAbriryGuardarestándaresdelasaplicacionesdeMicrosoftOffice.Conestoscuadrosdediálogo,losusuariosdelassolucionespuedenespecificarfácilmentelosarchivosylascarpetasquedeberáutilizarlasolución.
UtilizarelobjetoFileDialog
UtilicelapropiedadFileDialogparadevolverunobjetoFileDialog.LapropiedadFileDialogseencuentraencadaobjetoApplicationdelasaplicacionesdeOffice.Lapropiedadtomaunsoloargumento,DialogType,quedeterminaeltipodeobjetoFileDialogquedevuelvelapropiedad.ExistencuatrotiposdeobjetoFileDialog:
CuadrodediálogoAbrir:permitealusuarioseleccionarunoovariosarchivosquepuedeabriracontinuaciónenlaaplicaciónhostmedianteelmétodoExecute.CuadrodediálogoGuardarcomo:permitealusuarioseleccionarunsoloarchivo,concuyonombresepuede,acontinuación,guardarelarchivoactualmedianteelmétodoExecute.CuadrodediálogoSelectordearchivos:permitealusuarioseleccionarunoovariosarchivos.LasrutasdeaccesoaarchivosqueelusuarioseleccionasecapturanenlacolecciónFileDialogSelectedItems.CuadrodediálogoSelectordecarpetas:permitealusuarioseleccionarunarutadeacceso.LarutadeaccesoqueelusuarioseleccionasecapturaenlacolecciónFileDialogSelectedItems.
CadaaplicaciónhostsólopuederealizarunasolarepeticióndelobjetoFileDialog.Porlotanto,muchasdelaspropiedadesdelobjetoFileDialogseconservaninclusoalcrearvariosobjetosFileDialog.Porconsiguiente,asegúresedehaberestablecidocorrectamentetodaslaspropiedadesantesdemostrarelcuadrodediálogo.
ParamostraruncuadrodediálogodearchivosmedianteelobjetoFileDialog,deberáutilizarelmétodoShow.Unavezquesemuestraelcuadrodediálogo,noseejecutaráningúncódigohastaqueelusuariolocierre.ElejemplosiguientecreaymuestrauncuadrodediálogoSelectordearchivosy,acontinuación,muestracadaarchivoseleccionadoenuncuadrodemensaje.
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
ObjetoFileDialogFilterFileDialogFilters FileDialogFilter
RepresentaunfiltrodearchivosenuncuadrodediálogodearchivosquesemuestramedianteelobjetoFileDialog.Cadafiltrodearchivosdeterminaquéarchivossemuestranenelcuadrodediálogodearchivos.
UtilizarelobjetoFileDialogFilter
UtiliceelmétodoItemconlacolecciónFileDialogFiltersparadevolverunobjetoFileDialogFilter.UtiliceelmétodoAddparaagregarunobjetoFileDialogFilteralacolecciónFileDialogFilters.PuededevolverlasextensionesqueutilizaunobjetoFileDialogFilterparafiltrararchivosconlapropiedadExtensionsydevolverladescripcióndelfiltroconlapropiedadDescription;sinembargo,estaspropiedadessondesólolectura.SideseaestablecerlaextensiónodescripcióndeberáutilizarelmétodoAdd.
ElejemplosiguienterepitelosfiltrospredeterminadosdelcuadrodediálogoGuardarcomoymuestraladescripcióndecadafiltroqueincluyeunarchivodeMicrosoftExcel.
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
ColecciónFileDialogFiltersFileDialog FileDialogFilters FileDialogFilter
ColeccióndeobjetosFileDialogFilterquerepresentalostiposdearchivosquepuedenseleccionarseenelcuadrodediálogodearchivosquesemuestrautilizandoelobjetoFileDialog.
UtilizarlacolecciónFileDialogFilters
UtilicelapropiedadFiltersdelobjetoFileDialogparadevolverunacolecciónFileDialogFilters.ElcódigosiguientedevuelvelacolecciónFileDialogFiltersparaelcuadrodediálogoAbrirarchivo.
Application.FileDialog(msoFileDialogOpen).Filters
UtiliceelmétodoAddparaagregarobjetosFileDialogFilteralacolecciónFileDialogFilters.ElejemplosiguienteutilizaelmétodoClearparaborrarlacoleccióny,acontinuación,agregarfiltrosalamisma.ElmétodoClearvacíacompletamentelacolección;sinembargo,sinoagregafiltrosdespuésdeborrarla,elfiltro"Allfiles(*.*)"seagregaráautomáticamente.
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
AlcambiarlacolecciónFileDialogFiltersrecuerdequecadaaplicaciónsólopuederepetirunsoloobjetoFileDialog.EstosignificaquelacolecciónFileDialogFiltersrestablecerálosfiltrospredeterminadosalactivarelmétodoFileDialogconuntipodecuadrodediálogonuevo.
ElejemplosiguienterepitelosfiltrospredeterminadosdelcuadrodediálogoGuardarcomoymuestraladescripcióndecadafiltroqueincluyeunarchivodeMicrosoftExcel.
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
NotaSeproduciráunerroreneltiempodeejecuciónsiutilizalapropiedadFiltersjuntoconlosmétodosClear,AddoDeletesiseaplicaaunobjetoSaveAsFileDialog.Porejemplo,Application.FileDialog(msoFileDialogSaveAs).Filters.Clearproduciráunerrordetiempodeejecución.
ColecciónFileDialogSelectedItemsFileDialog FileDialogSelectedItems
UnacoleccióndevaloresStringquecorrespondealasrutasdeaccesoalosarchivosolascarpetasqueelusuariohaseleccionadoenelcuadrodediálogodearchivosquesemuestramedianteelobjetoFileDialog.
UtilizarlacolecciónFileDialogSelectedItems
UtilicelapropiedadSelectedItemsconelobjetoFileDialogparadevolverunacolecciónFileDialogSelectedItems.Elejemplosiguientemuestrauncuadrodediálogoenelquesepuedenseleccionararchivos,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
ObjetoFileSearchFileSearch Objetosmúltiples
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RepresentalafuncióndelcuadrodediálogoAbrir(menúArchivo).
UsodelobjetoFileSearch
UtilicelapropiedadFileSearchparadevolverelobjetoFileSearch.Elsiguienteejemplobuscalosarchivosespecificadosymuestraelnúmerodearchivosencontradosyelnombredecadaarchivo.
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
UtiliceelmétodoNewSearchpararestablecerelvalorpredeterminadodelabúsquedadecriterios.Todoslosvaloresdelaspropiedadessemantienendespuésdeejecutarcadabúsqueday,utilizandoelmétodoNewSearchesposibleestablecerdeformaselectivalaspropiedadesdelasiguientebúsquedadearchivossinrestablecerdeformamanuallosvaloresanteriores.Elsiguienteejemplorestableceloscriteriosdebúsquedapredeterminadosantesdecomenzarunanuevabúsqueda.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.FileName="Run"
.MatchTextExactly=True
.FileType=msoFileTypeAllFiles
EndWith
ColecciónFileTypesFileSearch FileTypes
UnacoleccióndevaloresdeltipomsoFileTypequedeterminaquétiposdearchivossedevuelvenconelmétodoExecutedelobjetoFileSearch.
UtilizarlacolecciónFileTypes
UtilicelapropiedadFileTypesconelobjetoFileSearchparadevolverunacolecciónFileTypes,porejemplo:
Setft=Application.FileSearch.FileTypes
NotaLapropiedadFileTypedelobjetoFileSearchborralacolecciónFileTypesyestableceelprimerelementodelacolecciónaltipodearchivoquedefinalapropiedadFileType.
SóloexisteunacolecciónFileTypesparatodaslasbúsquedas,porloqueesimportanteborrarlacolecciónFileTypesantesderealizarunabúsqueda,amenosquedeseebuscarlostiposdearchivosdebúsquedasanteriores.LaformamássencilladeborrarlacolecciónesestablecerlapropiedadFileTypeparaelprimertipodearchivoquedeseebuscar.TambiénpuedequitartiposindividualesmedianteelmétodoRemove.Paradeterminareltipodearchivodecadaelementodelacolección,utiliceelmétodoItemafindedevolverelvalormsoFileType.
ElejemplosiguientebuscatodoslosarchivosdeMicrosoftExcelyHTMLdelaunidadC:\.
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
ElejemplosiguienterecorrelacolecciónFileTypesyquitalostiposdearchivoquenoseandeMicrosoftWordoMicrosoftExcel(engeneral,esmássencilloborrarlacolecciónFileTypesyempezardecero).
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
ObjetoFoundFilesFileSearch PropertyTests(PropertyTest)FoundFiles
Representalalistadearchivosdevueltosenunabúsquedadearchivos.
UsodelobjetoFoundFiles
UtilicelapropiedadFoundFilesparadevolverelobjetoFoundFiles.Esteejemplorecorrelalistadearchivosencontradosymuestralarutadeaccesoyelnombredecadaarchivo.UtiliceFoundFiles(index),donde(index)eselnúmerodelíndice,paravolveralarutadeaccesoyalnombredelarchivodeunarchivoespecíficoencontradodurantelabúsqueda.
WithApplication.FileSearch
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
NextI
EndWith
UtiliceelmétodoExecuteparacomenzarlabúsquedadearchivosyactualizarelobjetoFoundFiles.ElsiguienteejemplobuscaenlacarpetaMyDocumentstodoslosarchivosquecomiencenpor"Cmd"ymuestralaubicaciónynombredecadaarchivoencontrado.Elejemplotambiénordenalosarchivosdevueltospornombredearchivoenordenalfabéticoascendente.
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
ObjetoHTMLProjectHTMLProject HTMLProjectItems(HTMLProjectItem)
Representaunaramadeproyectodenivelsuperior,comoenelEditordesecuenciasdecomandosdelExploradordelproyecto.
UtilizarelobjetoHTMLProject
UtiliceelmétodoOpendelobjetoHTMLProjectparaabrirunproyectoHTMLenelEditordesecuenciasdecomandosdeMicrosoft.ElproyectoseabreunavistaoriginalounavistadetextodeldocumentoactivodeMicrosoftWord,dellibroactivodeExcelodelapresentaciónactivadePowerPoint.ElejemplosiguienteabreenvistaoriginalunproyectoHTMLdeldocumentoactivodeWord.
ActiveDocument.HTMLProject.Open(msoHTMLProjectOpenSourceView)
UtilicelapropiedadHTMLProjectItemsparadevolverlacoleccióndeobjetosHTMLProjectItemdelproyectoHTML.UtiliceelmétodoRefreshDocumentparaactualizareldocumentoHTMLenlaaplicaciónhost.UtiliceelmétodoRefreshProjectparaactualizarelproyectoenelEditordesecuenciasdecomandosdeMicrosoft.UtiliceelmétodoStateparadeterminarsiesprecisoactualizarelproyectoHTML.
ObjetoHTMLProjectItemHTMLProject HTMLProjectItems(HTMLProjectItem)
RepresentaunobjetoindividualdeunproyectoqueconstituyeunaramadeelementodelproyectoenelExploradordelProyectodelEditordesecuenciasdecomandosdeMicrosoft.ElobjetoHTMLProjectItemespartedelacolecciónHTMLProjectItems.
UtilizarelobjetoHTMLProjectItem
UtiliceHTMLProjectItems(index),dondeindexeselnombreoelnúmerodeíndicedeunelementodeproyecto,paradevolverunsoloobjetoHTMLProjectItem.UtilicelapropiedadNameparadevolverelnombreparamostrardelelementodeproyecto.ElejemplosiguientedevuelveelnombredelprimerelementodelproyectoenlacolecciónHTMLProjectItemsdeldocumentoactivo.
MsgBox"Thefirstitemis"&_
ActiveDocument.HTMLProject.HTMLProjectItems(1).Name
UtiliceelmétodoOpenparaabrirelelementodeunproyectoenvistaoriginaloenvistadetexto;utilicelapropiedadIsOpenparadeterminarsielelementodelproyectoestáabiertoactualmente.Elejemplosiguienteabreelelementodelproyectodenombre"ItemOne"(eneldocumentoactivo)enlavistapredeterminaday,acontinuación,muestrauncuadrodemensajequeindicasielelementosehaabiertocorrectamente.
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne").Open
IfActiveDocument.HTMLProject._
HTMLProjectItems("ItemOne").IsOpenThen
MsgBox"Openedprojectitem"&ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne").Name
EndIf
UtiliceelmétodoSaveCopyAsparaguardarelelementodelproyectoutilizandounnuevonombredearchivo.ElejemplosiguienteguardaunacopiadeItemOnecomo"NewItem".
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne")_
.Open(msoHTMLProjectOpenTextView)
ActiveDocument.HTMLProject.HTMLProjectItems("ItemOne")_
.SaveCopyAs("C:\NewItem.txt")
SuponiendoqueexistaelarchivodetextoC:\NewText.txt,elejemplosiguienteutilizarálapropiedadLoadFromFileparaestablecereltextodeItemOnealtextocontenidoenelarchivo.ElejemplosiguienteutilizalapropiedadTextparamostrarelnuevotextoenuncuadrodemensaje.
MsgBoxActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").Text
ActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").LoadFromFile("C:\NewText.txt")
MsgBoxActiveDocument.HTMLProject.HTMLProjectItems_
("ItemOne").Text
ObjetodecolecciónHTMLProjectItemsHTMLProject HTMLProjectItems(HTMLProjectItem)
UnacoleccióndeobjetosHTMLProjectItemquerepresentaloselementosdelproyectoHTMLcontenidosenelobjetoHTMLProject.
UtilizarlacolecciónHTMLProjectItems
UtilicelapropiedadHTMLProjectItemsdelobjetoHTMLProjectparadevolverlacolecciónHTMLProjectItems.UtilicelapropiedadCountdelacolecciónHTMLProjectItemsparadevolverelnúmerodeelementosdelproyectoHTMLdeldocumentoespecificado.UtiliceelmétodoItemdelacolecciónHTMLProjectItemsparadevolverunobjetoindividualdeunproyecto.ElejemplosiguientedevuelveelnombredelprimerelementodelproyectoenlacolecciónHTMLProjectItemsdeldocumentoactivo.
MsgBox"Thefirstitemis"&_
ActiveDocument.HTMLProject.HTMLProjectItems(1).Name
ObjetoLanguageSettingsLanguageSettings
DevuelveinformaciónsobrelaconfiguracióndeidiomadeunaaplicacióndeMicrosoftOffice.
UtilizarelobjetoLanguageSettings
UtiliceApplication.LanguageSettings.LanguageID(MsoAppLanguageID),dondeMsoAppLanguageIDesunaconstanteutilizadaparadevolverinformacióndelidentificadorlocal(LCID)alaaplicaciónespecificada.
MsoAppLanguageIDpuedeserunadeestasconstantesdeMsoAppLanguageID.msoLanguageIDExeModemsoLanguageIDHelpmsoLanguageIDInstallmsoLanguageIDUImsoLanguageIDUIPrevious
Elejemplosiguientedevuelveenuncuadrodemensajeelidiomadeinstalación,elidiomadelainterfazdeusuarioylosidentificadoreslocalesdelidiomadeayuda.
MsgBox"ThefollowinglocaleIDsareregistered"&_
"forthisapplication:InstallLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDInstall)&_
"UserInterfaceLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDUI)&_
"HelpLanguage-"&_
Application.LanguageSettings.LanguageID(msoLanguageIDHelp)
UtiliceApplication.LanguageSettings.LanguagePreferredForEditingparadeterminarlosLCIDqueseregistraráncomoidiomasdeediciónpreferidosenlaaplicación,talcomosemuestraenelejemplosiguiente.
IfApplication.LanguageSettings._
LanguagePreferredForEditing(msoLanguageIDEnglishUS)Then
MsgBox"U.S.Englishisoneofthechoseneditinglanguagess."
EndIf
ObjetoMsoEnvelopeMsoEnvelope CommandBars
ProporcionaaccesoafuncionesquelepermitenenviardocumentoscomocorreoselectrónicosdirectamentedesdeaplicacionesdeMicrosoftOffice.
UtilizarelobjetoMsoEnvelope
UtilicelapropiedadMailEnvelopedelosobjetosDocument,ChartoWorksheet,segúnlaaplicaciónqueestéutilizando,paradevolverunobjetoMsoEnvelope.
ElejemplosiguienteenvíaeldocumentoactivodeMicrosoftWordcomouncorreoelectrónicoaladireccióndecorreoelectrónicoquepasealasubrutina.
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
ObjetoNewFileNewFile
ElobjetoNewFilerepresentaloselementosenumeradosenelpaneldetareasNuevoelementodisponibleenvariasaplicacionesdeMicrosoftOffice.LatablasiguientemuestralapropiedadqueseutilizaráparateneraccesoalobjetoNewFileencadaaplicación.
Aplicación PropiedadMicrosoftAccess NewFileTaskPaneMicrosoftExcel NewWorkbookMicrosoftFrontPage NewPageOrWebMicrosoftPowerPoint NewPresentationMicrosoftWord NewDocument
NotaLosejemplosquefiguranacontinuaciónsonparaWord,peropuedecambiarlapropiedadNewDocumentparacualquieradelaspropiedadesenumeradasanteriormenteyutilizarelcódigodelaaplicacióncorrespondiente.
UtilizarelobjetoNewFile
UtiliceelmétodoAddparaagregarunelementonuevoalpaneldetareasNuevoelemento.ElejemplosiguienteagregaunelementoalpaneldetareasdeWordNuevodocumento.
SubAddNewDocToTaskPane()
Application.NewDocument.AddFileName:="C:\NewDocument.doc",_
Section:=msoNew,DisplayName:="NewDocument"
CommandBars("TaskPane").Visible=True
EndSub
UtiliceelmétodoRemoveparaquitarunelementodelpaneldetareasNuevoelemento.ElejemplosiguientequitaeldocumentoagregadoenelejemploanteriordelpaneldetareasNuevodocumentodeWord.
SubRemoveDocFromTaskPane()
Application.NewDocument.RemoveFileName:="C:\NewDocument.doc",_
Section:=msoNew,DisplayName:="NewDocument"
CommandBars("TaskPane").Visible=True
EndSub
ObjetoODSOColumnODSOColumns ODSOColumn
Representauncampodeunorigendedatos.ElobjetoODSOColumnesunmiembrodelacolecciónODSOColumns.LacolecciónODSOColumnsincluyetodosloscamposdedatosdeunorigendedatosdecombinacióndecorrespondencia(porejemplo,Nombre,DirecciónyCiudad).
UtilizarelobjetoODSOColumn
UtiliceColumns(index),dondeindexeselnúmerodeíndiceoelnombredeuncampodedatos,paradevolverunsoloobjetoODSOColumn.Elnúmerodeíndicerepresentalaposicióndelcampodedatosenelorigendedatosdecombinacióndecorrespondencia.Esteejemplorecuperaelnombreyvalordelprimercampodelprimerregistrodelorigendedatosadjuntoalapublicaciónactiva.
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
Comentarios
NopuedeagregarcamposalacolecciónODSOColumns.TodosloscamposdedatosdeunorigendedatosseincluyenautomáticamenteenlacolecciónODSOColumns.
ObjetoODSOColumnsOfficeDataSourceObject ODSOColumns ODSOColumn
UnacoleccióndeobjetosODSOColumnquerepresentaloscamposdedatosdeunorigendedatosdecombinacióndecorrespondencia.
UtilizarelobjetoODSOColumns
UtilicelapropiedadColumnsparadevolverlacolecciónODSOColumns.Elejemplosiguientemuestralosnombresdecamposdelorigendedatosadjuntoalapublicaciónactiva.
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
UtiliceColumns(index),dondeindexeselnombreoelnúmerodeíndicedeuncampodedatos,paradevolverunsoloobjetoODSOColumn.Elnúmerodeíndicerepresentalaposicióndelcampodedatosenelorigendedatosdecombinacióndecorrespondencia.EsteejemplorecuperaelnombredelprimercampoyelvalordelprimerregistrodelcampoNombredelorigendedatosadjuntoalapublicaciónactiva.
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
ObjetoODSOFilterODSOFilters ODSOFilter
Representaelfiltroqueseaplicaráaunorigendedatosdecombinacióndecorrespondenciaadjunto.ElobjetoODSOFilteresunmiembrodelobjetoODSOFilters.
UtilizarelobjetoODSOFilter
Cadafiltroesunalíneadeunacadenadeconsulta.UtilicelaspropiedadesColumn,Comparison,CompareToyConjunctionparadevolveroestablecerelcriteriodeconsultadelorigendedatos.ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistroscuyocampoRegiónnosea"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
UtiliceelmétodoAdddelobjetoODSOFiltersparaagregaruncriteriodefiltronuevoaunaconsulta.Esteejemploagregaunalíneanuevaalacadenadeconsultay,acontinuación,aplicaelfiltrocombinadoalorigendedatos.
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
ObjetoODSOFiltersOfficeDataSourceObject ODSOFilters ODSOFilter
Representatodoslosfiltrosparaaplicaralorigendedatosadjuntoalapublicacióndecombinacióndecorrespondencia.ElobjetoODSOFiltersconstadeobjetosODSOFilter.
UtilizarelobjetoODSOFilters
UtiliceelmétodoAdddelobjetoODSOFiltersparaagregaruncriteriodefiltronuevoaunaconsulta.Esteejemploagregaunalíneanuevaalacadenadeconsultay,acontinuación,aplicaelfiltrocombinadoalorigendedatos.
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
UtiliceelmétodoItemparateneraccesoauncriteriodefiltroconcreto.Esteejemplorecorretodoelcriteriodefiltroysiencuentraunoconunvalorde"Región",locambiaparaquitardelacombinacióndecorrespondenciatodoslosregistrosquenosean"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
ObjetoOfficeDataSourceObjectOfficeDataSourceObject Variosobjetos
Representaelorigendedatosdecombinacióndecorrespondenciadeunaoperacióndecombinacióndecorrespondencia.
UtilizarelobjetoOfficeDataSourceObject
ParatrabajarconelobjetoOfficeDataSourceObject,dimensioneunavariablecomounobjetoOfficeDataSourceObject.Acontinuaciónpuedetrabajarconlosdiferentesmétodosypropiedadesasociadosconelobjeto.UtiliceelmétodoSetSortOrderparaespecificarcómoseclasificaránlosregistrosdeunorigendedatos.Elejemplosiguienteclasificaprimeroelorigendedatossegúnelcódigopostalenordendescendente,acontinuación,segúnelapellidoyelnombredepilaenordenascendente.
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
UtilicelaspropiedadesColumn,Comparison,CompareToyConjunctionparadevolveroestablecerelcriteriodeconsultadeorigendedatos.ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistroscuyocampoRegiónnosea"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
ObjetoPropertyTestsFileSearch PropertyTests(PropertyTest)FoundFiles
Representauncriterioindividualdebúsquedadearchivos.LoscriteriosdebúsquedasemuestranenelcuadrodediálogoBúsquedaavanzada(menúArchivo,comandoAbrir,botónAvanzada).ElobjetoPropertyTestesunmiembrodelacolecciónPropertyTests.
UsodelobjetoPropertyTest
UtilicePropertyTests(index),dondeindexeselnúmerodeíndice,paradevolverunobjetoPropertyTest.ElsiguienteejemplomuestratodosloscriteriosdebúsquedadelaprimerapruebadepropiedadesdelacolecciónPropertyTests.
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
ObjetodecolecciónPropertyTestsFileSearch PropertyTests(PropertyTest)FoundFiles
ColeccióndeobjetosPropertyTestquerepresentatodosloscriteriosdebúsquedadeunabúsquedadearchivos.LoscriteriosdebúsquedasemuestranenelcuadrodediálogoBúsquedaavanzada(menúArchivo,comandoAbrir,botónAvanzada).
UsodelacolecciónPropertyTests
UtilicelapropiedadPropertyTestsparadevolverlacolecciónPropertyTests.Elsiguienteejemplomuestraelnúmerodecriteriosdebúsquedaavanzadaqueseutilizaránenunabúsquedadearchivos.
Application.FileSearch.PropertyTests.Count
UtiliceelmétodoAddparaagregarunnuevoobjetoPropertyTestalacolecciónPropertyTests.Elsiguienteejemploagregadospruebasdepropiedadaloscriteriosdebúsqueda.Elprimercriterioespecificaquelosarchivosencontradospuedenserarchivosdecualquiertipoyelsegundocriterioespecificaquelosarchivosdebenhabersidomodificadosentreel1deeneroyel30dejuniode1996.Elejemplomuestraelnúmerodearchivosencontradosyelnombredecadaarchivoenuncuadrodemensaje.
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
UtilicePropertyTests(index),dondeindexeselnúmerodeíndice,paradevolverunobjetoPropertyTest.ElsiguienteejemplomuestratodosloscriteriosdebúsquedadelaprimerapruebadepropiedadesdelacolecciónPropertyTests.
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
ObjetoScopeFolderVariosobjetos ScopeFolder ScopeFolders
Correspondeaunacarpetaenlaquesepuedenrealizarbúsquedas.LosobjetosScopeFolderpuedenutilizarseconlacolecciónSearchFolders.LacolecciónSearchFoldersdefinelascarpetasquesebuscanalutilizarelobjetoFileSearch.SideseabuscarcarpetasespecíficaspuedeutilizarlosmétodosylaspropiedadesdelobjetoSearchScopeydelacolecciónScopeFolderspararecuperarlosobjetosScopeFolderyagregarlosalacolecciónSearchFolders.
UtilizarelobjetoScopeFolder
UtilicelapropiedadScopeFolderdelobjetoSearchScopeparadevolverelobjetoScopeFolderraízdeunámbitodebúsqueda,porejemplo:
Setsf=Application.FileSearch.SearchScopes.Item(1).ScopeFolder
UtiliceelmétodoItemdelacolecciónScopeFoldersparadevolverunasubcarpetadeunobjetoScopeFolderraíz,porejemplo:
Setsf=Application.FileSearch.SearchScopes.Item(1).ScopeFolder.ScopeFolders.Item(1)
UtiliceelmétodoItemdelacolecciónSearchFoldersparadevolverlacarpetaquesebuscarálapróximavezqueseactiveelmétodoExecutedelobjetoFileSearch;porejemplo:
Setsf=Application.FileSearch.SearchFolders.Item(1)
EncadaobjetoScopeFolderhayunacolecciónScopeFoldersquecontienelassubcarpetasdelobjetoScopeFoldermaestro.Puedeatravesartodalaestructuradelacarpetadeunámbitodebúsqueda,porejemplo,todaslasunidadeslocales,recorriendolascoleccionesScopeFoldersydevolviendotodoslosobjetosScopeFolderdenivelinferior.UnobjetoScopeFoldersinsubcarpetascontieneunacolecciónScopeFoldersvacía.
EneltemarelativoacolecciónSearchFolderspuedeencontrarunejemplosobrecómorecorrertodoslosobjetosScopeFolderdeunámbitodebúsqueda.
PuedeutilizarelmétodoAdddelacolecciónSearchFoldersparaagregarunobjetoScopeFolderalacolecciónSearchFolders,sinembargo,generalmenteesmásfácilutilizarelmétodoAddToSearchFoldersdelScopeFolderquedeseeagregar,yaquesóloexisteunasolacolecciónSearchFoldersparatodaslasbúsquedas.
EneltemarelativoalacolecciónSearchFolderspuedeencontrarunejemplosobrecómoagregarunScopeFolderalacolecciónSearchFolders.
ElejemplosiguientemuestralarutadeaccesoraízacadadirectoriodeMiPC.Pararecuperarestainformación,elejemploobtieneprimeroelobjeto
ScopeFolderdelaraízdeMiPC.LarutadeaccesoaesteobjetoScopeFolderserásiempre"*".ComocontodoslosobjetosScopeFolder,elobjetoraízcontieneunacolecciónScopeFolders.EsteejemplorecorreestacolecciónScopeFoldersymuestralarutadeaccesoacadaobjetoScopeFolderdelamisma.LasrutasdeaccesoaestosobjetosScopeFolderserán"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
ColecciónScopeFoldersScopeFolder ScopeFolders ScopeFolder
ColeccióndeobjetosScopeFolder.SólolosobjetosScopeFoldercontienencoleccionesScopeFolders.CadacolecciónScopeFolderscontienelosobjetosScopeFolderquecorrespondenalassubcarpetasdelobjetoScopeFoldermaestro.
UtilizarlacolecciónScopeFolders
UtilicelapropiedadScopeFoldersdelobjetoScopeFolderparadevolverunacolecciónScopeFolders.
DimsfsasScopeFolders
Setsfs=Application.FileSearch.SearchScopes.Item(1).ScopeFolder.ScopeFolders
NopuedeagregaroquitarobjetosScopeFolderdeunacolecciónScopeFolders.
ObjetoScriptScripts(Script)
RepresentaunbloquedesecuenciasdecomandosHTMLenundocumentodeMicrosoftWord,enunahojadecálculodeMicrosoftExceloenunadiapositivadeMicrosoftPowerPoint.ElobjetoScriptespartedelacolecciónScripts.
UtilizarelobjetoScript
UtiliceScripts.Item(index),dondeindexeselnombre,elIDoelnúmerodeíndicedeunasecuenciadecomandos,paradevolverunsoloobjetoScript.CadaobjetoScriptseidentificaconlapropiedadId,queproporcionaunnombreadecuadoquepuedeutilizarparaobteneraccesoalasecuenciadecomandos.ElejemplosiguienteagregaunasolasecuenciadecomandosalacolecciónScriptseneldocumentoactivoymuestraelIDdelasecuenciadecomandosconelvalordeíndice1.
myScript=ActiveDocument.Scripts.Add(_
,msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"ScriptOne",,_
"MsgBox(""ThisisScriptOne."")")
MsgBox(ActiveDocument.Scripts(1).Id)
PuedeespecificarellenguajedecomandosutilizadoenlasecuenciadecomandoscambiandolapropiedadLanguage.ElejemplosiguientecambiaellenguajedecomandosdelasecuenciadecomandosunoapáginasActiveServer(ASP).
ActiveDocument.Scripts.Item("ScriptOne")_
.Language=msoScriptLanguageASP
PuedecomprobarlaubicacióndelaformadeldelimitadordelasecuenciadecomandosenundocumentoHTMLmediantelapropiedadLocation.ElejemplosiguienterealizaunacomprobaciónparadeterminarsiScriptOneestáenelcuerpodeldocumentoHTMLactivo.
IfActiveDocument.Scripts("ScriptOne").Location=_
msoScriptLocationInBodyThen
MsgBox("ScriptisintheHTMLdocumentbody.")
Else
MsgBox("Scriptislocatedintheheader.")
EndIf
Puedecomprobaroestablecerlosatributosagregadosalaetiqueta<SCRIPT>(aexcepcióndelosatributosLANGUAGEeID)utilizandolapropiedadExtended.Elejemplosiguientecompruebalosatributosadicionalesdelasecuenciadecomandosunodeldocumentoactivo.
IfActiveDocument.Scripts(1).Extended=""Then
MsgBox("Noadditionalattributesarepresent"&_
"inScript"&
ActiveDocument.Scripts(1).Id)
PuedecomprobaroestablecereltextodelasecuenciadecomandosasociadoconunasecuenciadecomandosdeterminadamediantelapropiedadScriptText.Elejemplosiguientemuestrauncuadrodemensajequecontieneeltextodesecuenciadecomandosasociadoconlasecuenciadecomandosunodeldocumentoactivo.
MsgBox(ActiveDocument.Scripts("ScriptOne").ScriptText)
ObjetodecolecciónScriptsScripts(Script)
ColeccióndeobjetosScriptquerepresentalacoleccióndesecuenciasdecomandosHTMLdeldocumentoespecificado.
UtilizarlacolecciónScripts
LacolecciónScriptscontienetodoslosobjetosScriptdeundocumentodeterminado,enelordenoriginal(elordenelquelosobjetosScriptseagregaronalarchivodeorigen).Elordenoriginalnoseveafectadoporlaubicación(encabezadootextoindependiente)delasecuenciadecomandosdentrodeldocumento.PuedeutilizarobjetosScriptparaobteneraccesoaunasecuenciadecomandosoparaagregarunasecuenciadecomandosaundocumentodeMicrosoftWord,aunahojadeMicrosoftExceloaunadiapositivadeMicrosoftPowerPoint.TambiénpuedeutilizarlacolecciónScriptsparaobteneraccesoacualquierpáginaosecuenciadecomandosHTMLqueseabraenunaaplicacióndeMicrosoftOffice.
NotaMicrosoftAccessnoutilizaestecomponentecompartidodeOffice.
AgregarunobjetoScript
CuandoagregaunobjetoScriptalacolecciónScripts,seagregaráautomáticamenteunobjetoShapedetipomsoScriptAnchoraldocumento.EnunahojadeExceloenunadiapositivadePowerPoint,laformaseagregaráalacolecciónShapes;enundocumentodeWord,laformaseagregaráalacolecciónInlineShapes.ParaagregarunScriptaundocumento,utiliceelmétodoAdd.ElejemplosiguienteagregaunasolasecuenciadecomandosaldocumentoactivodeWord.
myScript=ActiveDocument.Scripts.Add(_
,msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"ScriptOne",,_
"MsgBox""ThisisScriptOne.""")
ParaobteneraccesoaunelementoconcretodelacolecciónScripts,utiliceelmétodoItemyproporcioneelatributoIDdelaetiqueta<SCRIPT>oelnúmerodeíndicequeindicalaposicióndelasecuenciadecomandosdentrodelacolección.ElIDdebeserúnicodentrodeldocumento.EnelcasodequeexistanatributosIDduplicados,sedevolverálaprimerasecuenciadecomandoscondichoIDqueseencuentre.ElejemplosiguientemuestrauncuadrodemensajequeindicalaprimerasecuenciadecomandosencontradaqueutilizaelID"ScriptOne".
MsgBox(ActiveDocument.Scripts.Item("ScriptOne").Language)
UtilicelapropiedadCountparadeterminarelnúmerodeobjetosScripteneldocumentoespecificado.Elejemplosiguientemuestraelnúmerodesecuenciasdecomandosquehayeneldocumentoactivo.
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
UtiliceelmétodoDeleteparaquitarunasecuenciadecomandosdelacolecciónScripts,talcomoseindicaenelejemplosiguiente.
ActiveDocument.Scripts("ScriptOne").Delete
ColecciónSearchFoldersFileSearch SearchFolders ScopeFolder
ColeccióndeobjetosScopeFolderquedeterminaenquécarpetasserealizarálabúsquedaalactivarelmétodoExecutedelobjetoFileSearch.
UtilizarlacolecciónSearchFolders
UtilicelapropiedadSearchFoldersconelobjetoFileSearchparadevolverlacolecciónSearchFolders,porejemplo:
Setsfs=Application.FileSearch.SearchFolders
ParacadaaplicaciónsólohayunacolecciónSearchFolders.Elcontenidodelacolecciónpermanecedespuésdequeelcódigoquelahallamadohayaacabadodeejecutarse.Porello,esimportanteborrarlacolección,amenosquedeseeincluircarpetasdebúsquedaspreviasenestabúsqueda.
PuedeutilizarelmétodoAdddelacolecciónSearchFoldersparaagregarunobjetoScopeFolderalacolecciónSearchFolders,sinembargo,generalmenteesmásfácilutilizarelmétodoAddToSearchFoldersdelScopeFolderquedeseeagregar,yaquesóloexisteunasolacolecciónSearchFoldersparatodaslasbúsquedas.
LacolecciónSearchFolderspuedeversecomouncomplementodelapropiedadLookIndelobjetoFileSearch.Lasdosespecificanlascarpetasdebúsquedayseutilizanalrealizarlabúsqueda.Sinembargo,sisólodeseautilizarlapropiedadLookIn,deberáasegurarsedequelacolecciónSearchFoldersestávacía.Alainversa,sisólodeseautilizarlacolecciónSearchFolders,establezcalapropiedadLookInparalarutadeaccesoalprimermiembrodelacolecciónSearchFoldersantesdeactivarelmétodoExecute.
Elejemplosiguientebuscaentodaslascarpetasdenominadas"1033"delamáquinalocaltodoslosarchivosdeMicrosoftExcelyHTML.ElejemploutilizalascoleccionesSearchFolders,SearchScopesyScopeFolders.
Esteejemploconstadedosrutinas.LarutinaSearchEveryFoldereslarutinaquedeberáejecutar.LarutinaOutputPathssediferenciadelaprincipalenqueéstasellamarepetidamenteafindeatravesartodalaestructuradedirectoriosdelamáquinalocal.
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
ObjetoSearchScopeSearchScopes SearchScope ScopeFolder
CorrespondeauntipodeárboldecarpetasquesepuedebuscarutilizandoelobjetoFileSearch.Porejemplo,lasunidadeslocalesdesuequiporepresentanunsoloámbitodebúsqueda.LascarpetasderedylasdeMicrosoftOutlooksontambiéndosámbitosindividualesdebúsquedadisponibles.CadaobjetoSearchScopeincluyeunsoloobjetoScopeFolderquecorrespondealacarpetaraízdelámbitodebúsqueda.
UtilizarelobjetoSearchScope
UtiliceelmétodoItemdelacolecciónSearchScopesparadevolverunobjetoSearchScope,porejemplo:
DimssAsSearchScope
Setss=Application.FileSearch.SearchScopes.Item(1)
Enúltimainstancia,elobjetoSearchScopeseutilizaparaproporcionaraccesoalosobjetosScopeFolderquepuedenagregarsealacolecciónSearchFolders.Sideseaverunejemploalrespecto,consulteeltemarelativoalacolecciónSearchFolders.
ConsulteeltemarelativoalobjetoScopeFolderparaverunsencilloejemplodeladevolucióndeunobjetoScopeFolderdesdeunobjetoSearchScope.
ElejemplosiguientemuestratodoslosobjetosSearchScopedisponiblesactualmente.
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
ColecciónSearchScopesFileSearch SearchScopes SearchScope
UnacoleccióndeobjetosSearchScope.
UtilizarlacolecciónSearchScopes
UtilicelapropiedadSearchScopesdelobjetoFileSearchparadevolverunacolecciónSearchScopes,porejemplo:
DimsssAsSearchScopes
Setsss=Application.FileSearch.SearchScopes
NopuedeagregaroquitarobjetosSearchScopedelacolecciónSearchScopes.
ObjetoSignatureSignatureSet Signature
Correspondeaunafirmadigitalqueseadjuntaaundocumento.LosobjetosSignatureseincluyenenlacolecciónSignatureSetdelobjetoDocument.
UtilizarelobjetoSignature
PuedeutilizarunobjetoSignatureparaunacolecciónSignatureSetutilizandoelmétodoAddydevolverunmiembroexistenteutilizandoelmétodoItem.ParaquitarunobjetoSignaturedeunacolecciónSignatureSet,utiliceelmétodoDeletedelobjetoSignature.
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
ColecciónSignatureSetSignatureSet Signature
UnacoleccióndeobjetosSignaturequecorrespondealasfirmasdigitalesadjuntasaundocumento.
UtilizarlacolecciónSignatureSet
UtilicelapropiedadSignaturesdelobjetoDocumentparadevolverunacolecciónSignatureSet,porejemplo:
Setsigs=ActiveDocument.Signatures
NotaNoseconservaránloscambiosquerealiceenlacolecciónSignatureSet,amenosqueactiveelmétodoCommit.
PuedeutilizarunobjetoSignatureparaunacolecciónSignatureSetutilizandoelmétodoAddydevolverunmiembroexistenteutilizandoelmétodoItem.ParaquitarunobjetoSignaturedeunacolecciónSignatureSet,utiliceelmétodoDeletedelobjetoSignature.
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
ObjetoWebPageFontWebPageFonts(WebPageFont)
RepresentalafuentepredeterminadautilizadacuandolosdocumentosseguardancomopáginasWebenunjuegodecaracteresconcreto.
UtilizarelobjetoWebPageFont
UtiliceelobjetoWebPageFontparadescribirlafuenteproporcional,eltamañodefuenteproporcional,lafuentedeanchofijoyeltamañodelafuentedeanchofijoparacualquierjuegodecaracteresdisponibles.
Seadmitenlossiguientesjuegosdecaracteres:msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
ElsiguienteejemploestablecelafuenteproporcionalyeltamañodelafuenteproporcionalparaelobjetoWebPageFontmyFont.
WithmyFont
ProportionalFont=Verdana
ProportionalFontSize=14
ObjetodecolecciónWebPageFontsWebPageFonts(WebPageFont)
ColeccióndeobjetosWebPageFontquedescribelafuenteproporcional,eltamañodelafuenteproporcional,lafuentedeanchofijoyeltamañodelafuentedeanchofijoqueseutilizancuandolosdocumentosseguardancomopáginasWeb.PuedeespecificarunconjuntodiferentedepropiedadesdepáginasWebparacadajuegodecaracteresqueestédisponible.
UtilizarlacolecciónWebPageFonts
LacolecciónWebPageFontscontieneunobjetoWebPageFontparacadajuegodecaracteres.
Seadmitenlossiguientesjuegosdecaracteres:msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
ElejemplosiguienteutilizalapropiedadItemparaestablecermyFontenelobjetoWebPageFontparaeljuegodecaracteresdesecuenciasdecomandosInglés/Europeooccidental/Otroalfabetolatinodentrodelaaplicaciónactual.
DimmyFontAsWebPageFont
SetmyFont=_
Application.DefaultWebOptions.Fonts.Item_
(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)
MétodoActivateWizard
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
ContinúaodetienelaAyudadelAyudantedeOfficedurantelaejecucióndeunasistentepersonalizado.
NotaDebeutilizarestemétodosóloparacompletarelprocesoiniciadoconelmétodoStartWizard.
expresión.ActivateWizard(WizardID,Act,Animation)
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
WizardIDLongrequerido.NúmeroúnicoqueidentificalasesióndelAsistenteparaelAyudantedeOffice,devueltoporelmétodoStartWizard.
ActMsoWizardActTyperequerido.EspecificaelcambioalasesióndeAyudadelAyudantedeOffice.
MsoWizardActTypepuedeserunadeestasconstantesdeMsoWizardActType.msoWizardActActivemsoWizardActInactivemsoWizardActResumemsoWizardActSuspend
AnimationVariantopcional.LaanimacióndelAyudantedeOfficeserealizacuandosesuspendeosecontinúa.
Ejemplo
EsteejemplocancelalasesióndelasistenteiniciadoconelmétodoStartWizard.LavariableIHelpForWizsehaestablecidoenelvalordevueltoporelmétodoStartWizard.
Assistant.ActivateWizardWizardID:=lHelpForWiz,_
Act:=msoWizardActSuspend,Animation:=msoAnimationGoodbye
Mostrartodo
MétodoAdd
MétodoAddcuandoseaplicaalobjetoNewFile.
AgregaunelementonuevoalpaneldetareasNuevoElemento.DevuelveunvalorBoolean.Truesielelementosehaagregadocorrectamente.
expression.Add(FileName,Section,DisplayName,Action)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
FilenameStringrequerida.Elnombredelarchivoqueseagregaalalistadearchivosdelpaneldetareas.
SectionVariantopcional.Lasecciónalaqueseagregaelarchivo.PuedesercualquierconstantemsoFileNewSection.
DisplayNameVariantopcional.Eltextoquesemuestraenelpaneldetareas.
ActionVariantopcional.Laacciónqueseejecutacuandoelusuariohaceclicenelelemento.PuedesercualquierconstantemsoFileNewSection.
MétodoAddcuandoseaplicaalobjetoCommandBars.
Creaunanuevabarradecomandosylaagregaalacoleccióndebarrasdecomandos.DevuelveunobjetoCommandBar.
expresión.Add(Name,Position,MenuBar,Temporary)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBars.
NameVariantopcional.Nombredelanuevabarradecomandos.Siseomiteesteargumento,Wordasignaráunnombrepredeterminadoalabarradecomandos,porejemplo,Custom1.
PositionVariantopcional.Posiciónotipodelanuevabarradecomandos.
PuedeserunadelasconstantesMsoBarPositionqueaparecenenlasiguientetabla:
Constante Descripción
msoBarLeft,msoBarTop,msoBarRight,msoBarBottom
Indicalascoordenadasizquierda,derecha,superioreinferiordelanuevabarradecomandos.
msoBarFloating Indicaquelanuevabarradecomandosnoestaráacoplada.
msoBarPopup Indicaquelanuevabarradecomandosseráunmenúcontextual.
msoBarMenuBar SóloparaMacintosh.
MenuBarVariantopcional.Trueparareemplazarlabarrademenúactivaconlanuevabarradecomandos.ElvalorpredeterminadoesFalse.
TemporaryVariantopcional.Trueparaquelanuevabarradecomandosseatemporal.Lasbarrasdecomandostemporalesseeliminanalcerrarlaaplicacióncontenedora.ElvalorpredeterminadoesFalse.
MétodoAddcuandoseaplicaalobjetoCommandBarControls.
CreaunobjetoCommandBarControlnuevoyloagregaalacoleccióndecontrolesdelabarradecomandosespecificada.
expresión.Add(Type,Id,Parameter,Before,Temporary)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarControls.
TypeVariantopcional.Tipodecontrolqueseagregaalabarradecomandosespecificada.PuedeserunadelasconstantesdeMsoControlTypesiguientes:msoControlButton,msoControlEdit,msoControlDropdown,msoControlComboBoxomsoControlPopup.
IdVariantopcional.Númeroenteroqueespecificauncontrolintegrado.Sielvalordeesteargumentoes1,osiseomiteesteargumento,seagregaráalabarradecomandosuncontrolpersonalizadoenblancodeltipoespecificado.
ParameterVariantopcional.Paracontrolesintegrados,laaplicacióncontenedorautilizaesteargumentoparaejecutarelcomando.Encontrolespersonalizados,esteargumentopuedeutilizarseparaenviarinformaciónalosprocedimientosdeVisualBasicoparaguardarlainformaciónacercadelcontrol,deformasimilaraunsegundovalordelapropiedadTag.
BeforeVariantopcional.Númeroqueindicalaposicióndelnuevocontroldebarradecomandos.Elnuevocontrolseinsertadelantedelcontrolubicadoenestaposición.Siseomiteesteargumento,elcontrolseagregaalfinaldelabarradecomandosespecificada.
TemporaryVariantopcional.Trueparaqueelnuevocontrolseatemporal.Loscontrolestemporalesseeliminanautomáticamentealcerrarlaaplicacióncontenedora.ElvalorpredeterminadoesFalse.
MétodoAddcuandoseaplicaalobjetoDocumentProperties.
Creaunanuevapropiedaddedocumentopersonalizada.SóloesposibleutilizarestemétodoconlacolecciónpersonalizadaDocumentProperties.
expresión.Add(Name,LinkToContent,Type,Value,LinkSource)
expresiónRequerida.ObjetoDocumentPropertiespersonalizado.
NameStringrequerida.Nombredelapropiedad.
LinkToContentBooleanrequerido.Especificasilapropiedadestávinculadaalcontenidodeldocumentocontenedor.SiesteargumentoesTrue,serequiereelargumentoLinkSource;siesFalse,serequiereelargumentodelvalor.
TypeVariantopcional.Tipodedatosdelapropiedad.PuedeserunadelassiguientesconstantesMsoDocProperties:msoPropertyTypeBoolean,msoPropertyTypeDate,msoPropertyTypeFloat,msoPropertyTypeNumberomsoPropertyTypeString.
ValueVariantopcional.Valordelapropiedadsinoestávinculadaalcontenidodeldocumentocontenedor.Sifueraposible,elvalorseconvierteparaquecoincidaconeltipodedatosespecificadoporelargumentodetipo;encasocontrario,seproduceunerror.SiLinkToContentesTrue,seomiteelargumentoValueylanuevapropiedaddedocumentotieneunvalorpredeterminadohasta
quelaaplicacióncontenedoraactualicelosvaloresdelapropiedadvinculada,normalmentealguardareldocumento.
LinkSourceVariantopcional.SeignorasiLinkToContentesFalse.Origendelapropiedadvinculada.Laaplicacióncontenedoradeterminalostiposdevinculacióndeorigenquesepuedenutilizar.
Comentarios
SiagregaunapropiedaddedocumentopersonalizadaalacolecciónDocumentPropertiesqueestávinculadaaunvalordadoenundocumentodeMicrosoftOffice,debeguardareldocumentoparaverelcambioenelobjetoDocumentProperty.
MétodoAddcuandoseaplicaalobjetoFileDialogFilters.
AgregaunfiltrodearchivosnuevoalalistadefiltrosdelcuadrodelistaemergenteTipodearchivodelcuadrodediálogoArchivo.DevuelveunobjetoFileDialogFilterquerepresentaelfiltrodearchivosqueseacabadeagregar.
expresión.Add(Description,Extensions,Position)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
DescriptionStringRequerida.Eltextoquerepresentaladescripcióndelaextensióndelarchivoquedeseaagregaralalistadefiltros.
ExtensionsStringRequerida.Eltextoquerepresentalaextensióndelarchivoquedeseaagregaralalistadefiltros.Sepuedeespecificarmásdeunaextensión,separadasporpuntoycoma(;).Porejemplo,elargumentoExtensionssepuedeasignaralacadena:"*.txt;*.htm".Nota:noesnecesarioagregarparéntesisalasextensiones.Officeagregaráautomáticamenteparéntesisalacadenadeextensionescuandolascadenasdelasextensionesyladescripciónesténconcatenadasenunelementodefiltrodearchivos.
PositionVariantopcional.Unnúmeroqueindicalaposicióndelcontrolnuevoenlalistadefiltros.Elfiltronuevoseinsertadelantedelfiltroubicadoenestaposición.Siseomiteesteargumento,elfiltroseagregaráalfinaldelalista.
Comentarios
Cadafiltrodeunalistaconstadedospartes:laextensióndelarchivo(p.ej..txt)yladescripcióndeltextodelaextensióndelarchivo(p.ej.Archivosdetexto).ElfiltrodearchivosapareceríaenelcuadrodelistaemergenteTipodearchivocomo:Archivosdetexto(*.txt).
Observequelosfiltrospredeterminadosnoseeliminanalagregarunfiltroalalista.
SólosemuestranlosfiltroscuandoestáactivadalaopciónWindows.
SiPositionnoesválido,semuestraunerrordetiempodeejecuciónfueradeloslímites.SilosvaloresdeDescriptionyExtensionsnosonválidos,semuestraunerrordetiempodeejecución(redistribución).
Losdiálogosdelselectordecarpetasnotienenfiltros,porlotanto,losmétodosdefiltronoseaplicanalselectordecarpetas.
MétodoAddcuandoseaplicaalobjetoScripts.
AgregaunobjetoScriptalacolecciónScriptsdeunodelosobjetossiguientes:unobjetoDocumentoRangeenMicrosoftWord;unobjetoWorksheetoChartenMicrosoftExcel;obienunobjetoSlide,SlideRange,Masterdediapositiva,oMasterdetítuloenMicrosoftPowerPoint.DevuelveunobjetoScript.
expresión.Add(Anchor,Location,Language,Id,Extended,ScriptText)
expresiónRequerida.LacolecciónScripts.
AnchorRangeopcional(sóloenMicrosoftExcel).ElargumentoAnchoraceptaunobjetoRangedeExcel,queespecifiquelacolocacióndeldelimitadordesecuenciadecomandosenunahojadeExcel.NopuedeinsertardelimitadoresdesecuenciadecomandosenlosgráficosdeExcel.
LocationMsoScriptLocationopcional.Especificalaubicacióndeldelimitadordesecuenciadecomandosenundocumento.Sihaespecificadoelargumento
Anchor,elargumentoLocationnoseutiliza,laubicacióndelargumentoAnchordeterminalaubicacióndeldelimitadordesecuenciadecomandos.
MsoScriptLocationpuedeserunadeestasconstantesdeMsoScriptLocation.msoScriptLocationInBodypredeterminadomsoScriptLocationInHead
LanguageMsoScriptLanguageopcional.Especificaellenguajedelasecuenciadecomandos.
MsoScriptLanguagepuedeserunadeestasconstantesdeMsoScriptLanguage.msoScriptLanguageASPmsoScriptLanguageJavamsoScriptLanguageOthermsoScriptLanguageVisualBasicpredeterminado
IdStringopcional.ElIDdelaetiqueta<SCRIPT>enHTML.ElargumentoIdespecificaunidentificadorSGMLutilizadoparanombrarelementos.Entrelosidentificadoresválidosseincluyecualquiercadenaquecomienceconunaletrayestéconstituidaporcaracteresalfanuméricos;lacadenatambiénpuedeincluirelcarácterdesubrayado(_).ElIDdebeserúnicodentrodeldocumentoHTML.EsteparámetroseexportacomoelatributoIDenlaetiqueta<SCRIPT>.
ExtendedStringopcional.Especificaatributosquedebenagregarsealaetiqueta<SCRIPT>(losatributosLANGUAGEeIDseexportanatravésdelosparámetrosLanguageeIdynodebenexportarseatravésdelparámetroExtended).Elformatopredeterminadoeslacadenavacía.Losatributosseseparanporespacios,aligualquesucedeenHTML.LaaplicaciónhostdeMicrosoftOfficenoproporcionaningúnmedioparacomprobarlasintaxisdelosatributospasados.
ScriptTextStringopcional.Especificaeltextocontenidoenunbloquedesecuenciasdecomandos.Elformatopredeterminadoeslacadenavacía.LaaplicaciónhostdeMicrosoftOfficecompruebalasintaxisdelasecuenciadecomandos.
Comentarios
UnaformaasociadaconunbloquedesecuenciasdecomandosnoseexportaoseimprimecomoformaenHTML;sóloseexportaelbloquedesecuenciasdecomandos.
NopuedeutilizarelmétodoAddparaagregarundelimitadordesecuenciadecomandosaunrangodediapositivasdePowerPointquecontengamásdeunadiapositiva.
MétodoAddcuandoseaplicaalobjetoSignatureSet.
DevuelveunobjetoSignaturequerepresentaunafirmadecorreoelectróniconueva.
expresión.Add
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
MétodoAddcuandoseaplicaalobjetoODSOFilters.
AgregaunfiltronuevoalacolecciónODSOFilters.
expresión.Add(Column,Comparison,Conjunction,bstrCompareTo,DeferUpdate)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
ColumnStringrequerida.Elnombredelatablaenelorigendedatos.
ComparisonMsoFilterComparisonrequerido.Cómosefiltranlosdatosdelatabla.
MsoFilterComparisonpuedeserunadeestasconstantesdeMsoFilterComparison.msoFilterComparisonContainsmsoFilterComparisonEqualmsoFilterComparisonGreaterThan
msoFilterComparisonGreaterThanEqualmsoFilterComparisonIsBlankmsoFilterComparisonIsNotBlankmsoFilterComparisonLessThanmsoFilterComparisonLessThanEqualmsoFilterComparisonNotContainsmsoFilterComparisonNotEqual
ConjunctionMsoFilterConjunctionrequerido.DeterminacómoserelacionaestefiltroconelrestodelosfiltrosdelobjetoODSOFilters.
MsoFilterConjunctionpuedeserunadeestasconstantesdeMsoFilterConjunction.msoFilterConjunctionAndmsoFilterConjunctionOr
bstrCompareToStringopcional.SielargumentoComparisonnoesmsoFilterComparisonIsBlankomsoFilterComparisonIsNotBlank,unacadenaconlaquesecomparanlosdatosdelatabla.
DeferUpdateBooleanopcional.ElvalorpredeterminadoesFalse.
MétodoAddcuandoseaplicaalobjetoAnswerWizardFiles.
Creaunareferencianueva(unvalorString)aunarchivodelAsistenteparaAyudayloagregaalacolecciónAnswerWizardFiles.
expresión.Add(FileName)
expresiónRequerida.ExpresiónquedevuelveunacolecciónAnswerWizardFiles.
FilenameStringrequerida.RutacompletaalarchivoespecificadodelAsistenteparaAyuda.
MétodoAddcuandoseaplicaalobjetoFileTypes.
Agregauntipodearchivonuevoaunabúsquedadearchivos.
expresión.Add(FileType)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
FileTypeMsoFileTyperequerido.Especificaeltipodearchivoquesebuscará.
MsoFileTypepuedeserunadeestasconstantesdeMsoFileType.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeCustommsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFilesmsoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItemmsoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPagesmsoFileTypeWordDocuments
MétodoAddcuandoseaplicaalobjetoPropertyTests.
AgregaunobjetoPropertyTestalacolecciónPropertyTests.
expresión.Add(Name,Condition,Value,SecondValue,Connector)
expresiónRequerida.ExpresiónquedevuelveunobjetoPropertyTests.
NameStringrequerida.Nombredelcriteriodelapropiedad.ElnombrecorrespondeaunvalordelcuadroPropiedaddelcuadrodediálogoBuscar,queseabredesdeelmenúHerramientasdelcuadrodediálogoAbrirdelaaplicación(menúArchivo).
ConditionMsoConditionrequerido.Condicióndeloscriteriosdebúsqueda.
MsoConditionpuedeserunadeestasconstantesdeMsoCondition.msoConditionAnyNumberBetweenmsoConditionAnytimemsoConditionAnytimeBetweenmsoConditionAtLeastmsoConditionAtMostmsoConditionBeginsWithmsoConditionDoesNotEqualmsoConditionEndsWithmsoConditionEqualsmsoConditionEqualsCompletedmsoConditionEqualsDeferredmsoConditionEqualsHighmsoConditionEqualsInProgressmsoConditionEqualsLowmsoConditionEqualsNormalmsoConditionEqualsNotStartedmsoConditionEqualsWaitingForSomeoneElsemsoConditionFileTypeAllFilesmsoConditionFileTypeBindersmsoConditionFileTypeCalendarItemmsoConditionFileTypeContactItemmsoConditionFileTypeDatabasesmsoConditionFileTypeDataConnectionFiles
msoConditionFileTypeDesignerFilesmsoConditionFileTypeDocumentImagingFilesmsoConditionFileTypeExcelWorkbooksmsoConditionFileTypeJournalItemmsoConditionFileTypeMailItemmsoConditionFileTypeNoteItemmsoConditionFileTypeOfficeFilesmsoConditionFileTypeOutlookItemsmsoConditionFileTypePhotoDrawFilesmsoConditionFileTypePowerPointPresentationsmsoConditionFileTypeProjectFilesmsoConditionFileTypePublisherFilesmsoConditionFileTypeTaskItemmsoConditionFileTypeTemplatesmsoConditionFileTypeVisioFilesmsoConditionFileTypeWebPagesmsoConditionFileTypeWordDocumentsmsoConditionFreeTextmsoConditionIncludesmsoConditionIncludesFormsOfmsoConditionIncludesNearEachOthermsoConditionIncludesPhrasemsoConditionInTheLastmsoConditionInTheNextmsoConditionIsExactlymsoConditionIsNomsoConditionIsNotmsoConditionIsYesmsoConditionLastMonthmsoConditionLastWeekmsoConditionLessThanmsoConditionMoreThanmsoConditionNextMonth
msoConditionNextWeekmsoConditionNotEqualToCompletedmsoConditionNotEqualToDeferredmsoConditionNotEqualToHighmsoConditionNotEqualToInProgressmsoConditionNotEqualToLowmsoConditionNotEqualToNormalmsoConditionNotEqualToNotStartedmsoConditionNotEqualToWaitingForSomeoneElsemsoConditionOnmsoConditionOnOrAftermsoConditionOnOrBeforemsoConditionThisMonthmsoConditionThisWeekmsoConditionTodaymsoConditionTomorrowmsoConditionYesterday
ValueVariantopcional.Valordeloscriteriosdebúsqueda.
SecondValueVariantopcional.Valorsuperiordelintervalodebúsqueda.SóloesposibleutilizaresteargumentosiConditionesmsoConditionAnyTimeBetweenomsoConditionAnyNumberBetween.
ConnectorMsoConnectoropcionalEspecificalaformaenquesecombinandoscriteriosdebúsqueda.
MsoConnectorpuedeserunadeestasconstantesdeMsoConnector.msoConnectorAndpredeterminadomsoConnectorOr
MétodoAddcuandoseaplicaalobjetoSearchFolders.
Agregaunacarpetadebúsquedaaunabúsquedadearchivos.
expresión.Add(ScopeFolder)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
ScopeFolderObjetoScopeFolderrequerido.Lacarpetaqueseagregaráalabúsqueda.
Ejemplo
CuandoseaplicaalobjetoAnswerWizardFiles.
EsteejemplopreparaelAsistenteparaAyudaparaqueacepteunalistadearchivospersonalizadosyagregadosarchivospersonalizadosdelAsistenteparaAyuda.Enprimerlugar,elejemploborralalistadearchivosy,acontinuación,agregadosarchivospersonalizadosdelAsistenteparaAyudaycompruebaelnombredelosarchivosparaasegurarsedequelosarchivossehanagregadocorrectamente.
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
CuandoseaplicaalobjetoCommandBarControls.
Esteejemplocreaunabarradeherramientaspersonalizadaquecontienenbotones(controles)paracortar,copiarypegar
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
CuandoseaplicaalobjetoDocumentProperties.
Esteejemplo,diseñadoparaejecutarloenMicrosoftWord,agregatrespropiedadespersonalizadasalacolecciónDocumentProperties.
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
CuandoseaplicaalobjetoPropertyTests.
Esteejemploagregadospruebasdepropiedadaloscriteriosdebúsqueda.LaprimeracompruebaquelosarchivosencontradosseandocumentosdeWordylasegundaquelosarchivosencontradoshayansidomodificadosentreel1deeneroyel30dejuniode1996.Elejemplotambiénmuestrauncuadrodemensajequepresentaelnúmerototaldearchivosencontrados,sihayalguno,yelnombredecadaunodeesosarchivos.
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
CuandoseaplicaalobjetoScripts.
EsteejemploagregaunnuevoScriptalahojadetrabajodellibroactivo.
DimrngScriptAnchorRangeAsRange
DimobjNewScriptAsScript
SetrngScriptAnchorRange=ActiveWorkbook._
Worksheets(1).Range("B5")
SetobjNewScript=ActiveWorkbook._
Worksheets(1).Scripts.Add(rngScriptAnchorRange,_
msoScriptLocationInBody,_
msoScriptLanguageVisualBasic,_
"MyNewScript",,_
"MsgBox(""AddedScriptobjectMyNewScript"")")
Mostrartodo
MétodoAddItem
Agregaunelementodelistaalcontroldecuadrocombinadodelabarradecomandosespecificada.Elcontroldecuadrocombinadodebeseruncontrolpersonalizadoydebeserouncuadrodelistaemergenteouncuadrocombinado.
NotaEstemétodofallarásiseaplicaauncontroldecuadrocombinadoqueseauncontroldecuadrodeediciónodecuadrocombinadointegrado.
expresión.AddItem(Text,Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarComboBox.
TextStringrequerida.Elementoquesevaaagregaralcontrolespecificado.
IndexVariantopcional.Laposicióndelelementoespecificadodelalista.Siseomiteesteargumento,elelementoseagregaalfinaldelalista.
Ejemplo
Esteejemploagregauncontroldecuadrocombinadoaunabarradecomandos.Elejemplotambiénagregadoselementosalcontrol,estableceelnúmerodeelementosdelíneayelanchodelcuadrocombinadoestablecidos.
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
MétodoAddToSearchFolders
AgregaunobjetoScopeFolderalacolecciónSearchFolders.
expresión.AddToSearchFolders
expresiónRequerida.ExpresiónquedevuelveunobjetoScopeFolder.
Comentarios
AunquepuedeutilizarelmétodoAdddelacolecciónSearchFoldersparaagregarunobjetoScopeFolderalacolecciónSearchFolders,generalmenteesmásfácilutilizarelmétodoAddToSearchFoldersdelobjetoScopeFolderquedeseeagregar,yaquesóloexisteunasolacolecciónSearchFoldersparatodaslasbúsquedas.
Ejemplo
ElejemplosiguienteagregaelobjetoScopeFolderraízalacolecciónSearchFolders.ConsulteeltemarelativoalacolecciónSearchFolderssideseaverunejemplomásextensosobrelautilizacióndelmétodoAddToSearchFolders.
Application.FileSearch.SearchScopes(1).ScopeFolder.AddToSearchFolders
MétodoApplyFilter
Aplicaunfiltroaunorigendedatosdecombinacióndecorrespondenciaparafiltrarregistrosespecíficosquecumplandeterminadoscriterios.
expresión.ApplyFilter
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemploagregaunfiltronuevoquequitatodoslosregistrosconuncampoRegiónvacíoy,acontinuación,aplicaelfiltroalapublicaciónactiva.
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
Mostrartodo
MétodoClear
Eliminatodosloselementosdelistadelcontroldecuadrocombinadodelabarradecomandosespecificada(cuadrodelistaemergenteocuadrocombinado)yborraelcuadrodetexto(cuadrodeediciónocuadrocombinado).
NotaEstemétodofallarásiseaplicaauncontroldebarradecomandosintegrado.
expresión.Clear
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarComboBox.
Ejemplo
Esteejemplocompruebaelnúmerodeelementosdelcontroldecuadrocombinadoenlabarradecomandos"Custom".Sihaymenosdetreselementosenlalistadelcuadrocombinado,elejemplolaborra,agregaunnuevoprimerelementoalalistay,acontinuación,muestraelnuevoelementocomopredeterminadoparaelcontroldecuadrocombinado.
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
MétodoClearFileList
BorralalistadearchivosdelAsistenteparaAyudaactual,incluidalalistapredeterminadadearchivosparalaaplicaciónhostdeMicrosoftOffice.
expresión.ClearFileList
expresiónExpresiónquedevuelveunobjetoAnswerWizard.
Comentarios
Utiliceestemétodoparaquitartodaslasentradasdelalistadearchivosactualrelativaalaaplicaciónespecificada.TambiénpuedeutilizarloparaasegurarsedequelosusuariosnopuedenobteneraccesoaningunodelosarchivospredeterminadosAnswerWizarddelaaplicaciónhost.Acontinuación,puedecrearunalistapersonalizadadearchivosutilizandoelmétodoAdddelacolecciónAnswerWizardFiles.
PararestablecerelconjuntopredeterminadodearchivosAnswerWizarddelaaplicaciónhost,utiliceelmétodoResetFileList.
Ejemplo
EsteejemplopreparaelAsistenteparaAyudaparaqueacepteunalistadearchivospersonalizadosy,acontinuación,añadedosarchivospersonalizados.Enprimerlugar,elejemploborralalistadearchivosy,acontinuación,añadedosarchivospersonalizadosdelAsistenteparaAyudaycompruebaelnúmerodearchivosparaasegurarsedequelosarchivossehanañadidocorrectamente.
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
MétodoClose
Cierraelglobonomodalactivo.Debeutilizarestemétodosóloenprocedimientosdedevolucióndellamada.
expresión.Close
expresiónRequerida.ExpresiónquedevuelveunobjetoBalloon.
Ejemplo
Esteejemplomuestraungloboquecontieneunbotónporcadatresimpresoras.Siemprequeelusuariohagaclicenunodeesostresbotones,elprocedimientodedevolucióndellamadaProcessPrinterseejecutayelglobosecierra.
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
MétodoCommit
GuardatodosloscambiosdelacolecciónSignatureSetespecificadaendisco.LoscambiosdelacolecciónSignatureSetnoseguardaránhastaqueelmétodoCommitseejecute.
expresión.Commit
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentoenWordyejecuteestafunción.Lafunciónrealizarálacomprobaciónparaasegurarsedequelafirmadigitalqueelusuarioseleccionanocaducaantesdelos12meses.Sicaduca,noseadjuntaráelcertificado.
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
Mostrartodo
MétodoCopy
Copiaelcontroldebarradecomandosespecificadoenunabarradecomandosexistente.
expresión.Copy(Bar,Before)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarControl,CommandBarButton,CommandBarPopupoCommandBarComboBox.
BarVariantopcional.UnobjetoCommandBarquerepresentalabarradecomandosdedestino.Siseomiteesteargumento,elcontrolsecopiaenlamismabarradecomandos,esdecir,labarradecomandosenlaqueyaestabaubicada.
BeforeVariantopcional.Númeroqueindicalaposicióndelnuevocontrolenlabarradecomandosespecificada.Elnuevocontrolseinsertadelantedelcontrolubicadoenestaposición.Siseomiteesteargumento,elcontrolsecopiaalfinaldelabarradecomandos.
Ejemplo
Esteejemplocopiaelprimercontroldelabarradecomandosdenominada"Standard"enlabarradecomandos"Custom"ylocolocaenprimerlugar.
SetmyCustomBar=CommandBars("Custom")
SetmyControl=CommandBars("Standard").Controls(1)
WithmyControl
.CopyBar:=myCustomBar,Before:=1
.SetFocus
EndWith
Mostrartodo
MétodoCopyFace
CopiaenelPortapapeleslaimagendelcontroldebotóndelabarradecomandosespecificada.
expresión.CopyFace
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarButton.
Comentarios
UtiliceelmétodoPasteFaceparapegarelcontenidodelPortapapelesenunaimagendebotón.
Ejemplo
EsteejemplobuscaelbotónAbririntegrado,copiasuimagenenelPortapapelesy,acontinuación,pegalaimagenenelbotónOrtografíaygramática.
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=23)
myControl.CopyFace
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,ID:=2)
myControl.PasteFace
Mostrartodo
MétodoDelete
MétodoDeletecuandoseaplicaalobjetoDocumentProperty.
Eliminaunapropiedaddedocumentopersonalizada.
expresión.Delete
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Comentarios
Noesposibleeliminarunapropiedaddedocumentointegrada.
MétodoDeletecuandoseaplicaalobjetoAnswerWizardFiles.
Eliminaelobjetoespecificadodelacolecciónquelocontiene.
expresión.Delete(FileName)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
FilenameStringrequerida.Elnombredelarchivoquesevaaeliminar,incluyendolarutadeaccesocompleta,elnombredelarchivoylaextensión.
MétodoDeletecuandoseaplicaalobjetoFileDialogFilters.
Eliminaunfiltrodediálogosdearchivos.
expresión.Delete(filter)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
filterVariantopcional.Elfiltroqueseeliminará.
MétodoDeletecuandoseaplicaalobjetoODSOFilters.
EliminaunfiltrodeobjetosdelacolecciónODSOFilters.
expresión.Delete(Index,DeferUpdate)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.Elnúmerodelfiltroqueseeliminará.
DeferUpdateBooleanopcional.
MétodoDeletecuandoseaplicaalosobjetosCommandBar,Script,ScriptsySignature.
Eliminaelobjetoespecificadodelacolección.
expresión.Delete
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Comentarios
EnlacolecciónScripts,alutilizarelmétodoDeletesequitantodaslassecuenciadecomandosdeldocumentodeWordespecificado,delahojadecálculodeExcelodeladiapositivadePowerPoint.Undelimitadordeunasecuenciadecomandosestárepresentadoporunaformaenlaaplicaciónhost.Porconsiguiente,elobjetoShapeasociadoacadadelimitadordesecuenciadecomandosdeltipomsoScriptAnchor,seeliminadesdelacolecciónShapesenExcelyPowerPoint,ydesdelascoleccionesInlineShapesyShapesenWord.
MétodoDeletecuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
Eliminaelobjetoespecificadodelacolecciónquelocontiene.
expresión.Delete(Temporary)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
TemporaryVariantopcional.Trueparaeliminarelcontrolenlasesiónactual.Laaplicaciónmostrarádenuevoelcontrolenlasiguientesesión.
Ejemplo
CuandoseaplicaalobjetoCommandBar.
Esteejemploeliminatodaslasbarrasdecomandospersonalizadasnovisibles.
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
CuandoseaplicaalobjetoDocumentProperty.
Esteejemploeliminaunapropiedaddedocumentopersonalizada.DebepasarseelobjetoDocumentPropertypersonalizadoalprocedimiento.
ActiveDocument.CustomDocumentProperties("CustomNumber").Delete
Mostrartodo
MétodoDoAlert
MuestraunaalertaydevuelveunvalorLongqueindicaquébotónhapresionadoelusuario.PuedemostrarlaalertamedianteelAyudantedeMicrosoftOfficeocomouncuadrodemensajenormal.
expresión.DoAlert(bstrAlertTitle,bstrAlertText,alb,alc,ald,alq,varfSysAlert)
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
bstrAlertTitleStringrequerida.Estableceeltítulodelaalerta.
bstrAlertTextStringrequerida.Estableceeltextodelaalerta.
albMsoAlertButtonTyperequerido.Determinaquébotonessemostraránenlaalerta.
MsoAlertButtonTypepuedeserunadeestasconstantesdeMsoAlertButtonType.msoAlertButtonAbortRetryIgnoremsoAlertButtonOKmsoAlertButtonOKCancelmsoAlertButtonRetryCancelmsoAlertButtonYesAllNoCancelUtilícelosólosielargumentovarfSysAlertestáestablecidoaFalse.msoAlertButtonYesNomsoAlertButtonYesNoCancel
alcMsoAlertIconTyperequerido.Determinaeliconoqueapareceenlaalerta.
MsoAlertIconTypepuedeserunadeestasconstantesdeMsoAlertIconType.msoAlertIconCritical
msoAlertIconInfomsoAlertIconNoIconmsoAlertIconQuerymsoAlertIconWarning
aldMsoAlertDefaultTyperequerido.Determinaquébotónestáestablecidocomoelpredeterminadodelaalerta.Siesteargumentoestáestablecidoaunvalorsuperioralnúmerodebotones,devolveráunerror.
MsoAlertDefaultTypepuedeserunadeestasconstantesdeMsoAlertDefaultType.msoAlertDefaultFifthmsoAlertDefaultFirstmsoAlertDefaultFourthmsoAlertDefaultSecondmsoAlertDefaultThird
alqMsoAlertCancelTyperequerido.SedebeestablecersiempreamsoAlertCancelDefault.Cualquierotraconfiguraciónpuededevolverunerror.
MsoAlertCancelTypepuedeserunadeestasconstantesdeMsoAlertCancelType.msoAlertCancelDefaultmsoAlertCancelFifthmsoAlertCancelFirstmsoAlertCancelFourthmsoAlertCancelSecondmsoAlertCancelThird
varfSysAlertBooleanrequerido.TruesilaalertasemuestraenuncuadrodemensajeoFalsesisemuestraenelAyudantedeOffice.
Comentarios
LosvaloresdevueltosdelmétodoDoAlertcorrespondenalosvaloresdeltipovbMsgBoxResultenumerado(porejemplo,vbYes,vbNoovbCancel).Ademásdeestosvalores,tambiénsepuedendevolverlossiguientes:
"Yestoall"=8"Tryagain"=10"Continue"=11
Ejemplo
ElejemplosiguientemuestraunaalertamedianteelAyudantedeOfficeyuncuadrodemensajequeindicaquébotónhapresionadoelusuario.Sielayudanteestádeshabilitado,laalertasemostraráenuncuadrodemensajenormal.
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
MétodoEndWizard
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
CierralaventanadelAyudantedeOfficeysueltalavariablequeidentificademaneraúnicalasesióndelAsistente.
NotaDebeutilizarestemétodosóloparacompletarelprocesoiniciadoconelmétodoStartWizard.
expresión.EndWizard(WizardID,varfSuccess,Animation)
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
WizardIDLongrequerido.NúmeroúnicoqueidentificalasesióndelAsistenteparaelAyudantedeOffice,devueltoporelmétodoStartWizard.
varfSuccessBooleanrequerido.Alvolverelmétodo,esteargumentoesTruesielusuariofinalizócorrectamenteelAsistente.
AnimationVariantopcional.LaanimacióndelAyudantedeOfficeserealizasivarfSuccessseestableceenTrue.ElvalorpredeterminadoesmsoAnimationCharacterSuccessMajor.
Ejemplo
EsteejemplocierraunasesióndelAsistenteparaelAyudantedeOfficequeelusuariohayafinalizadocorrectamente.LavariableIHelpForWizsehaestablecidoenelvalordevueltoporelmétodoStartWizard.
Assistant.EndWizardWizardId:=lHelpForWiz,_
varfSuccess:=True,Animation:=msoAnimationGoodbye
Mostrartodo
MétodoExecute
MétodoExecutecuandoseaplicaalobjetoFileSearch.
Comienzalabúsquedadelosarchivosespecificados.DevuelveunvalorLong;cero(0)sinosehaencontradoningúnarchivoounnúmeropositivosihaencontradounoovariosarchivos.
expresión.Execute(SortBy,SortOrder,AlwaysAccurate)
expresiónRequerida.ExpresiónquedevuelveunobjetoFileSearch.
SortByMsoSortByopcional.Métodoutilizadoparaclasificarlosarchivosdevueltos.
MsoSortBypuedeserunadeestasconstantesdeMsoSortBy.msoSortByFileNamepredeterminadomsoSortByFileTypemsoSortByLastModifiedmsoSortByNonemsoSortBySize
SortOrderMsoSortOrderopcional.Ordenenqueseclasificanlosarchivosdevueltos.
MsoSortOrderpuedeserunadeestasconstantesdeMsoSortOrder.msoSortOrderAscendingpredeterminadomsoSortOrderDescending
AlwaysAccurateBooleanopcional.Trueparaquelabúsquedaincluyaarchivosquehayansidoagregados,modificadosoeliminadosdesdequeseactualizóporúltimavezelíndice.ElvalorpredeterminadoesTrue.
MétodoExecutecuandoseaplicaalosobjetosCommandBarButton,
CommandBarComboBox,CommandBarControl,CommandBarPopupyFileDialog.
Paralosobjetosdelabarradecomandos,ejecutaelprocedimientoocomandointegradoasignadoalcontroldebarradecomandosespecificado.Paracontrolespersonalizados,utilicelapropiedadOnActionparaespecificarelprocedimientoquedeseaejecutar.
ParaobjetosFileDialogdetipomsoFileDialogOpenomsoFileDialogSaveAs,llevaacabolaaccióndelusuariojustodespuésdellamaralmétodoShow.
expresión.Execute
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Ejemplo
CuandoseaplicaalobjetoFileSearch.
EsteejemplobuscatodoslosarchivosenlacarpetaMyDocumentsqueterminanconlaextensióndearchivo".doc"y,acontinuación,muestralaubicaciónyelnombredecadaarchivoencontrado.Elejemploordenatambiénlalistadelosnombresdearchivosdevueltosenordenalfabéticoascendente.
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
CuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
EsteejemplodeMicrosoftExcelcreaunabarradecomandosydespuésagregauncontroldebotóndebarradecomandosintegradoaesabarra.ElbotónejecutalafuncióndeExcelAutosuma.EsteejemploutilizaelmétodoExecuteparasumarelrangodeceldasseleccionadocuandoaparecelabarradecomandos.
DimcbrCustBarAsCommandBar
DimctlAutoSumAsCommandBarButton
SetcbrCustBar=CommandBars.Add("Custom")
SetctlAutoSum=cbrCustBar.Controls_
.Add(msoControlButton,CommandBars("Standard")_
.Controls("AutoSum").Id)
cbrCustBar.Visible=True
ctlAutoSum.Execute
MétodoFindControl
DevuelveunobjetoCommandBarControlquecumpleloscriteriosespecificados.
expresión.FindControl(Type,Id,Tag,Visible,Recursive)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBars.
TypeMsoControlTypeopcional.Tipodecontrol.
MsoControlTypepuedeserunadeestasconstantesdeMsoControlType.msoControlActiveXmsoControlCustommsoControlButtonmsoControlEditmsoControlDropdownmsoControlComboBoxmsoControlButtonDropdownmsoControlSplitDropdownmsoControlGenericDropdownmsoControlGraphicCombomsoControlSplitButtonMRUPopupmsoControlSplitExpandingGridmsoControlGraphicDropdownmsoControlPopupmsoControlGraphicPopupmsoControlButtonPopupmsoControlGaugemsoControlLabelmsoControlExpandingGrid
msoControlGridmsoControlOCXDropDownmsoControlSplitButtonPopupmsoControlPane
IdVariantopcional.Identificadordelcontrolquesevaabuscar.
TagVariantopcional.Elvalorderótulodelcontrolquesevaabuscar.
VisibleVariantopcional.Trueparaincluirsólocontrolesdebarradecomandosvisiblesenlabúsqueda.ElvalorpredeterminadoesFalse.LasbarrasdecomandosvisiblesincluyentodaslasbarrasdeherramientasvisiblesycualquiermenúqueseabraalavezqueseejecutaelmétodoFindControl.
RecursiveBooleanopcional.Trueparaincluirenlabúsquedalabarradecomandosytodaslassubbarrasdeherramientasemergentes.EsteargumentosóloseaplicaalobjetoCommandBar.ElvalorpredeterminadoesFalse.
Comentarios
SilacolecciónCommandBarscontienedosomáscontrolesquecumplenloscriteriosdebúsqueda,FindControldevuelveelprimercontrolencontrado.Sinoseencuentraningúncontrolquecumplaloscriterios,FindControldevuelveNothing.
Ejemplo
Esteejemploencuentraelprimercontroldelabarradecomandosdenominada"Custom".Sielcontrolesunbotón,elejemploutilizaelmétodoFindControlparabuscarelbotónCopy(enlabarradeherramientasStandard)y,acontinuación,copiarlaimagendelbotónCopyypegarlaenelcontrol.
SetoldCtrl=CommandBars("Custom").Controls(1)
IfoldCtrl.Type=1Then
SetnewCtrl=CommandBars.FindControl(Type:=_
MsoControlButton,ID:=_
CommandBars("Standard").Controls("Copy").ID)
NewCtrl.CopyFace
OldCtrl.PasteFace
EndIf
MétodoFindControls
DevuelvelacolecciónCommandBarControlsquecumpleloscriteriosespecificados.
expresión.FindControls(Type,Id,Tag,Visible)
expresiónRequerida.ExpresiónquedevuelveunacolecciónCommandBarControls.
TypeMsoControlTypeopcional.Tipodecontrol.
MsoControlTypepuedeserunadeestasconstantesdeMsoControlType.msoControlActiveXmsoControlCustommsoControlButtonmsoControlEditmsoControlDropdownmsoControlComboBoxmsoControlButtonDropdownmsoControlSplitDropdownmsoControlGenericDropdownmsoControlGraphicCombomsoControlSplitButtonMRUPopupmsoControlSplitExpandingGridmsoControlGraphicDropdownmsoControlPopupmsoControlGraphicPopupmsoControlButtonPopupmsoControlGaugemsoControlLabel
msoControlExpandingGridmsoControlGridmsoControlOCXDropDownmsoControlSplitButtonPopupmsoControlPaneIdVariantopcional.Identificadordelcontrolquesevaabuscar.
TagVariantopcional.Elvalordelrótulodecontrolquesevaabuscar.
VisibleVariantopcional.Trueparaincluirsólocontrolesdebarradecomandosvisiblesenlabúsqueda.ElvalorpredeterminadoesFalse.
Comentarios
Sinoseencuentraningúncontrolquecumplaloscriterios,elmétodoFindControlsdevuelveNothing.
Ejemplo
EsteejemploutilizaelmétodoFindControlsparadevolvertodoslosmiembrosdelacolecciónCommandBarsquetenganunId.iguala18ymuestraenuncuadrodemensajeelnúmerodecontrolesquecumplenloscriteriosdebúsqueda.
DimmyControlsAsCommandBarControls
SetmyControls=CommandBars.FindControls(Type:=msoControlButton,ID:=18)
MsgBox"Thereare"&myControls.Count&_
"controlsthatmeetthesearchcriteria."
MétodoHelp
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
MuestraelAyudantedeOfficeyelglobointegradodelAyudante"¿Quédeseahacer?"delaAyudaenpantallaestándardeOffice.
expresión.Help
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
Ejemplo
ElejemplomuestraelglobointegradodelAyudantequelepreguntaquémásdeseahacercuandoelusuarioactivalacasilladeverificación"Ineedmoreinformation"(Serequieremásinformación).
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
Mostrartodo
MétodoItem
MétodoItemcuandoseaplicaalobjetoCOMAddIns.
DevuelveunmiembrodelacolecciónCOMAddInsespecificada.
expresión.Item(Index)
expresiónRequerida.LacolecciónCOMAddInsespecificada.
IndexVariantrequerido.PuedeutilizarunvalorordinalquedevuelvaelcomplementoCOMadichaposiciónenlacolecciónCOMAddIns,obien,unvalorStringquerepresenteelProgIDdelcomplementoCOMespecificado.
MétodoItemcuandoseaplicaalobjetoFileDialogFilters.
DevuelveunobjetoFileDialogFilterqueesmiembrodelacolecciónFileDialogFiltersespecificada.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.NúmerodeíndicedelobjetoFileDialogFilterquesevaadevolver.
MétodoItemcuandoseaplicaalobjetoHTMLProjectItems.
DevuelveelobjetoHTMLProjectItemquerepresentaunproyectoespecíficoenelEditordesecuenciadecomandosdeMicrosoft.
expresión.Item(Index)
expresiónRequerida.UnacolecciónHTMLProjectItems.
IndexVariantrequerido.Nombreonúmerodeíndicedelelementodel
proyectoHTMLquedebedevolverse.
MétodoItemcuandoseaplicaalobjetoScripts.
DevuelveunmiembrodelacolecciónScripts.AceptaelnúmerodeíndiceoelIDdelasecuenciadecomandosquedeseaquedevuelvalaaplicacióndeMicrosoftOffice.ElmétodoItemaceptaunvalorVariantquepuedeaceptarunnúmeroordinal(valoríndice),elcualdevuelvelasecuenciadecomandosalmacenadaendichaposiciónenlacolecciónScriptsopuedeaceptarunvalorStringquerepresenteelnombreoelIDdelasecuenciadecomandos.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoScripts.
IndexVariantrequerido.ElIDoelnúmerodeíndicedelasecuenciadecomandosquedebedevolverse.
Comentarios
LacolecciónScriptscontienetodaslassecuenciasdecomandosdeundocumentoconcretoenelordenoriginal(elordenenelquelosobjetosScriptaparecenenelarchivodeorigen).Lassecuenciasdecomandossemantienenenelordenoriginalindependientementedesuubicacióneneldocumento,esdecir,sintenerencuentasiestánenelencabezadooeneltextoindependiente.
PuedeutilizarelmétodoItemparaobteneraccesoaunasecuenciadecomandosdelacolecciónScriptsmedianteelIDdelaetiqueta<SCRIPT>.ElatributoIDdelaetiqueta<SCRIPT>esidénticoalapropiedadIddelobjetoScript.SihayIDduplicadosomúltipleseneldocumentoyutilizalapropiedadIddeunobjetoScriptparaobteneraccesoaunasecuenciadecomandosmedianteelmétodoItem,OfficedevolverálaprimerasecuenciadecomandosquecoincidaconelID;seomitiránlasdemássecuenciasdecomandosconelmismoID.
LosnuevosdelimitadoresdesecuenciadecomandosqueseagreguenalacolecciónseincluiránalfinaldelacolecciónScriptsenelordenenelqueseagregaronaldocumento.LosdelimitadoresdesecuenciadecomandospermaneceránenesteordenhastaqueeldocumentoseguardecomoHTML,secierreysevuelvaaabrirenlaaplicaciónhost.Sisigueestospasos,lacolecciónScriptsseindizaráenelordenenelquelosdelimitadoresdesecuenciadecomandosapareceneneldocumento,loquepuedediferirdelordenenelqueseagregaron.Porlotanto,esconvenientequeutilicelapropiedadIddelobjetoScriptenlugardelaposicióndelasecuenciadecomandosenlacolección,puesdeestemodo,seasegurarádequeidentificalasecuenciadecomandosconseguridad.
MétodoItemcuandoseaplicaalobjetoFileDialogSelectedItems.
DevuelveunvalorStringquecorrespondealarutadeaccesoaunodelosarchivosqueelusuariohaseleccionadoenuncuadrodediálogodearchivosmostradomedianteelmétodoShowdelobjetoFileDialog.LacolecciónFileDialogSelectedItemsesunacoleccióndecadenas.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.Númerodeíndicedelacadenaquesevaadevolver.
MétodoLoadFromFile
ActualizaeltextoenelEditordesecuenciasdecomandosdeMicrosoftcontextodelarchivoespecificado(eneldisco).
expresión.LoadFromFile(Filename)
expresiónUnobjetoHTMLProjectItem.
FilenameStringrequerida.Larutacompletadelarchivodetextoquecontieneeltextoquedebecargarse.
Ejemplo
EsteejemplodeterminasielelementoHTMLespecificadoestáabierto;sielelementoestáabierto,elejemplocargarálasecuenciadecomandosdesdeelarchivoespecificado.
IfActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).IsOpenThen
ActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).LoadFromFile("C:\MyScript.txt")
Else
MsgBox"TheHTMLProjectItemisnotopen."
EndIf
Mostrartodo
MétodoMove
Puedequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
MétodoMovecuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
Mueveelcontroldelabarradecomandosespecificadoaunabarradecomandosexistente.
expresión.Move(Bar,Before)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
BarVariantopcional.ObjetoCommandBarquerepresentalabarradecomandosdedestinodelcontrol.Siseomiteesteargumento,elcontrolsemuevealfinaldelabarradecomandosenqueseencuentraactualmente.
BeforeVariantopcional.Númeroqueindicalaposicióndelcontrol.Elcontrolseinsertaantesdelcontrolqueocupaactualmenteestaposición.Siseomiteesteargumento,elcontrolseinsertaenlamismabarradecomandos.
MétodoMovecuandoseaplicaalobjetoAssistant.
MueveelAyudantedeOfficealaubicaciónespecificada.
expresión.Move(xLeft,yTop)
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
xLeftIntegerRequerido.Posiciónizquierda,enpuntos,delaventanadelAyudantedeOffice.
yTopIntegerRequerido.Posiciónsuperior,enpuntos,delaventanadelAyudantedeOffice.
Ejemplo
MétodoMovecuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControl,yCommandBarPopup.
EsteejemplomueveelprimercontroldecuadrocombinadodesdelabarradecomandospersonalizadadenominadaCustomalaposiciónanterioralséptimocontroldedichabarra.Elejemploestablecelaetiqueta"Selectionbox"yasignaunaprioridadbajaalcontrolparaqueseeliminedelabarradecomandossinoseajustantodosloscontrolesaunafila.
Setallcontrols=CommandBars("Custom").Controls
ForEachctrlInallControls
Ifctrl.Type=msoControlComboBoxThen
Withctrl
.MoveBefore:=7
.Tag="Selectionbox"
.Priority=5
EndWith
ExitFor
EndIf
Next
MétodoMovecuandoseaplicaalobjetoAssistant.
EsteejemplomuestraelAyudantedeOfficeenlaubicaciónespecificadayestablecevariasopcionesantesdemostrarlo.
WithAssistant
.Reduced=True
.MovexLeft:=400,yTop:=300
.MoveWhenInTheWay=True
.TipOfDay=True
.Visible=True
.Animation=msoAnimationGreeting
EndWith
MétodoNewSearch
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Restablecelosvalorespredeterminadosdetodosloscriteriosdebúsqueda.
expresión.NewSearch
expresiónRequerida.ExpresiónquedevuelveunobjetoFileSearch.
Comentarios
Losvaloresdeloscriteriosdebúsquedasemantienenduranteunasesióndelaaplicación.Utiliceestemétodocadavezquecambieloscriteriosdebúsqueda.EstemétodonorestableceelvalordelapropiedadLookIn.
Ejemplo
EsteejemploutilizaelmétodoNewSearchpararestablecerloscriteriosdebúsquedapredeterminadosantesdecomenzarunanuevabúsqueda.
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
Mostrartodo
MétodoOpen
AbreelproyectoHTMLespecificadooelelementodelproyectoHTMLenelEditordesecuenciasdecomandosdeMicrosoftenunadelasvistasqueespecificanlasconstantesopcionalesMsoHTMLProjectOpenquefiguranacontinuación.Sinoseespecificaunadelasconstantes,elelementodelproyectoseabriráenlavistapredeterminada.
expresión.Open(OpenKind)
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
OpenKindMsoHTMLProjectOpenopcional.Vistaenlaqueseabreelproyectooelelementodeproyectoespecificado.
MsoHTMLProjectOpenpuedeserunadeestasconstantesdeMsoHTMLProjectOpen.msoHTMLProjectOpenSourceViewmsoHTMLProjectOpenTextView
Comentarios
LavistapredeterminadaseestableceenfuncióndesiestáabiertoonoelEditordesecuenciasdecomandosdeMicrosoftcuandoseejecutaelmétodoOpen.SielEditordesecuenciasdecomandosnoestáabierto,elmétodoOpeniniciaráelEditordesecuenciasdecomandosenlavistaoriginal.SielEditordesecuenciasdecomandosyaestáabierto,elmétodoOpenactivaráelEditordesecuenciasdecomandosymostrarálasecuenciadecomandosenlavistaactual.
Ejemplo
EsteejemploabreelproyectoHTMLenellibroactivoenlavistaoriginal.
AppActiveWorkbook.HTMLProject.Open_
(msoHTMLProjectOpenSourceView)
EsteejemploabreelprimerelementodelproyectoHTMLdellibroactivoenvistadetexto.
ActiveWorkbook.HTMLProject.HTMLProjectItems_
Item(1).Open(msoHTMLProjectOpenTextView)
Mostrartodo
MétodoPasteFace
PegaelcontenidodelPortapapelesenelcontroldebotóndelabarradecomandosespecificada.
expresión.PasteFace
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarButton.
Ejemplo
EsteejemplobuscaelbotónintegradoFileOpenypegalaimagendesdeelbotónOrtografíaygramáticaenéldesdeelPortapapeles.
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=2)
myControl.CopyFace
SetmyControl=CommandBars.FindControl(Type:=msoControlButton,Id:=23)
myControl.PasteFace
MétodoRefreshDocument
ActualizaelproyectoHTMLenlaaplicaciónhostdeMicrosoftOffice.
expresión.RefreshDocument(Refresh)
expresiónExpresiónquedevuelveunobjetoHTMLProject.
RefreshBooleanrequerido.Truesidebenguardarsetodosloscambios;Falsesidebenomitirsetodosloscambios.
Comentarios
LautilizacióndeestemétodoesequivalenteahacerclicenelbotónActualizardelabarradeherramientasActualizarenlaaplicaciónhostdeOffice.SiactualizaeldocumentoestableciendoelmétodoRefreshDocumentenTrue,todosloscambiosrealizadosenelcódigoHTMLconelEditordesecuenciasdecomandosseguardaránenlaaplicaciónhostdeOffice.SiestableceRefreshDocumentenFalse,sepasaránporaltotodosloscambiosrealizadosenelcódigoHTML.TengaencuentaqueelvalordevueltoporelmétodoStateseveafectadoporelmétodoRefreshDocument.SiactivaRefreshDocument(True),elmétodoStatedevolverámsoHTMLProjectStateDocumentProjectUnlockedsiseactivadespuésdelaoperacióndeactualización.
Ejemplo
EsteejemploactualizaelproyectoHTMLdellibroactivoenlaaplicaciónhost.
ActiveWorkbook.HTMLProject.RefreshDocument(True)
MétodoRefreshProject
ActualizaelproyectoHTMLespecificadoenelEditordesecuenciasdecomandosdeMicrosoft.
expresión.RefreshProject
expresiónExpresiónquedevuelveunobjetoHTMLProject.
Comentarios
LautilizacióndeestemétodoesequivalenteahacerclicenelbotónActualizardelabarradeherramientasActualizardelEditordesecuenciasdecomandosdeMicrosoft.SiactualizaeldocumentoestableciendoRefreshDocumentenTrue,todosloscambiosefectuadosenelcódigoHTMLenlaaplicaciónhostdeOfficeseguardaránenelproyectoHTMLenelEditordesecuenciasdecomandosdeMicrosoft.SiestableceRefreshDocumentenFalse,sepasaránporaltotodosloscambiosrealizadosenelcódigoHTML.
Ejemplo
EsteejemploactualizaelproyectoHTMLenelEditordesecuenciasdecomandosdeMicrosoft.
ActiveWorkbook.HTMLProject.RefreshProject(True)
MétodoRefreshScopes
ActualizalalistadeobjetosScopeFolderdisponiblesactualmente.
expresión.RefreshScopes
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestratodoslosobjetosScopeFolderdisponiblesactualmenteenlaunidadC:\delámbitodeMiPC.
SubTestRefreshScopesMethod()
'DisplayswhathappensbeforeandaftertheRefreshScopes
'methodiscalledwhenanewfolderisaddedtothelist
'ofscopefolders.
'Listbeforethefolderiscreated.
CallListFolderNames
'CreateanewfolderontheC:\driveinMyComputer.
'Anerrorwilloccurifthisfolderalreadyexists.
MkDirPath:="C:\Delete_After_Using"
'Listafterthefolderiscreated.
CallListFolderNames
'Refreshthelistoffolders.
Application.FileSearch.RefreshScopes
'Thenewly-createdfoldernowappearsinthelist.
CallListFolderNames
EndSub
SubListFolderNames()
DimstrResultsAsString
'LoopthroughallthefoldernamesontheC:\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
Mostrartodo
MétodoReleaseFocus
Liberaelfocodelainterfazdeusuariodetodaslasbarrasdecomandos.
expresión.ReleaseFocus
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBars.
Ejemplo
Esteejemploagregatresbotonesenblancoalabarradecomandosdenominada"Custom"yestableceelfocoenelcentrodelbotón.Acontinuación,elbotónesperacincosegundosantesdeliberarelfocodelainterfazdeusuariodesdetodaslasbarrasdecomandos.
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
Mostrartodo
MétodoRemove
MétodoRemovecuandoseaplicaalobjetoNewFile.
QuitaunelementodelpaneldetareasNuevoelemento.DevuelveunvalorBoolean.
expresión.Remove(FileName,Section,DisplayName,Action)
expresiónRequerida.ExpresiónquedevuelveunobjetoNewFile.
FilenameStringrequerida.Nombredelareferenciaaarchivo.
SectionVariantopcional.Laseccióndelpaneldetareasenqueseencuentralareferenciaaarchivo.PuedesercualquierconstantemsoFileNewSection.
DisplayNameVariantopcional.Textodelareferenciaaarchivo.
ActionVariantopcional.Laacciónqueseejecutacuandoelusuariohaceclicenelelemento.PuedesercualquierconstantemsoFileNewSection.
MétodoRemovecuandoseaplicaalosobjetosFileTypes,PropertyTestsySearchFolders.
Quitaelobjetoespecificadodelacolección.
expresión.Remove(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.Númerodeíndicedelapruebadepropiedadquesevaaeliminar.
Ejemplo
CuandoseaplicaalosobjetosFileTypes,PropertyTestsySearchFolders.
Esteejemploeliminaelprimercriteriodebúsquedadelacolección.
Application.FileSearch.PropertyTests.Remove(1)
CuandoseaplicaalobjetoNewFile.
EsteejemploquitaelelementoespecificadodelpaneldetareasNewDocumentdeWord.
SubRemoveDocFromTaskPane()
Application.NewDocument.RemoveFileName:="C:\Newfile.doc",_
Section:=msoNewfromTemplate,DisplayName:="NewFile"
CommandBars("TaskPane").Visible=True
EndSub
Mostrartodo
MétodoRemoveItem
Eliminaunelementodelistadelcontroldecuadrocombinadodelabarradecomandosespecificada.
NotaEstapropiedadfallacuandoseaplicaacontrolesquenoseancontrolesdelista.
expresión.RemoveItem(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarComboBox.
IndexLongrequerido.Elementoquesevaaeliminardelalista.
Ejemplo
Esteejemplodeterminasihaymásdetreselementosenelcuadrocombinadoespecificado.Sihaymásdetreselementos,elejemploquitaelsegundoelemento,alteraelestiloparaquenomuestreelrótulodelcuadrocombinadoyestableceunnuevovalor.TambiénestablecelapropiedadTagdelobjetomaestro,objetoCommandBarControl,paraquemuestrequelalistahacambiado.
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
Mostrartodo
MétodoReset
Restablecelabarradecomandosintegradaespecificadaasuconfiguraciónpredeterminadaorestableceelcontroldebarradecomandosasufuncióneimagenpredeterminadas.
expresión.Reset
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBar,CommandBarControl,CommandBarButton,CommandBarPopupoCommandBarComboBox.
Comentarios
Alrestableceruncontrolintegradoserestablecensusaccionesoriginalesytodaslaspropiedadesasuestadooriginal.Alrestablecerunabarradecomandosintegradaseeliminanloscontrolespersonalizadosyserestablecenloscontrolesintegrados.
Ejemplo
Esteejemploutilizaelvalordeuserparaajustarlasbarrasdecomandodeacuerdoconelniveldeusuario.Siuseres"Level1,"semuestralabarradecomandosdenominada"Custom".Siuserescualquierotrovalor,labarradecomandosintegradadeVisualBasicserestableceasuestadopredeterminadoysedeshabilitalabarradecomandosdenominada"Custom".
SetmyBar=CommandBars("Custom")
Ifuser="Level1"Then
myBar.Visible=True
Else
CommandBars("VisualBasic").Reset
myBar.Enabled=False
EndIf
MétodoResetFileList
RestablecelalistadearchivosdelAsistenteparaAyudaactualalalistadearchivosdelaaplicaciónhostdeMicrosoftOffice.
expresión.ResetFileList
expresiónExpresiónquedevuelveunobjetoAnswerWizard.
Comentarios
UtiliceestemétodopararestablecertodaslasentradasdelalistaactualdearchivosdelAsistenteparaAyudaalalistadelregistrodeWindowsdelaaplicaciónhost.Puedeestablecerunalistadearchivospredeterminadaañadiendolosnombresdelosarchivospersonalizadosalaclavederegistroadecuada.
Ejemplo
EsteejemplorestablecelalistadearchivosdelAsistenteparaAyudaactualy,acontinuación,muestraelnúmerodearchivosylosnombresdelosarchivosenuncuadrodemensaje.
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
MétodoResetTips
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
RestablecelassugerenciasdelaaplicaciónqueapareceránenelglobodelAyudantedeOffice.
expresión.ResetTips
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
Comentarios
ElmétodoResetTipscorrespondealbotónRestablecermissugerenciasdelafichaOpciones,enelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemplorestablecelassugerenciasdelaaplicaciónantesdemostrarelAyudantedeOffice.Apareceráunglobodeconfirmaciónindicandoalusuarioquesehanrestablecidolassugerenciasdelaaplicación.
WithApplication.Assistant
.On=True
.Visible=True
.Animation=msoAnimationGreeting
.ResetTips
EndWith
MétodoSaveCopyAs
GuardaelproyectoHTMLespecificadoconunnuevonombredearchivo.
expresión.SaveCopyAs(Filename)
expresiónUnobjetoHTMLProjectItem.
FilenameStringrequerida.RutacompletadelarchivoenelquedeseaguardarelelementodelproyectoHTML.
Ejemplo
EsteejemploguardaunacopiadeltextodelelementodelproyectoHTMLactualenelarchivoNewScript.txt.
ActiveWorkbook.HTMLProject.HTMLProjectItems._
Item(1).SaveCopyAs("C:\NewScript.txt")
MétodoSetAvoidRectangle
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
EvitaquesemuestreelglobodelAyudantedeOfficeenunáreaespecíficadelapantalla.
expresión.SetAvoidRectangle(Left,Top,Right,Bottom)
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
Left,Top,Right,BottomLongrequerido.Coordenadas,enpuntosyconrelaciónalapantalla,deláreadelapantalladondenosemostraráelglobodelAyudantedeOffice.
Comentarios
EstapropiedadevitaqueelglobodelAyudantedeOfficesesuperpongaaloscuadrosdediálogoyAsistentespersonalizados.
Ejemplo
EsteejemploevitaqueelglobodelAyudantedeOfficerepresentadoporlavariablemyBalloonsemuestreeneláreadelapantalladefinidaporlascoordenadasespecificadas,medidaenpíxeles.
SetmyBalloon=Assistant.NewBalloon
WithmyBalloon
.SetAvoidRectangle300,250,700,500
.Text="Cannotdisplayincoordinates"&_
"300,250,700,500."
.Show
EndWith
Mostrartodo
MétodoSetFocus
Mueveelfocodeltecladoalcontroldebarradecomandosespecificadoparapoderrecibirlaentradadeteclado.Eltipodeentradadetecladoquesepuededirigiralcontroldependedeltipodecontroldequesetrate.
Comentarios
Elfocosobreelcontrolesimperceptible.Despuésdeutilizarestemétodo,notaráunrealcetridimensionalenesecontrol.Paradesplazarseporlasbarrasdeherramientas,presionelasteclasdedirección,delamismaformaquesihubieratenidoaccesoalcontrolpresionandosóloloscontrolesdelteclado.
expresión.SetFocus
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarControl,CommandBarButton,CommandBarPopupoCommandBarComboBox.
Ejemplo
Esteejemplocreaunabarradecomandosdenominada"Custom"yagregaloscontrolesComboBoxyButtonaesabarra.Acontinuación,elejemploutilizaelmétodoSetFocusparaestablecerelfocoenelcontrolComboBox.
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
MétodoSetSortOrder
Estableceelordendeclasificacióndelosdatosdecombinacióndecorrespondencia.
expresión.SetSortOrder(SortField1,SortAscending1,SortField2,SortAscending2,SortField3,SortAscending3)
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
SortField1Stringrequerida.Elprimercampoenelqueseclasificanlosdatosdecombinacióndecorrespondencia.
SortAscending1Booleanopcional.True(predeterminado)pararealizarunaclasificaciónascendenteenSortField1;Falsepararealizarunaclasificacióndescendente.
SortField1Stringrequerida.Elsegundocampoenelqueseclasificanlosdatosdecombinacióndecorrespondencia.Elvalorpredeterminadoesunacadenavacía.
SortAscending2Booleanopcional.True(predeterminado)pararealizarunaclasificaciónascendenteenSortField2;Falsepararealizarunaclasificacióndescendente.
SortField3Stringrequerida.Eltercercampoenelqueseclasificanlosdatosdecombinacióndecorrespondencia.Elvalorpredeterminadoesunacadenavacía.
SortAscending3Booleanopcional.True(predeterminado)pararealizarunaclasificaciónascendenteenSortField3;Falsepararealizarunaclasificacióndescendente.
Ejemplo
Elejemplosiguienteclasificaprimeroelorigendedatossegúnelcódigopostalenordendescendente,acontinuaciónsegúnelapellidoyelnombredepilaenordenascendente.
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
Mostrartodo
MétodoShow
MétodoShowcuandoseaplicaalobjetoBalloon.
Muestraelobjetogloboespecificado.DevuelveunaconstantedeMsoBalloonButtonTypequeindicaenquébotónorótulohaceclicelusuario.Esdesólolectura.
MsoBalloonButtonTypepuedeserunadeestasconstantesdeMsoBalloonButtonType.msoBalloonButtonAbortmsoBalloonButtonBackmsoBalloonButtonCancelmsoBalloonButtonClosemsoBalloonButtonIgnoremsoBalloonButtonNextmsoBalloonButtonNomsoBalloonButtonNullmsoBalloonButtonOKmsoBalloonButtonOptionsmsoBalloonButtonRetrymsoBalloonButtonSearchmsoBalloonButtonSnoozemsoBalloonButtonTipsmsoBalloonButtonYesmsoBalloonButtonYesToAll
expresión.Show
expresiónRequerida.ExpresiónquedevuelveunobjetoBalloon.
MétodoShowcuandoseaplicaalobjetoFileDialog.
MuestrauncuadrodediálogodearchivosydevuelveunvalorLongqueindicasielusuariohapresionadoelbotóndeacción(-1)oeldecancelar(0).SiactivaelmétodoShow,noseejecutaráningúncódigomáshastaqueelusuariocierreelcuadrodediálogodearchivos.EnelcasodeloscuadrosdediálogoGuardarcomoyAbrir,utiliceelmétodoExecutedespuésdelmétodoShowparaejecutarlaaccióndelusuario.
expresión.Show
expresiónRequerida.ExpresiónquedevuelveunobjetoFileDialog.
Ejemplo
CuandoseaplicaalobjetoBalloon.
Esteejemplocreaunglobocondosopcionesderótulosdelgloboparaestablecerlaorientacióndelaimpresión:PortraityLandscape.ElejemploutilizaelmétodoShowenunainstrucciónSelectCaseparadeterminarquéorientaciónhaelegidoelusuario.
SetbalNew=Assistant.NewBalloon
WithbalNew
.Heading="Pleasechooseaprinterorientation"
.Labels(1).Text="Portrait"
.Labels(2).Text="Landscape"
.Button=msoButtonSetNone
EndWith
SelectCasebalNew.Show
Case1
'InsertcodetosetprintertoPortrait.
Case2
'InsertcodetosetprintertoLandscape.
EndSelect
Esteejemplocreaunglobocontresbotonesdecomando:Yes,NoyCancel.ElejemploutilizaelmétodoShowenunainstrucciónSelectCaseparadeterminarelvalordevueltodelbotónenelqueelusuariohahechoclic.
SetbalNew=Assistant.NewBalloon
WithbalNew
.Heading="Areyousureyouwanttosetthe"&_
"printerorientationtoLandscape?"
.BalloonType=msoBalloonTypeButtons
.Button=msoButtonSetYesNoCancel
EndWith
SelectCasebalNew.Show
Case-2 'UserselectedCancelbutton.
returnValue=MsgBox("Operationcanceled.",_
vbOKOnly,"PrinterMessage")
Case-3 'UserselectedYesbutton.
returnValue=MsgBox("Printersetto"&_
"Landscape.",vbOKOnly,"PrinterMessage")
Case-4 'UserselectedNobutton.
returnValue=MsgBox("Printerorientationnot"&_
"reset.",vbOKOnly,"PrinterMessage")
EndSelect
CuandoseaplicaalobjetoFileDialog.
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
Mostrartodo
MétodoShowPopup
Muestralabarradecomandosespecificadacomounmenúcontextualenlascoordenadasespecificadasoenlascoordenadasactualesdelpuntero.
NotaSilapropiedadPositiondelabarradecomandosnoseestableceenmsoBarPopup,estemétodofalla.
expresión.ShowPopup(x,y)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBar.
xVariantopcional.CoordenadaXdelaposicióndelmenúcontextual.Siseomiteesteargumento,seutilizarálacoordenadaXactualdelpuntero.
yVariantopcional.CoordenadaYdelaposicióndelmenúcontextual.Siseomiteesteargumento,seutilizarálacoordenadaYactualdelpuntero.
Ejemplo
Esteejemplocreaunmenúcontextualquecontienedoscontroles.ElmétodoShowPopupseutilizaparamostrarelmenúcontextual.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarPopup,Temporary:=False)
WithmyBar
.Controls.AddType:=msoControlButton,Id:=3
.Controls.AddType:=msoControlComboBox
EndWith
myBar.ShowPopup
MétodoStartWizard
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
IniciaelAyudantedeOfficeydevuelveunvalorLongqueidentificalasesión.SólopuedeutilizarestemétodoparainiciarelAyudantedeOfficeenunasistentepersonalizado.
NotaElnúmerodevueltoporelmétodoStartWizardloutilizanlosmétodosActivateWizardyEndWizard.
expresión.StartWizard(On,Callback,PrivateX,Animation,CustomTeaser,Top,Left,Bottom,Right)
expresiónRequerida.ExpresiónquedevuelveunobjetoAssistant.
OnBooleanrequerido.TrueparamostrarelglobodeOffice.ElglobodeOfficepreguntaalusuariosideseaayudaparaelasistentepersonalizadoactivo.NoesnecesarioutilizarlapropiedadVisibleparamostrarelAyudantedeOfficeAssistantsisehaespecificadoTrueparaesteargumento.
CallbackStringrequerida.ElnombredelprocedimientodedevolucióndellamadainiciadoporelglobodeOfficeyelglobosecundario.ElglobosecundariopermitealusuarioaelegirentrelaayudapersonalizadaqueproporcionaelasistenteylaayudaestándardeOffice.
PrivateXLongrequerido.Unnúmeroqueidentificaelgloboquehainiciadoelprocedimientodedevolucióndellamada.
AnimationVariantopcional.LaanimacióndelAyudantedeOfficecuandoseutilizaestemétodo.ElvalorpredeterminadoesmsoAnimationGetWizardy.
CustomTeaserVariantopcional.FalseparamostrarelglobodeOffice.
Top,Left,Bottom,RightVariantopcional.Laposicióndelasesquinas,enpuntosyconrelaciónalapantalla,delasistentepersonalizadodesdeelAyudante
deOfficedeterminarácuándoapareceelAyudantedeOffice.
Comentarios
Adiferenciadelosprocedimientosdedevolucióndellamadautilizadosporlosglobosestándarsinmodo,elprocedimientodedevoluciónllamadoporelglobodeOfficeyelglobosecundarioqueapareceduranteunasesióndelasistenteparaelAyudantedeOffice,sólollevadosargumentos:unaconstanteMsoWizardMsgTypeyelúnicovalorespecificadoporelargumentoPrivateXdelmétodoStartWizard.
SielusuariohaceclicconelbotónsecundarioenelglobodeOfficeoenelglobosecundario,laconstantemsoWizardMsgShowHelppasaalprimerargumentodelprocedimientodedevolucióndellamada.Sielusuariohaceclicenelbotónsecundario,pasalaconstantemsoWizardLocalStateOff.LasdemásconstantesMsoWizardMsgTypepasanporelmétodoActivateWizardsisehaespecificadomsoWizardActResumeomsoWizardActSuspendparaelargumentoAct.EnelcasodemsoWizardMsgShowHelp,elprocedimientodedevolucióndellamadadebemostrarelgloboadecuadoparaelpanelactualdelasistentepersonalizado.Además,enelcasodemsoWizardLocalStateOff,elprocedimientodedevolucióndellamadadebeocultarelglobovisible.
Ejemplo
EsteejemploiniciaelAyudantedeOfficecomopartedelprocesoqueproporcionainformaciónmientrasseejecutaunasistentepersonalizado.LavariableIHelpForWizsehaestablecidoenelvalordevueltoporelmétodoStartWizard,queesLong.
lHelpForWiz=Assistant.StartWizard(On:=True,_
Callback:="myCallback",PrivateX:=23)
MétodoUpdate
ActualizaelcontenidodelacolecciónCOMAddInsdelalistadecomplementosalmacenadosenelregistrodeWindows.
expresión.Update
expresiónLacolecciónCOMAddIns.
Comentarios
AntesdeutilizaruncomplementoCOMdeterminadoenunaaplicacióndeMicrosoftOffice,elcomplementodebeestarincluidoenelregistrodeWindowscomocomponenteCOM,juntoconsuId.correspondientedecategoríadecomponente.
Ejemplo
ElsiguienteejemploactualizaelcontenidodelacolecciónCOMAddInsdelalistadecomplementosalmacenadosenelregistrodeWindows.
Application.COMAddIns.Update
PropiedadActionControl
DevuelveelobjetoCommandBarControlcuyapropiedadOnActionestáestablecidaparaqueejecuteelprocedimiento.Sielprocedimientodeejecuciónnohasidoiniciadoporuncontroldebarradecomandos,estapropiedaddevuelveNothing.Esdesólolectura.
Ejemplo
Esteejemplocreaunabarradecomandosdenominada"Custom",agregatresbotonesaesabarray,acontinuación,utilizalaspropiedadesActionControlyTagparadeterminarelúltimobotóndelabarradecomandosenelquesehizoclic.
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
LasubrutinawhichButtonrespondealmétodoOnActionydeterminaelúltimobotóndelabarradecomandosenelquesehizoclic.
SubwhichButton()
SelectCaseCommandBars.ActionControl.Tag
Case"RightArrow"
MsgBox("RightArrowbuttonclicked.")
Case"UpArrow"
MsgBox("UpArrowbuttonclicked.")
Case"DownArrow"
MsgBox("DownArrowbuttonclicked.")
EndSelect
EndSub
PropiedadActiveMenuBar
DevuelveunobjetoCommandBarquerepresentalabarrademenúsactivadelaaplicacióncontenedora.Esdesólolectura.
Ejemplo
Esteejemploagregauncontrolemergentetemporaldenominado"Custom"alfinaldelabarrademenúsactivay,acontinuación,agregauncontroldebotóndenominado"Import"enlabarradecomandosmostradaporelcontrol.
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
PropiedadAdaptiveMenu
Truesisehabilitaunmenúpersonalizado.BooleandeLectura/Escritura.
Ejemplo
EsteejemploestablecelapropiedadAdaptiveMenuenFalseparaelmenúArchivodelaaplicaciónMicrosoftOfficeenlaqueestétrabajando.
CommandBars("File").AdaptiveMenu=False
PropiedadAdaptiveMenus
Truesilosmenúsadaptablesestánhabilitados.BooleandeLectura/Escritura.
Ejemplo
EsteejemploestablecetresopcionesparatodaslasbarrasdecomandosenMicrosoftOffice,incluyendolasbarrasdecomandospersonalizadasyloscontrolesdeesasbarras.
WithCommandBars
.LargeButtons=True
.DisplayFonts=True
.AdaptiveMenus=True
EndWith
PropiedadAllowMultiSelect
Truesisepermitealusuarioseleccionarvariosarchivosenuncuadrodediálogodearchivos.BooleandeLectura/Escritura.
expresión.AllowMultiSelect
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
EstapropiedadnotieneefectoenloscuadrosdediálogoSelectordecarpetasoGuardarcomoporquelosusuariosnodeberíanpoderseleccionarvariosarchivosenestetipodecuadrosdediálogodearchivos.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
PropiedadAnimation
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestablecelaaccióndeanimacióndeAyudantedeOffice.SiseaplicaestapropiedadalobjetoAssistantylaanimaciónescompatible,elAyudanteseanimainmediatamente(siestávisibleyhabilitado).AlaplicarestapropiedadalobjetoBalloon,elAyudanteseanimasólomientrassemuestreelglobo.MsoAnimationTypedeLectura/Escritura.
MsoAnimationTypepuedeserunadeestasconstantesdeMsoAnimationType.msoAnimationAppearmsoAnimationBeginSpeakingmsoAnimationCharacterSuccessMajormsoAnimationCheckingSomethingmsoAnimationDisappearmsoAnimationEmptyTrashmsoAnimationGestureDownmsoAnimationGestureLeftmsoAnimationGestureRightmsoAnimationGestureUpmsoAnimationGetArtsymsoAnimationGetAttentionMajormsoAnimationGetAttentionMinormsoAnimationGetTechymsoAnimationGetWizardymsoAnimationGoodbyemsoAnimationGreetingmsoAnimationIdlemsoAnimationListensToComputermsoAnimationLookDown
msoAnimationLookDownLeftmsoAnimationLookDownRightmsoAnimationLookLeftmsoAnimationLookRightmsoAnimationLookUpmsoAnimationLookUpLeftmsoAnimationLookUpRightmsoAnimationPrintingmsoAnimationRestPosemsoAnimationSavingmsoAnimationSearchingmsoAnimationSendingMailmsoAnimationThinkingmsoAnimationWorkingAtSomethingmsoAnimationWritingNotingSomething
Comentarios
"Clippit"eselAyudantepredeterminadoymsoAnimationIdleeseltipodeanimaciónpredeterminadoparaelAyudante.
DependiendodelAyudanteseleccionado,lapropiedadAnimationpuedeproducironounaanimaciónobvia.Sinembargo,todaslasconstantesMsoAnimationTypesonválidasparatodoslosAyudantes.Observequedistintasconstantespuedenproducirlamismaanimación.
LassiguientesconstantesMsoAnimationTyperepresentananimacionesquerepitenlaacciónespecificadahastaquesecierreelAyudanteohastaquelapropiedadAnimationserestablezcaconotraanimación:
msoAnimationCheckingSomething
msoAnimationGetTechy
msoAnimationListensToComputer
msoAnimationSearching
msoAnimationThinking
msoAnimationWorkingAtSomething
msoAnimationWritingNotingSomething
Ejemplo
EsteejemplomuestraelAyudantedeOfficeenunaubicaciónespecíficayconfiguravariasopcionesantesdemostrarlo.
WithAssistant
.On=True
.Visible=True
.MovexLeft:=400,yTop:=300
.MoveWhenInTheWay=True
.TipOfDay=True
.Animation=msoAnimationGreeting
EndWith
PropiedadApplication
DevuelveunobjetoApplicationquerepresentalaaplicacióncontenedoradelobjetoespecificado(puedeutilizarestapropiedadconunobjetoAutomationparadevolverlaaplicacióncontenedoradelobjeto).
expresión.Application
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemplodevuelveelnombredelaaplicaciónenlaquesecreólabarradecomandosdenominadaStandardymuestraelresultadoenuncuadrodemensaje.
SetAppobj=CommandBars("Standard").Application
MsgBoxAppobj
PropiedadAssistWithAlerts
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielglobodelAyudantedeOfficemuestramensajesdealertadelaaplicaciónsiemprequeestévisible.BooleandeLectura/Escritura.
Comentarios
LapropiedadAssistWithAlertscorrespondealaopciónMostraralertasdeUtilizarelAyudantedeOfficedelafichaOpciones,enelcuadrodediálogoAyudantedeOffice.
SiestapropiedadestáestablecidaenFalse,laaplicaciónmuestramensajesdealertaencuadrosdediálogosinelAyudantedeOffice.
Ejemplo
EsteejemploestablecequeelAyudantedeOfficesemuestresiemprequesegenereunaalertadelaaplicación.
WithAssistant
.On=True
.Visible=True
.AssistWithHelp=True
.AssistWithAlerts=True
.Animation=msoAnimationGetAttentionMajor
EndWith
PropiedadAssistWithHelp
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeaparecesiemprequeelusuariopresionelateclaF1paramostrarlaAyuda.BooleandeLectura/Escritura.
Comentarios
LapropiedadAssistWithHelpcorrespondealaopciónResponderalateclaF1deUtilizarelAyudantedeOfficeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
SielvalordeestapropiedadesFalse,apareceráelcuadrodediálogoTemasdeAyudaenlugardelAyudantedeOffice.
Ejemplo
EsteejemplomuestraelAyudantedeOfficesiemprequeelusuariopresionelateclaF1paramostrarlaAyuda.
WithAssistant
.On=True
.Visible=True
.AssistWithHelp=True
.AssistWithAlerts=True
.Animation=msoAnimationGetAttentionMajor
EndWith
PropiedadAssistWithWizards
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeproporcionainformacióndeAyudaacercadelosasistentes.BooleandeLectura/Escritura.
Comentarios
LapropiedadAssistWithWizardscorrespondealaopciónAyudaconasistentesdeUtilizarelAyudantedeOfficeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaqueofrezcainformacióndeAyudaacercadelosasistentes.
Assistant.AssistWithWizards=True
PropiedadAttachCertificate
TruesielcertificadodigitalquecorrespondealobjetoSignatureespecificadoseadjuntaaldocumento.BooleandeLectura/Escritura.
expresión.AttachCertificate
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentoenWordyejecuteestafunción.Lafunciónrealizarálacomprobaciónparaasegurarsedequelafirmadigitalqueseleccionaelusuarionocaducaantesde12meses.Sicaduca,noseadjuntaelcertificado.
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
PropiedadBalloonError
Devuelveunvalorqueindicaelúltimoerrordegloboregistrado.MsoBalloonErrorTypedesólolectura.
MsoBalloonErrorTypepuedeserunadeestasconstantesdeMsoBalloonErrorType.msoBalloonErrorBadCharacterElglobocontieneuncarácterdecontrolASCIIdistintodeCRoLFymenorque32.msoBalloonErrorBadPictureRefElglobocontieneunmapadebitsquenosehapodidomostrarporqueelarchivonoexisteoporqueelmapadebitsnoesunarchivo.BMPo.WMFválido.msoBalloonErrorBadReferenceElglobocontieneunareferencianoreconocidaonoadmitida.msoBalloonErrorButtonlessModalElgloboqueintentómostraresmodal,peronocontienebotones.Elglobonosemostraráporquenopuedecerrarse.msoBalloonErrorButtonModelessElgloboqueintentómostrarnotienemodo,contienebotonesynotieneunprocedimientoasignadoalapropiedadCallback.Elglobonosemostraráporqueserequiereunprocedimientoparaevaluarelbotónseleccionadoenél.msoBalloonErrorCharNotTopmostForModalElglobodemodohasidorequeridoporunaaplicacióndistintaalaaplicaciónactiva.MicrosoftOfficesólomuestraglobosparalaaplicaciónactiva(lasuperior).msoBalloonErrorCOMFailureElglobonosehapodidomostrardebidoaunfalloCOM.msoBalloonErrorNoneNoseencontróningúnerror.msoBalloonErrorOtherElglobonoapareceráporquesehaproducidoalgúnotroerror;porejemplo,otroglobomodalyaestáactivo.msoBalloonErrorOutOfMemoryElglobonoapareceráporquenohaymemoriasuficiente.msoBalloonErrorTooBigElgloboesdemasiadograndecomoparamostrarseenpantalla.
msoBalloonErrorTooManyControlsElglobocontienemásdeveintecontroles(casillasdeverificaciónoetiquetas).
Ejemplo
Esteejemplocreaungloboquegeneraunerror.Elerrorsedebeaqueelglobosehacreadosinposibilidaddecerrarlo.EltipodebotónsehaestablecidoenmsoButtonSetNoneyelmododeglobopredeterminadoesmsoModeModal,produciendounglobomodalsinbotones.Observequenohayformadecerrarunglobomodalsinbotones.
WithApplication.Assistant
With.NewBalloon
.Heading="Thiswillnevershow."
.Text="Imagineaballoonhere."
.Button=msoButtonSetNone
.Show
EndWith
.Visible=True
If.BalloonError=msoBalloonErrorButtonlessModalThen
MsgBox"Youneedabuttontodismisstheballoon."
EndIf
EndWith
PropiedadBalloonType
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceeltipodegloboqueutilizaelAyudantedeOffice.AlcrearunobjetoBalloon,estapropiedadestáinicialmenteestablecidaenmsoBalloonTypeButtons.MsoBalloonTypedeLectura/Escritura.
MsoBalloonTypepuedeserunadeestasconstantesdeMsoBalloonType.msoBalloonTypeBulletsmsoBalloonTypeButtonsmsoBalloonTypeNumbers
Ejemplo
Esteejemplocreaunglobodeinstruccionesqueexplicacómoseleccionarunaimpresora.Elglobonotienemodo,deformaqueelusuariopuedeseguirlasinstruccionesdelgloboymantenerlovisiblemientrastrabaja.
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
Mostrartodo
PropiedadBeginGroup
Truesielcontroldebarradecomandosespecificadoestáalprincipiodeungrupodecontrolesenlabarradeherramientas.BooleandeLectura/Escritura.
Ejemplo
Esteejemploestablecequeelúltimocontroldelabarrademenúsactivaestéalprincipiodesupropiogrupo.
SetmyMenuBar=CommandBars.ActiveMenuBar
SetlastMenu=myMenuBar_
.Controls(myMenuBar.Controls.Count)
lastMenu.BeginGroup=True
Mostrartodo
PropiedadBuiltIn
Truesilabarradecomandosoelcontroldebarradecomandosespecificadoesunabarradecomandosocontrolintegradosdelaaplicacióncontenedora.Falsesisetratadeunabarradecomandosocontrolpersonalizados,osisetratadeuncontrolintegradocuyapropiedadOnActionhasidoestablecida.Booleandesólolectura.
Ejemplo
Esteejemploeliminatodaslasbarrasdecomandospersonalizadasnovisibles.
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
Mostrartodo
PropiedadBuiltInFace
Truesilaimagendelcontroldebotóndelabarradecomandosespecificadaesunaimagenintegrada.ElvalordeestapropiedadsólopuedeserTruequerestablecerálaimagenintegrada.BooleandeLectura/Escritura.
Ejemplo
Esteejemplodeterminasilaimagendelprimercontroldelabarradecomandosdenominada"Custom"eslaimagenintegrada.Enestecaso,elejemplocopialaimagendebotónenelPortapapeles.
SetmyControl=CommandBars("MyCustomBar").Controls(1)
WithmyControl
If.BuiltInFace=TrueThen.CopyFace
EndWith
PropiedadButton
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceeltipodebotónmostradoenlaparteinferiordelgloboAyudantedeOffice.AlcrearunobjetoBalloon,estapropiedadestáinicialmenteestablecidaenmsoButtonSetOK.MsoButtonSetTypedeLectura/Escritura.
MsoButtonSetTypepuedeserunadeestasconstantesdeMsoButtonSetType.msoButtonSetAbortRetryIgnoremsoButtonSetBackClosemsoButtonSetBackNextClosemsoButtonSetBackNextSnoozemsoButtonSetCancelmsoButtonSetNextClosemsoButtonSetNonemsoButtonSetOKmsoButtonSetOkCancelmsoButtonSetRetryCancelmsoButtonSetSearchClosemsoButtonSetTipsOptionsClosemsoButtonSetYesAllNoCancelmsoButtonSetYesNomsoButtonSetYesNoCancel
Ejemplo
Esteejemplomuestraungloboconencabezado,texto,tresopcionesderegiónydosbotonesdecomando(OKyCancel).
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Button=msoButtonSetOkCancel
.Show
EndWith
PropiedadButtonName
EstableceodevuelveunvalorStringquerepresentaeltextoquesemuestraenelbotóndeaccióndeuncuadrodediálogodearchivos.Deformapredeterminada,estapropiedadestáestablecidaeneltextoestándarparaeltipodecuadrodediálogodearchivos.Porejemplo,enelcasodelcuadrodediálogoAbrir,lapropiedadestáestablecidaa"Abrir"deformapredeterminada.Lectura/Escritura.
expresión.ButtonName
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
PropiedadCallback
Estableceelnombredelprocedimientoparaqueseejecuteenunglobonomodal.StringdeLectura/Escritura.
Comentarios
ElprocedimientoqueseespecifiqueparalapropiedadCallbackdebeestarescritopararecibirdosotresargumentos,segúnconquésevayaautilizarlapropiedad.SiseutilizalapropiedadCallbackconunasistente,sedebeescribirelprocedimientopararecibirdosargumentos:unnúmeroenterolargoquerepresenteelvalormsoBalloonButtonTypedelbotónenelqueelusuariohaceclic,yunnúmeroenterolargoquesóloidentifiquealglobo.SiseutilizalapropiedadCallbackconunglobonomodal,sedebeescribirelprocedimientopararecibirtresargumentos:elobjetoBalloonquellamaalprocedimiento;unnúmeroenterolargoquerepresentaelvalormsoBalloonButtonTypedelbotónenelqueelusuariohaceclic;yunnúmeroenterolargoquesóloidentifiquealgloboquellamaalprocedimiento,comoseindicaenlapropiedaddelgloboPrivate.
Elprocedimientodedevolucióndellamadadebecontener,porlomenos,unacondiciónbajolaqueseapliqueelmétodoClosealobjetoBalloonalquesehatraspasado;sino,elglobonomodalnosepodrácerrar.
Siespecificaunprocedimientoquesealmaceneenunmódulodeclaseindependiente,debeincluirelnombredelmóduloenelvalorqueseasignealapropiedadCallback;porejemplo,"Sheet1.MyCallback).
Ejemplo
Esteejemplomuestraungloboquecontieneunbotónporcadatresimpresoras.Siemprequeelusuariohagaclicenunodeesostresbotones,elprocedimientodedevolucióndellamadaProcessPrinterseejecutayelglobosecierra.
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
Mostrartodo
PropiedadCaption
Devuelveoestableceeltextodeltítulodelcontroldebarradecomandosespecificado.StringdeLectura/Escritura.
NotaEltítulodeuncontroltambiénsemuestracomoSugerenciapredeterminada.
Ejemplo
Esteejemploagregauncontroldebarradecomandosconlaimagendebotóndelcorrectorortográficoaunabarradecomandospersonalizaday,acontinuación,estableceeltítulo"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
PropiedadCheckboxes
DevuelvelacolecciónBalloonCheckboxesquerepresentatodaslascasillasdeverificacióndelgloboespecificado.Esdesólolectura.
Paraobtenermásinformaciónacercadecómodevolverunsolomiembrodeunacolección,veaDevolverunobjetodeunacolección.
Ejemplo
Esteejemplocreaungloboconencabezado,textoytresopcionesderegión.Cuandoelusuarioseleccionaunacasilladeverificacióny,acontinuación,haceclicenAceptarenelglobo,seimprimenlosdatosdelaregiónoregionesseleccionadas.
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
PropiedadChecked
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesilacasilladeverificaciónespecificadaenelgloboAyudantedeOfficeestáactivada.BooleandeLectura/Escritura.
Ejemplo
Esteejemplocreaungloboconencabezado,textoytresopcionesderegión.Cuandoelusuarioseleccionaunacasilladeverificacióny,acontinuación,haceclicenAceptarenelglobo,seimprimenlosdatosdelaregiónoregionesseleccionadas.
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
PropiedadColumn
DevuelveoestableceunvalorStringquerepresentaelnombredelcampodelorigendedatosdecombinacióndecorrespondenciaqueutilizaráenelfiltro.Lectura/Escritura.
expresión.Column
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistrosquenotenganuncampoRegióniguala"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
PropiedadColumns
DevuelveunobjetoODSOColumnsquerepresentaloscamposdeunorigendedatos.
expresión.Columns
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
Elejemplosiguientemuestralosnombresdecamposdelorigendedatosadjuntoalapublicaciónactiva.
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
Mostrartodo
PropiedadCommandBar
DevuelveunobjetoCommandBarquerepresentaelmenúmostradoporelcontrolemergenteespecificado.Esdesólolectura.
Ejemplo
EsteejemploestableceelvalorfourthLevelparaelcuartocontroldelabarradecomandosdenominada"Drawing".
SetfourthLevel=CommandBars("Drawing")_
.Controls(1).CommandBar.Controls(4)
PropiedadCommandBars
DevuelveunacolecciónCommandBars.
expresión.CommandBars
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientedevuelvelacolecciónCommandBarsdelobjetoMsoEnvelopeenMicrosoftWord.
DimcbarsAsCommandBars
Setcbars=Application.ActiveDocument.MailEnvelope.Commandbars
PropiedadCompareTo
DevuelveoestableceunvalorStringquerepresentaeltextodecomparacióndelcriteriodefiltrodeconsultas.Lectura/Escritura.
expresión.CompareTo
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistrosquenotenganuncampoRegióniguala"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
Mostrartodo
PropiedadComparison
DevuelveoestableceunaconstantedeMsoFilterComparisonquerepresentacómocompararlaspropiedadesColumnyCompareTo.Lectura/Escritura.
MsoFilterComparisonpuedeserunadeestasconstantesdeMsoFilterComparison.msoFilterComparisonContainsmsoFilterComparisonEqualmsoFilterComparisonGreaterThanmsoFilterComparisonGreaterThanEqualmsoFilterComparisonIsBlankmsoFilterComparisonIsNotBlankmsoFilterComparisonLessThanmsoFilterComparisonLessThanEqualmsoFilterComparisonNotContainsmsoFilterComparisonNotEqual
expresión.Comparison
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistrosquenotenganuncampoRegióniguala"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
PropiedadCondition
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Devuelvelacondicióndeloscriteriosdebúsquedaespecificados.MsoConditiondesólolectura.
MsoConditionpuedeserunadeestasconstantesdeMsoCondition.msoConditionAnyNumberBetweenmsoConditionAnytimemsoConditionAnytimeBetweenmsoConditionAtLeastmsoConditionAtMostmsoConditionBeginsWithmsoConditionDoesNotEqualmsoConditionEndsWithmsoConditionEqualsmsoConditionFileTypeAllFilesmsoConditionFileTypeBindersmsoConditionFileTypeCalendarItemmsoConditionFileTypeContactItemmsoConditionFileTypeDatabasesmsoConditionFileTypeDataConnectionFilesmsoConditionFileTypeDesignerFilesmsoConditionFileTypeEPaperFilesmsoConditionFileTypeExcelWorkbooksmsoConditionFileTypeJournalItemmsoConditionFileTypeMailItemmsoConditionFileTypeNoteItemmsoConditionFileTypeOfficeFiles
msoConditionFileTypeOutlookItemsmsoConditionFileTypePhotoDrawFilesmsoConditionFileTypePowerPointPresentationsmsoConditionFileTypeProjectFilesmsoConditionFileTypePublisherFilesmsoConditionFileTypeTaskItemmsoConditionFileTypeTemplatesmsoConditionFileTypeVisioDocumentsmsoConditionFileTypeWebPagesmsoConditionFileTypeWordDocumentsmsoConditionFreeTextmsoConditionIncludesmsoConditionIncludesFormsOfmsoConditionIncludesNearEachOthermsoConditionIncludesPhrasemsoConditionInTheLastmsoConditionInTheNextmsoConditionIsExactlymsoConditionIsNomsoConditionIsNotmsoConditionIsYesmsoConditionLastMonthmsoConditionLastWeekmsoConditionLessThanmsoConditionMoreThanmsoConditionNextMonthmsoConditionNextWeekmsoConditionOnmsoConditionOnOrAftermsoConditionOnOrBeforemsoConditionThisMonthmsoConditionThisWeekmsoConditionToday
msoConditionTomorrowmsoConditionYesterday
Ejemplo
Esteejemplodevuelveelvalordecondicióndeloscriteriosdebúsquedadelaprimerapruebadepropiedades.
WithApplication.FileSearch.PropertyTests(1)
MsgBox"Theconditionyou'vesetis:"&.Condition
EndWith
Mostrartodo
PropiedadConjunction
DevuelveoestableceunaconstantedeMsoFilterConjunctionquerepresentacómoestárelacionadouncriteriodefiltroconotrocriteriodefiltrodelobjetoODSOFilters.Lectura/Escritura.
MsoFilterConjunctionpuedeserunadeestasconstantesdeMsoFilterConjunction.msoFilterConjunctionAndmsoFilterConjunctionOr
expresión.Conjunction
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientecambiaunfiltroexistenteparaquitardelacombinacióndecorrespondenciatodoslosregistrosquenotenganuncampoRegióniguala"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
PropiedadConnect
DevuelveoestableceelestadodeconexióndelobjetoCOMAddInespecificado.BooleandeLectura/Escritura.
Comentarios
LapropiedadConnectdevuelveTruesielcomplementoestáactivo;devuelveFalsesielcomplementoestáinactivo.Uncomplementoactivoestáregistradoyconectado;uncomplementoinactivoestáregistrado,peronoestáconectadoactualmente.
Ejemplo
ElejemplosiguientemuestrauncuadrodemensajequeindicasielcomplementoCOMestáregistradoyconectadoactualmente.
IfApplication.COMAddIns(1).ConnectThen
MsgBox"Theadd-inisconnected."
Else
MsgBox"Theadd-inisnotconnected."
EndIf
PropiedadConnector
Devuelveelconectorentredosvaloresdepruebadepropiedadessimilares.ElvalorpredeterminadoesmsoConnectorAnd.MsoConnectordesólolectura.
MsoConnectorpuedeserunadeestasconstantesdeMsoConnector.msoConnectorAndmsoConnectorOr
Comentarios
Unconectorespecificasidoscriteriosdebúsquedasimilaressecombinaránparaformarunapruebadepropiedad,comoconmsoConnectorAndosetrataránindependientemente,comoconmsoConnectorOr.
Ejemplo
Esteejemplomuestraunmensajequedescribecómoseevaluaránloscriteriosdebúsquedadeunabúsquedadearchivos.
WithApplication.FileSearch.PropertyTests(1)
If.Connector=msoConnectorAndThen
MsgBox"Allsearchcriteriawillbecombined."
Else
MsgBox"Criteriawillbetreatedindependently"
EndIf
EndWith
PropiedadConnectString
DevuelveoestableceunvalorStringquerepresentalaconexiónalorigendedatosdecombinacióndecorrespondenciaespecificado.Lectura/Escritura.
expresión.ConnectString
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemplocompruebasilacadenadeconexióncontieneloscaracteresODSOOutlookymuestraelmensajecorrespondiente.
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
Mostrartodo
PropiedadContext
Devuelveoestableceunacadenaquedeterminasiseguardarálabarradecomandosespecificada.Laaplicacióndefineeinterpretalacadena.StringdeLectura/Escritura.
Comentarios
LapropiedadContextsólopuedeestablecerseparabarrasdecomandospersonalizadas.Estapropiedadfallarásilaaplicaciónnoreconocelacadenadecontextoosinoadmitequeelprogramacambielascadenasdecontexto.
Ejemplo
Esteejemplomuestrauncuadrodemensajeconlacadenadecontextoparalabarradecomandosdenominada"Custom".EsteejemplofuncionaenMicrosoftWordyencualquieraplicaciónqueadmitalapropiedadContext.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlButton,ID:=2
.Visible=True
EndWith
MsgBox(myBar.Context)
PropiedadControls
DevuelveunobjetoCommandBarControlsquerepresentatodosloscontrolesdelabarradecomandosodelcontrolemergente.Esdesólolectura.
Paraobtenermásinformaciónsobrecómodevolverunsolomiembrodeunacolección,veaDevolverunobjetodeunacolección.
Ejemplo
Esteejemploagregauncontroldecuadrocombinadoalabarradecomandosdenominada"Custom"yagregadoselementosalalistadelcuadrocombinado.Elejemplotambiénestableceelnúmerodeelementosdelínea,elanchodelcuadrocombinadoyunvalorvacíopredeterminadoparaelcuadrocombinado.
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
PropiedadCount
Puedequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceunvalorLongqueindicaelnúmerodeelementosdelacolecciónespecificada.LongdeLectura/EscrituraparalosobjetosBalloonCheckboxesyBalloonLabels;LongdesólolecturaparaelrestodelosobjetosdelalistaAplicara.
expresión.Count
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Comentarios
ParalacolecciónCommandBars,elrecuentosóloincluyebarrasdemenús,barrasdeherramientasymenúscontextuales.
ParalacolecciónScriptselrecuentoquesedevuelveeselnúmerodebloquesdesecuenciadecomandosdeldocumentoespecificado.EnMicrosoftWord,Scripts.Countdevuelveelnúmerototaldedelimitadoresdesecuenciasdecomandosenlíneayflotantescombinados.
Ejemplo
EsteejemploutilizalapropiedadCountparamostrarelnúmerodebarrasdecomandosenlacolecciónCommandBars.
MsgBox"Thereare"&CommandBars.Count&_
"barsintheCommandBarscollection."
EsteejemploutilizalapropiedadCountparamostrarelnúmerodecasillasdeverificaciónenelgloboAyudantedeOffice.
WithAssistant.NewBalloon
.CheckBoxes(1).Text="FirstChoice"
.CheckBoxes(2).Text="SecondChoice"
.Text="Youhavethefollowing"_
&.CheckBoxes.Count&"choices."
.Show
EndWith
Esteejemplomuestraelnúmerodepropiedadespersonalizadasdeundocumentoeneldocumentoactivo.
MsgBox("Thereare"&_
ActiveDocument.CustomDocumentProperties.Count&_
"customdocumentpropertiesinthe"&_
"activedocument.")
PropiedadCreator
Devuelveelcódigodecuatrocaracteresdelaaplicaciónenquesecreóelobjetoespecificado.SóloaplicableenequiposMacintosh.Longdesólolectura.
expresión.Creator
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
PropiedadDataSource
DevuelveoestableceunvalorStringquerepresentaelnombredelorigendedatosadjunto.Lectura/Escritura.
expresión.DataSource
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
Elejemplosiguienteestableceelnombredelorigendedatossielnombreestáenblanco.
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
Mostrartodo
PropiedadDescription
PropiedadDescriptioncuandoseaplicaalobjetoCOMAddIn.
DevuelveoestableceunvalorStringdescriptivoparaelobjetoCOMAddInespecificado.Lectura/Escritura.
expresión.Description
expresiónRequerida.ExpresiónquedevuelveunobjetoCOMAddIn.
PropiedadDescriptioncuandoseaplicaalobjetoFileDialogFilter.
DevuelveladescripcióndecadaobjetoFiltercomounvalorString.Ladescripcióneseltextoquesemuestraenelcuadrodediálogodelarchivo.Esdesólolectura.
expresión.Description
expresiónRequerida.ExpresiónquedevuelveunobjetoFileDialogFilter.
Ejemplo
CuandoseaplicaalobjetoCOMAddIn.
ElejemplosiguientemuestraeltextodescriptivodelcomplementoCOMdeaccesibilidadparadibujardeMicrosoftOffice.
MsgBox"Thedescriptionofthis"&_
"COMAddInis"""&Application.COMAddIns._
Item("msodraa9.ShapeSelect")._
Description&"""
CuandoseaplicaalobjetoFileDialogFilter.
ElejemplosiguienterepitelosfiltrospredeterminadosdelcuadrodediálogoGuardarcomoymuestraladescripcióndelosfiltrosqueincluyecadaarchivodeMicrosoftExcel.LapropiedadExtensionsseutilizaparaencontrarlosobjetosdefiltroapropiados.
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
Mostrartodo
PropiedadDescriptionText
Devuelveoestableceladescripcióndelcontroldelabarradecomandosespecificado.Ladescripciónnosemuestraalusuario,peropuedeserútilparadocumentarelcomportamientodelcontrolparaotrosprogramadores.StringdeLectura/Escritura.
Comentarios
EstapropiedadseutilizaparaelglobodeAyudaenMacintosh.
Ejemplo
Esteejemploagregauncontrolaunabarradecomandosconunadescripcióndelcomportamientodelcontrol.
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
Mostrartodo
PropiedadDialogType
DevuelveunaconstantedeMsoFileDialogTypequerepresentaeltipodecuadrodediálogoqueelobjetoFileDialogestáestablecidoparamostrar.Esdesólolectura.
MsoFileDialogTypepuedeserunadeestasconstantesdeMsoFileDialogType.msoFileDialogFilePickermsoFileDialogFolderPickermsoFileDialogOpenmsoFileDialogSaveAs
expresión.DialogType
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientetomaunobjetoFileDialogdetipodesconocidoyejecutaelmétodoExecutesiesuncuadrodediálogoGuardarcomooAbrir.
SubDisplayAndExecuteFileDialog(ByReffdAsFileDialog)
'UseaWith...EndWithblocktoreferencetheFileDialogobject.
Withfd
'Iftheuserpressestheactionbutton...
If.Show=-1Then
'UsetheDialogTypepropertytodeterminewhetherto
'usetheExecutemethod.
SelectCase.DialogType
CasemsoFileDialogOpen,msoFileDialogSaveAs:.Execute
'Donothingotherwise.
CaseElse
EndSelect
'IftheuserpressesCancel...
Else
EndIf
EndWith
EndSub
PropiedadDisableAskAQuestionDropdown
TruesiestáhabilitadoelmenúdesplegabledelAsistenteparaAyuda.BooleandeLectura/Escritura.
expresión.DisableAskAQuestionDropdown
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientealternalapropiedadDisableAskAQuestionDropdown.
SubToggleQuestionDropdown()
WithApplication.CommandBars
If.DisableAskAQuestionDropdown=TrueThen
.DisableAskAQuestionDropdown=False
Else
.DisableAskAQuestionDropdown=True
EndIf
EndWith
EndSub
PropiedadDisableCustomize
Truesiestádeshabilitadalapersonalizacióndelabarradeherramientas.BooleandeLectura/Escritura.
expresión.DisableCustomize
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientealternalapropiedadDisableCustomize.
SubToggleCustomize()
WithApplication.CommandBars
If.DisableCustomize=TrueThen
.DisableCustomize=False
Else
.DisableCustomize=True
EndIf
EndWith
EndSub
PropiedadDisplayFonts
TruesilosnombresdelasfuentesdelcuadroFuenteaparecenensusfuentesactuales.BooleandeLectura/Escritura.
Ejemplo
EsteejemploestablecetresopcionesparatodaslasbarrasdecomandosenMicrosoftOffice,incluyendolasbarrasdecomandospersonalizadasyloscontrolesdeesasbarras.
WithCommandBars
.LargeButtons=True
.DisplayFonts=True
.AdaptiveMenus=True
EndWith
Mostrartodo
PropiedadDisplayKeysInTooltips
TruesisemuestranlasteclasdemétodoabreviadoenlosToolTipsdecadacontroldebarradecomandos.BooleandeLectura/Escritura.
Comentarios
ParamostrarlasteclasenlosToolTips,debeestablecertambiénlapropiedadDisplayTooltipsenTrue.
Ejemplo
EsteejemploestablecelasopcionesdetodaslasbarrasdecomandosdeMicrosoftOffice.
WithCommandBars
.LargeButtons=True
.DisplayTooltips=True
.DisplayKeysInTooltips=True
.MenuAnimationStyle=msoMenuAnimationUnfold
EndWith
Mostrartodo
PropiedadDisplayTooltips
TruesisemuestranSugerenciassiemprequeelusuariositúeelpunteroenloscontrolesdebarradecomandos.BooleandeLectura/Escritura.
Comentarios
EstablecerlapropiedadDisplayTooltipsenunaaplicacióncontenedoraafectainmediatamenteatodaslasbarrasdecomandosdedichaaplicaciónydecualquierotraaplicacióndeMicrosoftOfficequeseestéejecutandoenesemomentooqueseabradespués,hastaqueestapropiedadseestablezcadenuevo.
Ejemplo
EsteejemplomuestracontrolesgrandeseInformaciónsobreherramientasentodaslasbarrasdecomandos.
SetallBars=CommandBars
allBars.LargeButtons=True
allBars.DisplayTooltips=True
Mostrartodo
PropiedadDropDownLines
Devuelveoestableceelnúmerodelíneasdelcontroldecuadrocombinadodelabarradecomandosespecificada.Elcontroldecuadrocombinadodebeseruncontrolpersonalizadoydebesercuadrodelistaemergenteouncuadrocombinado.LongdeLectura/Escritura.
NotaEstemétodofallarásilapropiedadseestableceparauncontroldecuadrocombinadoqueseauncontroldecuadrodeediciónodecuadrocombinadointegrado.
Comentarios
Siestapropiedadseestableceen0(cero),elnúmerodelíneasdecontrolsebasaráenelnúmerodeelementosdelalista.
Ejemplo
Esteejemploagregauncontroldecuadrocombinadoalabarradecomandosdenominada"Custom"y,acontinuación,agregadoselementosalalistadelcuadrocombinado.Elejemplotambiénestableceelnúmerodeelementosdelínea,elanchodelcuadrocombinadoyunvalorvacíopredeterminadoparaelcuadrocombinado.
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
Mostrartodo
PropiedadDropDownWidth
Devuelveoestableceelancho,enpíxeles,delalistadelcontroldecuadrocombinadodelabarradecomandosespecificada.LongdeLectura/Escritura.
NotaSiestapropiedadseestableceparaunabarradecomandosintegrada,seproduciráunerror.
Comentarios
Siestapropiedadseestableceen-1,elanchodelalistasebasaráenlalongituddelelementomáslargodelalistadelcuadrocombinado.Siestapropiedadseestableceen0,elanchodelalistasebasaráenelanchodelcontrol.
Ejemplo
Esteejemploagregauncontroldecuadrocombinadoalabarradecomandosdenominada"Custom"y,acontinuación,agregadoselementosalalistadelcuadrocombinado.Elejemplotambiénestableceelnúmerodeelementosdelínea,elanchodelcuadrocombinadoyunvalorvacíopredeterminadoparaelcuadrocombinado.
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
Mostrartodo
PropiedadEnabled
Truesiestáhabilitadalabarradecomandosocontroldebarradecomandosespecificados.BooleandeLectura/Escritura.
Comentarios
Parabarrasdecomandos,siseestableceestapropiedadenTrueelnombredelabarraapareceráenlalistadebarrasdecomandosdisponibles.
Paracontrolesintegrados,siestablecelapropiedadEnabledenTruelaaplicacióndeterminasuestado;siseestableceenFalselosdeshabilita.
Ejemplo
Esteejemploajustalasbarrasdecomandosdeacuerdoconelniveldeusuarioespecificadoporuser.Siuseres"Level1,"semuestralabarradecomandosdenominada"VBCustomBar".Siuserescualquierotrovalor,labarradecomandosintegradadeVisualBasicserestableceasuestadopredeterminadoysedeshabilitalabarradecomandosdenominada"VBCustomBar".
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
Esteejemploañadedosbotonesdebarradecomandosalabarradecomandosdenominada"Custom".Deformapredeterminada,elprimercontrolestádeshabilitadoyelsegundohabilitado.
SetmyBar=CommandBars("Custom")
WithmyBar
.Controls.AddType:=msoControlButton,Id:=3
.Controls(1).Enabled=False
.Controls.AddType:=msoControlButton,Id:=3
EndWith
myBar.Visible=True
PropiedadExpireDate
DevuelveunavariableVariantquerepresentalafechaenquecaducalafirmadigitalquecorrespondealobjetoSignature.Esdesólolectura.
expresión.ExpireDate
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentoenWordyejecuteestafunción.Lafunciónrealizarálacomprobaciónparaasegurarsedequelafirmadigitalqueseleccionaelusuarionocaducaantesde12meses.Sicaduca,noseadjuntaelcertificado.
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
PropiedadExtended
Estableceodevuelveatributosagregadosalaetiqueta<SCRIPT>,aexcepcióndelosatributosLANGUAGEeID.StringdeLectura/Escritura.
Comentarios
Losatributosseseparanporespacios,aligualquesucedeenHTML.NopuedepasarelatributoLANGUAGEoelatributoIDutilizandolapropiedadExtended.
LaaplicaciónhostdeMicrosoftOfficenoproporcionaningúnmedioparacomprobarlasintaxisdelosatributospasados.
SipasaelatributoLANGUAGEenlapropiedadExtended,laetiqueta<SCRIPT>recibedosopcionesdeidioma,loqueoriginaunconflicto.
SipasaunatributoIDenlapropiedadExtendedynosehaestablecidoningúnIDatravésdelparámetroIDdelmétodoAddodelapropiedadIddelobjetoScript,elIDseexportarácorrectamente.
Ejemplo
EsteejemplocompruebalapropiedadExtendedparaasegurarsedequenosehanagregadoatributosadicionalesalaprimerasecuenciadecomandosdelahojaunodellibroactivo.
IfActiveWorkbook.Worksheets(1).Scripts(1).Extended_
<>""Then
MsgBox"Thisscriptcontainsextendedattributes."
EndIf
PropiedadExtensions
DevuelveunvalorStringquecontienelasextensionesquedeterminanquéarchivossemuestranenuncuadrodediálogodearchivosparacadaobjetoFilter.Esdesólolectura.
expresión.Extensions
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguienterepitelosfiltrospredeterminadosdelcuadrodediálogoGuardarcomoymuestraladescripcióndelosfiltrosqueincluyecadaarchivodeMicrosoftExcel.LapropiedadExtensionsseutilizaparaencontrarlosobjetosdefiltroapropiados.
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
Mostrartodo
PropiedadFaceId
DevuelveoestableceelnúmerodeId.delaimagendebotónactualmenteasignadaalcontroldebotóndelabarradecomandosespecificada.LongdeLectura/Escritura.
Comentarios
LapropiedadFaceIdindicaelaspecto,nolafunción,deunbotóndelabarradecomandos.LapropiedadIddelobjetoCommandBarControldeterminalafuncióndelbotón.
ElvalordelapropiedadFaceIddeunbotóndelabarradecomandosconunaimagenpersonalizadaes0(cero).
Ejemplo
Esteejemploagregaunbotónaunabarradecomandospersonalizada.HacerclicenestebotónequivaleahacerclicenelcomandoAbrirdelmenúArchivoyaqueelnúmerodeId.es23aunqueelbotóntienelamismaimagenqueelbotónintegradoGráfico.
SetnewBar=CommandBars.Add(Name:="Custom2",_
Position:=msoBarTop,Temporary:=True)
newBar.Visible=True
Setcon=newBar.Controls.Add(Type:=msoControlButton,Id:=23)
con.FaceId=17
PropiedadFeatureTips
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeproporcionainformaciónacercadelautilizacióndelasfuncionesdelaaplicaciónmáseficazmente.BooleandeLectura/Escritura.
Comentarios
LapropiedadFeatureTipssecorrespondeconlaopciónUsomásefectivodelasfuncionesenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaproporcionarinformaciónsobrecómoutilizarlasfuncionesdelaaplicacióndeunamaneramáseficaz.
Assistant.FeatureTips=True
PropiedadFileName
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
ObjetoAssistant:DevuelveoestablecelarutadeaccesoyelnombredelarchivodelAyudantedeOfficeactivo.StringdeLectura/Escritura.
ObjetoFileSearch:Devuelveoestableceelnombredelarchivoquedeseabuscarenunabúsquedadearchivos.Enelnombredelarchivopuedenincluirseloscomodines*(asterisco)o?(signodeinterrogación).Utiliceelcomodíndelsignodeinterrogaciónparaindicarcualquiercaráctersencillo.Porejemplo,escribam?lesparaindicar"males"y"miles".Utiliceelcomodíndelasteriscoparaindicarcualquiernúmerodecaracteres.Porejemplo,escriba*.txtparabuscartodoslosarchivosquetenganextensión.TXT.StringdeLectura/Escritura.
expresión.FileName
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemplobuscalosarchivosubicadosenlacarpetaMyDocumentsqueempiezanporcmdytienenunaextensiónenelnombredelarchivo.Elnombreylaubicacióndelosarchivosencontradossemuestraenelejemplo.
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
PropiedadFiles
DevuelveunacolecciónAnswerWizardFilesquerepresentalalistadearchivosdisponiblesenelAsistenteparaAyudaactual.Esdesólolectura.
Paraobtenermásinformaciónsobrecómodevolverunsolomiembrodeunacolección,veaDevolverunobjetodeunacolección.
Ejemplo
EsteejemplorestablecelalistadearchivosdelAsistenteparaAyudaactualy,acontinuación,muestraelnúmerodearchivosylosnombresdelosarchivosenuncuadrodemensaje.
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
Mostrartodo
PropiedadFileType
Devuelveoestableceeltipodearchivoquebuscarduranteunabúsquedadearchivos.MsoFileTypedeLectura/Escritura.
MsoFileTypepuedeserunadeestasconstantesdeMsoFileType.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeCustommsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFilesmsoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItemmsoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPagesmsoFileTypeWordDocuments
expresión.FileType
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
LaconstantemsoFileTypeOfficeFilesincluyetodoslosarchivosquetienenunadelassiguientesextensiones:*.doc,*.xls,*.ppt,*.pps,*.obd,*.mdb,*.mpd,*.dot,*.xlt,*.pot,*.obt,*.htm,or*.html.
Ejemplo
EsteejemplobuscatodoslosarchivosdeCuadernoubicadosenlacarpetaMyDocuments.Elejemplomuestraenuncuadrodemensajeconelnombreylaubicacióndecadaarchivoencontrado.
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
PropiedadFileTypes
DevuelveunacolecciónFileTypes.
expresión.FileTypes
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientebuscatodoslosarchivosdeMicrosoftExcelyHTMLdelaunidadC:\.
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
PropiedadFilterIndex
DevuelveoestableceunvalorLongqueindicaelfiltrodearchivospredeterminadodeuncuadrodediálogodearchivos.Elfiltropredeterminadodeterminaquétiposdearchivossemuestranalabrirporprimeravezelcuadrodediálogodearchivos.Lectura/Escritura.
expresión.FilterIndex
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
Siintentaestablecerestapropiedadaunnúmerosuperiorqueeldefiltros,seseleccionaráelúltimofiltrodisponible.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.Esteejemplomuestratambiéncómoagregarunfiltrodearchivosnuevoyhacerqueseaelfiltropredeterminado.
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
PropiedadFilters
DevuelveunacolecciónFileDialogFilters.
expresión.Filters
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.Elejemploagregatambiénunfiltrodearchivosnuevodenominado"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
PropiedadFixedWidthFont
Estableceodevuelvelaopcióndefuentedeanchofijoenlaaplicaciónhost.StringdeLectura/Escritura.
Comentarios
CuandoestablecelapropiedadFixedWidthFont,laaplicaciónhostnocompruebasielvaloresválido.
Ejemplo
EsteejemploestablecelafuenteyeltamañodefuentedeanchofijoparaelconjuntodecaracteresInglés/Europeooccidental/Otroalfabetolatinodentrodelaaplicaciónactiva.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFont="System"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFontSize=12
PropiedadFixedWidthFontSize
Estableceodevuelvelaopcióndetamañodefuentedeanchofijoenlaaplicaciónhost,enpuntos.Singledelectura/escritura.
Comentarios
CuandoestablecelapropiedadFixedWidthFontSize,laaplicaciónhostnocompruebasielvaloresválido.Siespecificaunvalornoválido,comopuedeseruncarácternonumérico,laaplicaciónhostestableceráeltamañoen0puntos.Puedeasignarlostamañosdemedioenmediopunto;siinsertaotrasfraccionesdetamañoenpuntos,éstasseredondearánhaciaarribaohaciaabajoalmediopuntomáscercano.
Ejemplo
EsteejemploestablecelafuenteyeltamañodefuentedeanchofijoparaelconjuntodecaracteresInglés/Europeooccidental/Otroalfabetolatinodentrodelaaplicaciónactiva.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFont="System"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.FixedWidthFontSize=12
PropiedadFoundFiles
DevuelveunobjetoFoundFilesquecontienelosnombresdetodoslosarchivosencontradosenlaoperacióndebúsqueda.Esdesólolectura.
Ejemplo
Esteejemplorecorrelalistadearchivosencontradosdurantelabúsquedaymuestralarutadeaccesodecadaarchivo.
WithApplication.FileSearch
Fori=1To.FoundFiles.Count
MsgBox.FoundFiles(i)
NextI
EndWith
PropiedadGuessHelp
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficemuestraunalistadetemasdeAyudarelevantesbasadosenelcontextoenqueseencuentreelusuarioinmediatamenteantesdehacerclicenlaventanadelAyudanteopresionarF1.BooleandeLectura/Escritura.
Comentarios
LapropiedadGuessHelpcorrespondealaopciónSugerirtemasdeAyudadeUtilizarelAyudantedeOfficeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaquesugieratemasdeAyuda.
Assistant.GuessHelp=True
PropiedadGuid
Devuelveelidentificadordeclaseexclusivoglobal(GUID)paraelobjetoCOMAddInespecificado.Stringdesólolectura.
Ejemplo
ElejemplosiguientemuestraenuncuadrodemensajeelProgIDyelGUIDdelcomplementoCOMuno.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
PropiedadHeading
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceelencabezadoqueapareceeneldiálogoAyudantedeOffice.StringdeLectura/Escritura.
Comentarios
Puedeespecificarquesemuestreungráficoeneltítulodeglobodetextoutilizandolasintaxissiguiente:{typelocationsizing_factor},dondetypeesbmp(mapadebits)owmf(metarchivodeWindows),locationeselidentificadorderecursosolarutadeaccesoynombredearchivo,ysizing_factorindicaelanchodelwmf(seomiteparalosbmp).
Eltítulodeglobodetextotambiénadmitetextosubrayadoytextoquetieneaplicadounodelos16coloresdelapaletadelsistema.Paramostrareltextosubrayadodeuntítulo,utilicelasintaxis{ul}o{ul1};utilice{ul0}paradesactivarelsubrayado.Paracambiarelcolordeltextodeltítulo,insertedelantedelacadenadetextolasecuenciadecaracteres{cfnumber},dondenumberesunodeloscoloresdesistemaincluidosenlasiguientetabla.
Númerodecolordelsistema Color0 Negro1 Rojooscuro2 Verdeoscuro3 Amarillooscuro4 Azulmarino5 Púrpura6 Verdeazulado7 Plateado248 Grisclaro249 Rojo250 Verde251 Amarillo252 Azul253 Fucsia254 Aguamarina255 Blanco
Siespecificaunnúmerodistintodelosnúmerosdecolorespecificadosaquí,el
textodeltítuloseránegro.
Ejemplo
Esteejemplocreaundiálogoconencabezado,textoytresopcionesderegióny,acontinuación,lomuestra.
WithAssistant.NewBalloon
.Button=msoButtonSetOkCancel
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
Mostrartodo
PropiedadHeight
Devuelveoestableceelaltodelcontroldelabarradecomandosodelabarradecomandos.LongdeLectura/Escritura.
expresión.Height
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Ejemplo
EsteejemploagregauncontrolpersonalizadoalabarradecomandosdenominadaCustom.Elejemploestableceelaltodelcontrolpersonalizadoeneldobledelaltodelabarradecomandosyestableceelanchodelcontrolen50píxeles.Observecómolabarradecomandoscambiasutamañodeformaautomáticaparaadaptarloalcontrol.
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
Mostrartodo
PropiedadHelpContextId
DevuelveoestableceelidentificadordecontextodeltemadeAyudaadjuntoalcontroldebarradecomandos.LongdeLectura/Escritura.
Comentarios
Parautilizarestapropiedad,tambiéndebeestablecerlapropiedadHelpFile.LostemasdelaAyudaseobtienenpresionandoMayús+F1.
Ejemplo
Esteejemploagregaunabarradecomandospersonalizadaconuncuadrocombinadoquerealizaelseguimientodelosdatosalmacenados.Además,esteejemploespecificaeltemadelaAyudaquesevaamostrarenelcuadrocombinadocuandoelusuariopresionaMAYÚS+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
Mostrartodo
PropiedadHelpFile
DevuelveoestableceelnombredearchivodeltemadeAyudaadjuntoalcontroldebarradecomandos.StringdeLectura/Escritura.
Comentarios
Parautilizarestapropiedad,tambiéndebeestablecerlapropiedadHelpContextID.LostemasdelaAyudaseobtienenpresionandoMAYÚS+F1.
Ejemplo
Esteejemploagregaunabarradecomandospersonalizadaconuncuadrocombinadoquerealizaelseguimientodelosdatosalmacenados.Además,esteejemploespecificaeltemadelaAyudaquesevaamostrarenelcuadrocombinadocuandoelusuariopresionaMAYÚS+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
PropiedadHighPriorityTips
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficemuestrasugerenciasdeprioridadalta.BooleandeLectura/Escritura.
Comentarios
LapropiedadHighPriorityTipscorrespondealaopciónMostrarsólosugerenciasdeprioridadaltadeMostrarsugerenciasacercadeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaquemuestresugerenciasdeprioridadalta.
Assistant.HighPriorityTips=True
PropiedadHTMLProjectItems
DevuelvelacolecciónHTMLProjectItemsqueseincluyeenelproyectoHTMLespecificado.HTMLProjectItemsdesólolectura.
Ejemplo
EsteejemplodevuelveelnúmerodeelementosincluidosenlacolecciónHTMLProjectItemsdelproyectoHTMLdellibroactivo.
intCount=ActiveWorkbook.HTMLProject.HTMLProjectItems.Count
PropiedadHyperlinkType
Estableceodevuelveeltipodehipervínculoasociadoconelbotóndelabarradecomandos.MsoCommandBarButtonHyperlinkTypedeLectura/Escritura.
MsoCommandBarButtonHyperlinkTypepuedeserunadeestasconstantesdeMsoCommandBarButtonHyperlinkType.msoCommandBarButtonHyperlinkInsertPicturemsoCommandBarButtonHyperlinkNonemsoCommandBarButtonHyperlinkOpen
Ejemplo
EsteejemplocompruebalapropiedadHyperlinkTypeparaelbotónespecificadodelabarradecomandosenlabarradecomandosdenominada"Custom".SiHyperlinkTypeseestableceenmsoCommandBarButtonHyperlinkNone,elejemploestablecerálapropiedadenmsoCommandBarButtonHyperlinkOpenylaURLenwww.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
PropiedadIcon
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceeltipodeiconoqueapareceenlapartesuperiorizquierdadelgloboAyudantedeOffice.MsoIconTypedeLectura/Escritura.
MsoIconTypepuedeserunadeestasconstantesdeMsoIconType.msoIconAlertmsoIconAlertCriticalmsoIconAlertInfomsoIconAlertQuerymsoIconAlertWarningmsoIconNonemsoIconTip
Ejemplo
Esteejemplocreaungloboconuniconode"Alerta"queindicaalusuarioqueseleccioneunaimpresora.
WithAssistant.NewBalloon
.Heading="SelectAPrinter"
.Text="Youmustselectaprinterbeforeprinting."
.Icon=msoIconAlert
.CheckBoxes(1).Text="Localprinter"
.CheckBoxes(2).Text="Networkprinter"
.Show
EndWith
Mostrartodo
PropiedadId
PropiedadId,segúnseaplicaalosobjetosCommandBarButton,CommandBarComboBoxyCommandBarControl.
DevuelveelId.parauncontroldelabarradecomandosintegrado.Longdesólolectura.
expresión.Id
expresiónRequerida.Unaexpresiónquedevuelveunodelosobjetosanteriores.
Comentarios
UnId.decontroldeterminalaacciónintegradaparaesecontrol.ElvalordelapropiedadIdparatodosloscontrolespersonalizadoses1.
PropiedadId,segúnseaplicaalobjetoScript.
EstableceodevuelveelIDdeunobjetoScript.StringdeLectura/Escritura.
expresión.Id
expresiónRequerida.ExpresiónquedevuelveunobjetoScript.
Comentarios
ElIDdevueltoeselatributoIDdelaetiqueta<SCRIPT>enHTML.SinosehaespecificadounatributoIDenlaetiqueta<SCRIPT>,lapropiedadIddevolveráunacadenavacía.
IdespecificaunidentificadorSGMLutilizadoparadenominarelementos.Entrelosidentificadoresválidosseincluyecualquiercadenaquecomienceconunaletrayestéconstituidaporcaracteresalfanuméricos;lacadenatambiénpuedeincluirelcarácterdesubrayado(_).
ElIDdebeserúnicodentrodeldocumentoHTML.
Ejemplo
SegúnseaplicaalosobjetosCommandBarButton,CommandBarComboBoxyCommandBarControl.
Esteejemplocambialacaradelbotóndelprimercontrolenlabarradecomandosdenominada"Custom2"sielvalordelId.delbotónesinferiora25.
Setctrl=CommandBars("Custom").Controls(1)
Withctrl
If.Id<25Then
.FaceId=17
.Tag="Changedcontrol"
EndIf
EndWith
Elsiguienteejemplocambiaeltítulodecadacontroldelabarradecomandosdenominada"Standard"alvaloractualdelapropiedadIdparaesecontrol.
ForEachctlInCommandBars("Standard").Controls
ctl.Caption=CStr(ctl.Id)
Nextctl
SegúnseaplicaalobjetoScript.
EsteejemploestableceunnuevovalorparalapropiedadIddelaprimerasecuenciadecomandosdelahojaunodellibroactivo.
ActiveWorkbook.Worksheets(1).Scripts(1).Id="UpdatedScriptName"
PropiedadIndex
DevuelveunvalorLong,querepresentaelnúmerodeíndicedeunobjetodelacolección.Esdesólolectura.
expresión.Index
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
Laposicióndelprimercontroldebarradecomandoses1.LosseparadoresnosecuentanenlacolecciónCommandBarControls.
Ejemplo
Esteejemplobuscaenlabarradecomandosdenominada"Custom2"uncontrolconunnúmerodeId.iguala23.Siseencuentraestecontrolysunúmerodeíndiceesmayorque5,elcontrolsesituaráenprimerlugarenlabarradecomandos.
SetmyBar=CommandBars("Custom2")
Setctrl1=myBar.FindControl(Id:=23)
Ifctrl1.Index>5Then
ctrl1.Movebefore:=1
EndIf
PropiedadInitialFileName
EstableceodevuelveunvalorStringquerepresentalarutadeaccesoy/onombredearchivoquesemuestrainicialmenteenuncuadrodediálogodearchivos.Lectura/Escritura.
expresión.InitialFileName
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
Puedeutilizarloscaracterescomodín'*'(asterisco)e'?'(interrogación)alespecificarelnombredearchivo,peronoalespecificarlarutadeacceso.'*'(asterisco)representacualquiernúmerodecaracteresconsecutivose'?'(interrogación)unsolocarácter.Porejemplo,.InitialFileName="c:\c*s.txt"devolverá"charts.txt"y"checkregister.txt."
Siespecificalarutadeaccesosinelnombredelarchivo,aparecerántodoslosarchivosquepasanelfiltrodearchivosenelcuadrodediálogo.
Siespecificaunarchivoqueseencuentraenlacarpetadeinicio,sóloapareceráestearchivoenelcuadrodediálogo.
Siespecificaunnombredearchivoquenoestáenlacarpetadeinicio,enelcuadrodediálogonoapareceráningúnarchivo.EltipodearchivoqueespecifiqueenlapropiedadInitialFileNamesobrescribirálosvaloresdelfiltrodearchivos.
Siespecificaunarutadeaccesonoválida,seutilizarálaúltimaquehayautilizado.Unmensajeadvertiráalusuariodequesehautilizadounarutadeaccesonoválida.
Siseestableceestapropiedadenunacadenasuperiora256caracteresseproduciráunerrordetiempodeejecución.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
Mostrartodo
PropiedadInitialView
DevuelveoestableceunaconstantedeMsoFileDialogViewquerepresentalapresentacióninicialdearchivosycarpetasenuncuadrodediálogodearchivos.Lectura/Escritura.
MsoFileDialogViewpuedeserunadeestasconstantesdeMsoFileDialogView.msoFileDialogViewDetailsmsoFileDialogViewLargeIconsmsoFileDialogViewListmsoFileDialogViewPreviewmsoFileDialogViewPropertiesmsoFileDialogViewSmallIconsmsoFileDialogViewThumbnailEstaconstantesóloestádisponibleenMicrosoftWindows2000,MicrosoftWindowsMillenniumEditionoposterior.msoFileDialogViewWebViewNodisponible.Siseleccionaestaconstante,seutilizarálavistapredeterminada.
expresión.InitialView
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosenvistadetalladamedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
PropiedadIntroduction
EstableceodevuelveeltextodeintroducciónqueseincluyeenundocumentoenviadoutilizandoelobjetoMsoEnvelope.Eltextodeintroducciónseincluyeenlapartesuperiordeldocumentodecorreoelectrónico.StringdeLectura/Escritura.
expresión.Introduction
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguienteenvíaeldocumentoactivodeMicrosoftWordcomouncorreoelectrónicoaladireccióndecorreoelectrónicoquepasealasubrutina.
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
PropiedadIsCertificateExpired
TruesielcertificadodigitalquecorrespondealobjetoSignaturehacaducado.Booleandesólolectura.
expresión.IsCertificateExpired
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
PropiedadIsCertificateRevoked
TruesielemisordelcertificadodigitalquecorrespondealobjetoSignatureloharevocado.Booleandesólolectura.
expresión.IsCertificateRevoked
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
PropiedadIsOpen
TruesielproyectoHTMLestáabiertoenelEditordesecuenciasdecomandosdeMicrosoft.Booleandesólolectura.
Ejemplo
EsteejemplodeterminasiestáabiertoelelementoespecificadodelproyectoHTML.Siloestá,elejemplocargarálasecuenciadecomandosdelarchivoespecificado.
IfActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).IsOpenThen
ActiveWorkbook.HTMLProject.HTMLProjectItems_
.Item(1).LoadFromFile("C:\MyScript.txt")
Else
MsgBox"TheHTMLProjectItemisnotopen."
EndIf
PropiedadIsPriorityDropped
Truesielcontrolnoseencuentraactualmenteenelmenúoenlabarradeherramientasquesebasaenlasestadísticasdeusoyenladistribucióndelespacio.NótesequenosetratadelomismoquelavisibilidaddecontrolesdefinidaenlapropiedadVisible.UncontrolconlapropiedadVisibleestablecidaenTrue,noestarávisibleinmediatamenteenunmenúpersonalizadoobarradeherramientassiIsPriorityDroppedesTrue.Booleandesólolectura.
Comentarios
ParadeterminarcuándoestablecerIsPriorityDroppedenTrueparaunelementodemenúespecífico,MicrosoftOfficemantieneunrecuentototaldelnúmerodevecesqueseutilizóelelementodemenúyunregistrodelnúmerodediferentessesionesdelaaplicaciónenlasqueelusuarioutilizóotroelementodelmismomenúsinutilizardichoelemento.Cuandoestevaloralcanzadeterminadosvaloresdeumbral,elrecuentodisminuye.Cuandoelrecuentollegaacero,lapropiedadIsPriorityDroppedseestableceenTrue.Losprogramadoresnopuedenestablecerelvalordelasesión,nielvalordelumbral,nilapropiedadIsPriorityDropped.Sinembargo,puedenutilizarlapropiedadAdaptiveMenusparadeshabilitarlosmenúsadaptablesenmenúsespecíficosdeunaaplicación.
ParadeterminarcuándoestablecerIsPriorityDroppedenTrueparauncontrolespecíficodeunabarradeherramientas,Officemantieneunalistadelordenenqueseejecutaronporúltimavezloscontrolesdeesabarradeherramientas.Unabarradeherramientasmostrarátantoscontrolescomotengaespacioparamostrar,comenzandoporelqueseutilizóporúltimavezhastaelqueseutilizómenosrecientemente.LoscontrolesquetenganlapropiedadPriorityestablecidaen1semostraránsiempreylabarradeherramientasajustarálasfilas,encasonecesario,paramostrarestoscontroles.LosprogramadorespuedenutilizarlapropiedadPriorityparaquesemuestrensiempredeterminadoscontrolesdeunabarradeherramientasoparavolveracolocarbarrasdeherramientas,demodoquehayaespaciosuficienteparamostrartodosloscontroles.
PuedeutilizarlasiguientetablaparapredecirelnúmerodesesionesdurantelasqueunelementodemenúdeunmenúpersonalizadoquedarávisibleantesdequelapropiedadIsPriorityDroppeddelmismoseestablezcaenTrue.
Númerodevecesdeutilizacióndelcontroldelabarradecomandos Númerodesesionesdelaaplicación
0,1 32 63 94,5 12
6-8 179-13 2314-24 2925omás 31
Ejemplo
EsteejemplocompruebalapropiedadIsPriorityDroppedparaelprimercontroldelabarradecomandosdenominada"Custom".SiIsPriorityDroppedesTrue,elejemploestablecelapropiedadAdaptiveMenusenFalse,restaurandolabarradecomandosperdida.
IfCommandBars("Custom").Controls(1).IsPriorityDroppedThen
CommandBars.AdaptiveMenus=True
EndIf
PropiedadIssuer
DevuelveunvalorStringquerepresentaelnombredelemisordelcertificadodigitalquecorrespondealobjetoSignature.Esdesólolectura.
expresión.Issuer
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
PropiedadIsValid
TruesielcertificadodigitalquecorrespondealobjetoSignatureesválido.Uncertificadopuedenoserválidopordiferentesmotivos:desdehabercaducadohastahaberseproducidocambioseneldocumentoquelocontiene.Booleandesólolectura.
expresión.IsValid
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
Mostrartodo
PropiedadItem
PropiedadItemcuandoseaplicaalacolecciónFileTypes.
DevuelveunvalorqueindicaeltipodearchivoquesebuscarámedianteelmétodoExecutedelobjetoFileSearch.MsoFileTypedesólolectura.
MsoFileTypepuedeserunadeestasconstantesdeMsoFileType.msoFileTypeAllFilesmsoFileTypeBindersmsoFileTypeCalendarItemmsoFileTypeContactItemmsoFileTypeDatabasesmsoFileTypeDataConnectionFilesmsoFileTypeDesignerFilesmsoFileTypeDocumentImagingFilesmsoFileTypeExcelWorkbooksmsoFileTypeJournalItemmsoFileTypeMailItemmsoFileTypeNoteItemmsoFileTypeOfficeFilesmsoFileTypeOutlookItemsmsoFileTypePhotoDrawFilesmsoFileTypePowerPointPresentationsmsoFileTypeProjectFilesmsoFileTypePublisherFilesmsoFileTypeTaskItemmsoFileTypeTemplatesmsoFileTypeVisioFilesmsoFileTypeWebPages
msoFileTypeWordDocuments
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunacolecciónFileTypes.
IndexLongrequerido.Númerodeíndicedelobjetoquesevaadevolver.
PropiedadItemcuandoseaplicaalobjetoCommandBars.
DevuelveunobjetoCommandBardelacolecciónCommandBars.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBars.
IndexVariantrequerido.Nombreonúmerodeíndicedelobjetoquesevaadevolver.
PropiedadItemcuandoseaplicaalobjetoCommandBarControls.
DevuelveunobjetoCommandBarControldelacolecciónCommandBarControls.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarControls.
IndexVariantrequerido.Nombreonúmerodeíndicedelobjetoquesevaadevolver.
PropiedadItemcuandoseaplicaalobjetoDocumentProperties.
DevuelveunobjetoDocumentPropertydelacolecciónDocumentProperties.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoDocumentProperties.
IndexVariantrequerido.Nombreonúmerodeíndicedelapropiedadde
documentoquesevaadevolver.
PropiedadItemcuandoseaplicaalosobjetosBalloonCheckboxesyBalloonLabels.
DevuelveunobjetoBalloonCheckBoxoBalloonLabel.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.Númerodeíndicedelacasilladeverificaciónorótuloquesevaadevolver.
PropiedadItemcuandoseaplicaalobjetoMsoEnvelope.
DevuelveunobjetoMailItemquepuedeutilizarseparaenviareldocumentocomouncorreoelectrónico.
expresión.Item
expresiónRequerida.ExpresiónquedevuelveunobjetoMsoEnvelope.
PropiedadItemcuandoseaplicaalobjetoPropertyTests.
DevuelveunobjetoPropertyTestdelacolecciónPropertyTests.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoPropertyTests.
IndexLongrequerido.Númerodeíndicedelapruebadepropiedadquesevaadevolver.
PropiedadItemcuandoseaplicaalosobjetosScopeFoldersySearchFolders.
DevuelveunobjetoScopeFolderquerepresentaunasubcarpetadelobjetoprimario.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.Determinaquésubcarpetadevuelve.
PropiedadItemcuandoseaplicaalobjetoSearchScopes.
DevuelveunobjetoSearchScopequecorrespondealáreaenqueserealizarálabúsquedadearchivos,comolasunidadeslocalesolascarpetasdeMicrosoftOutlook.
expresión.Item(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoSearchScopes.
IndexLongrequerido.DeterminaquéobjetoSearchScopedevuelve.
PropiedadItemcuandoseaplicaalobjetoSignatureSet.
DevuelveunobjetoSignaturequecorrespondealdelasfirmasdigitalesconlasqueestáfirmadoeldocumentoactualmente.
expresión.Item(iSig)
expresiónRequerida.ExpresiónquedevuelveunobjetoSignatureSet.
iSigLongrequerido.DeterminaquéobjetoSignaturedevuelve.
PropiedadItemcuandoseaplicaalosobjetosAnswerWizardFilesyFoundFiles.
DevuelveunacadenadenombresdearchivodeunacolecciónAnswerWizardFilesounnombredearchivodelalistadenombresdearchivoquerepresentaelobjetoFoundFiles,respectivamente.Stringdesólolectura.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexLongrequerido.NúmerodeíndicedelacadenadenombredearchivodelAsistenteparaAyudaoelnombredelarchivoquedevuelve.
PropiedadItemcuandoseaplicaalosobjetosAssistant,BalloonCheckbox,BalloonLabelyFileDialog.
Devuelveeltextoasociadoalobjetoespecificado.Stringdesólolectura.
expresión.Item
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
PropiedadItemcuandoseaplicaalobjetoWebPageFonts.
DevuelveunobjetoWebPageFontdelacolecciónWebPageFontsparaunvalordeterminadodeMsoCharacterSet.
expresión.Item(Index)
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
IndexMsoCharacterSetrequerido.Eljuegodecaracteresespecificado.
MsoCharacterSetpuedeserunadeestasconstantesdeMsoCharacterSet.msoCharacterSetArabicmsoCharacterSetCyrillicmsoCharacterSetEnglishWesternEuropeanOtherLatinScriptmsoCharacterSetGreekmsoCharacterSetHebrewmsoCharacterSetJapanesemsoCharacterSetKoreanmsoCharacterSetMultilingualUnicodemsoCharacterSetSimplifiedChinesemsoCharacterSetThaimsoCharacterSetTraditionalChinesemsoCharacterSetVietnamese
Ejemplo
CuandoseaplicaalobjetoCommandBars.
Itemeselmiembropredeterminadodelobjetoocolección.LasdossiguientesinstruccionesasignanunobjetoCommandBaracmdBar.
SetcmdBar=CommandBars.Item("Standard")
SetcmdBar=CommandBars("Standard")
CuandoseaplicaalosobjetosBalloonCheckboxesyBalloonLabels.
Itemeselmiembropredeterminadodelobjetoocolección.LasdosinstruccionessiguientesasignanalblTexteltextodelprimerrótulodelobjetoBalloonasignadoamyBalloon.
lblText=myBalloon.Labels(1).Item
lblText=myBalloon.Labels(1)
CuandoseaplicaalosobjetosAnswerWizardFilesyFoundFiles.
EsteejemplorestablecelalistadearchivosdelAsistenteparaAyudaactualymuestraelnúmerodearchivosylosnombresdelosmismosenuncuadrodemensaje,utilizandolapropiedadItemparadevolverlosnombresdearchivo.
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
CuandoseaplicaalobjetoWebPageFonts.
ElejemplosiguienteutilizalapropiedadItemparaestablecermyFontenelobjetoWebPageFontdeljuegodecaracteresInglés/Europeooccidental/Otroalfabetolatinoenlaaplicaciónactiva.
DimmyFontAsWebPageFont
SetmyFont=_
Application.DefaultWebOptions.Fonts._
Item(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)
CuandoseaplicaalobjetoMsoEnvelope.
ElejemplosiguienteenvíaeldocumentoactivodeMicrosoftWordcomouncorreoelectrónicoaladireccióndecorreoelectrónicoquepasealasubrutina.
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
PropiedadKeyboardShortcutTips
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeproporcionainformacióndeAyudaacercadelosmétodosabreviadosdelteclado.BooleandeLectura/Escritura.
Comentarios
LapropiedadKeyboardShortcutTipscorrespondealaopciónMétodosabreviadosdeMostrarsugerenciasacercadeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaqueofrezcainformacióndeAyudaacercadelasteclasdemétodoabreviado.
Assistant.KeyboardShortcutTips=True
PropiedadLabels
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveunacolecciónBalloonLabelsquerepresentatodoslosrótulosdebotones,rótulosdenúmerosyrótulosdeviñetascontenidosenelgloboAyudantedeOfficeespecificado.Esdesólolectura.
Paraobtenermásinformaciónacercadecómodevolverunsolomiembrodeunacolección,veaDevolverunobjetodeunacolección.
Ejemplo
Esteejemplocreaungloboquecontienetresopciones.LavariablexseconfiguracomoelvalordevueltoporelmétodoShow,queserá1,2ó3segúnelrótuloseleccionadoporelusuario.Enelejemplo,uncuadrodemensajemuestraelvalordelavariablex,peropuedepasarelvaloraotroprocedimientoopuedeutilizarloenunainstrucciónSelectCase.
Setb=Assistant.NewBalloon
Withb
.Heading="Thisismyheading"
.Text="Selectoneofthesethings:"
.Labels(1).Text="ChoiceOne"
.Labels(2).Text="ChoiceTwo"
.Labels(3).Text="ChoiceThree"
x=.Show
EndWith
MsgBoxx
PropiedadLanguage
Especificaodevuelveelidiomadelasecuenciadecomandosactiva.MsoScriptLanguagedeLectura/Escritura.
MsoScriptLanguagepuedeserunadeestasconstantesdeMsoScriptLanguage.msoScriptLanguageASPmsoScriptLanguageJavamsoScriptLanguageOthermsoScriptLanguageVisualBasic
Comentarios
LasconstantesMsoScriptLanguageutilizadasconlapropiedadLanguagetambiénseutilizanenelparámetroLanguagedelmétodoAdddelacolecciónScripts.
Ejemplo
EsteejemplocompruebalapropiedadLanguageparaasegurarsedequelaprimerasecuenciadecaracteresdelahojaunodellibroactivoestáescritaenVBScript.
IfActiveWorkbook.Worksheets(1).Scripts(1).Language<>_
msoScriptLanguageVisualBasicThen
MsgBox"LanguageisnotsettoVBScript."
EndIf
PropiedadLanguageID
Devuelveelidentificadorlocal(LCID)dellenguajedeinstalación,delidiomadelainterfazdeusuarioodelidiomadelaAyuda.Longdesólolectura.
expresión.LanguageID(Id)
expresiónRequerida.ExpresiónquedevuelveunobjetoLanguageSettings.
IdMsoAppLanguageIDRequerida.
ConstanteMsoAppLanguageID Significado
msoLanguageIDExeMode
Elmododeidiomaqueestáutilizandolaaplicación.EstaopciónseaplicasóloaMicrosoftExcelyMicrosoftAccess.Estaopciónafectaalosidiomassequepuedenmostraryeditar,asícomoalascaracterísticasespecíficasdeidiomadisponibles,elestilodelosnúmeros,lasopcionesdemoneda,etc.
SinoseutilizaningunodelosidiomasadmitidosenExcelyAccess,laaplicaciónhostnoseconfiguraráparaadmitirlosidiomasorientalesdeescrituradederechaaizquierda.Losidiomasadmitidossonlossiguientes:
Árabe
Chinosimplificado
Chinotradicional
Coreano
Hebreo
Japonés
Persa
Urdu
Yiddish
msoLanguageIDHelp IdiomautilizadoparalaAyudaenpantalla.
msoLanguageIDInstall
OpcionesdeidiomautilizadasporMicrosoftOfficeparaconfigurarlosvalorespredeterminados.Porejemplo,MicrosoftWordutilizaestaopciónparadeterminareldiseñodelasbarrasdeherramientasylostipospredeterminadosdeviñetasynúmerosbasadosencadaidioma.
msoLanguageIDUI Idiomautilizadoporlainterfazdeusuariodelaaplicaciónhost.
msoLanguageIDUIPrevious
Opcióndeidiomadelainterfazdeusuarioenelmomentoenelqueelequiposereinicióporúltimavez.Unprogramaocomplementopuedeutilizarestoparadeterminarsihacambiadoelidiomadelainterfazdeusuario.
Ejemplo
EsteejemplodeMicrosoftExcelcompruebalasopcionesdelapropiedadLanguageIDparalainterfazdeusuario,asícomoelmododeejecuciónparaverificarqueestánestablecidosenelmismoLCID.Elejemplodevolveráunerrorsiencuentraunadiscrepancia.
IfApplication.LanguageSettings.LanguageID(msoLanguageIDExeMode)_
<>Application.LanguageSettings.LanguageID(msoLanguageIDUI)_
ThenMsgBox"Theuserinterfacelanguageandexecution"&_
"modearedifferent."
PropiedadLanguagePreferredForEditing
DevuelveTruesisehamodificadoelvalordelaconstantemsoLanguageIDenelregistrodeWindowscomoidiomapreferidoparaedición.Booleandesólolectura.
expresión.LanguagePreferredForEditing(lid)
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
lidMsoLanguageIDRequerida.
MsoLanguageIDpuedeserunadeestasconstantesdeMsoLanguageID.msoLanguageIDAfrikaansmsoLanguageIDAlbanianmsoLanguageIDAmharicmsoLanguageIDArabicmsoLanguageIDArabicAlgeriamsoLanguageIDArabicBahrainmsoLanguageIDArabicEgyptmsoLanguageIDArabicIraqmsoLanguageIDArabicJordanmsoLanguageIDArabicKuwaitmsoLanguageIDArabicLebanonmsoLanguageIDArabicLibyamsoLanguageIDArabicMoroccomsoLanguageIDArabicOmanmsoLanguageIDArabicQatarmsoLanguageIDArabicSyria
msoLanguageIDArabicTunisiamsoLanguageIDArabicUAEmsoLanguageIDArabicYemenmsoLanguageIDArmenianmsoLanguageIDAssamesemsoLanguageIDAzeriCyrillicmsoLanguageIDAzeriLatinmsoLanguageIDBasquemsoLanguageIDBelgianDutchmsoLanguageIDBelgianFrenchmsoLanguageIDBengalimsoLanguageIDBrazilianPortuguesemsoLanguageIDBulgarianmsoLanguageIDBurmesemsoLanguageIDByelorussianmsoLanguageIDCatalanmsoLanguageIDCherokeemsoLanguageIDChineseHongKongmsoLanguageIDChineseMacaomsoLanguageIDChineseSingaporemsoLanguageIDCroatianmsoLanguageIDCzechmsoLanguageIDDanishmsoLanguageIDDutchmsoLanguageIDEnglishAUSmsoLanguageIDEnglishBelizemsoLanguageIDEnglishCanadianmsoLanguageIDEnglishCaribbeanmsoLanguageIDEnglishIrelandmsoLanguageIDEnglishJamaicamsoLanguageIDEnglishNewZealandmsoLanguageIDEnglishPhilippinesmsoLanguageIDEnglishSouthAfrica
msoLanguageIDEnglishTrinidadmsoLanguageIDEnglishUKmsoLanguageIDEnglishUSmsoLanguageIDEnglishZimbabwemsoLanguageIDEstonianmsoLanguageIDFaeroesemsoLanguageIDFarsimsoLanguageIDFinnishmsoLanguageIDFrenchmsoLanguageIDFrenchCameroonmsoLanguageIDFrenchCanadianmsoLanguageIDFrenchCotedIvoiremsoLanguageIDFrenchLuxembourgmsoLanguageIDFrenchMalimsoLanguageIDFrenchMonacomsoLanguageIDFrenchReunionmsoLanguageIDFrenchSenegalmsoLanguageIDFrenchWestIndiesmsoLanguageIDFrenchZairemsoLanguageIDFrisianNetherlandsmsoLanguageIDGaelicIrelandmsoLanguageIDGaelicScotlandmsoLanguageIDGalicianmsoLanguageIDGeorgianmsoLanguageIDGermanmsoLanguageIDGermanAustriamsoLanguageIDGermanLiechtensteinmsoLanguageIDGermanLuxembourgmsoLanguageIDGreekmsoLanguageIDGujaratimsoLanguageIDHebrewmsoLanguageIDHindimsoLanguageIDHungarian
msoLanguageIDIcelandicmsoLanguageIDIndonesianmsoLanguageIDInuktitutmsoLanguageIDItalianmsoLanguageIDJapanesemsoLanguageIDKannadamsoLanguageIDKashmirimsoLanguageIDKazakhmsoLanguageIDKhmermsoLanguageIDKirghizmsoLanguageIDKonkanimsoLanguageIDKoreanmsoLanguageIDLaomsoLanguageIDLatvianmsoLanguageIDLithuanianmsoLanguageIDMacedonianmsoLanguageIDMalayalammsoLanguageIDMalayBruneiDarussalammsoLanguageIDMalaysianmsoLanguageIDMaltesemsoLanguageIDManipurimsoLanguageIDMarathimsoLanguageIDMexicanSpanishmsoLanguageIDMixedmsoLanguageIDMongolianmsoLanguageIDNepalimsoLanguageIDNonemsoLanguageIDNoProofingmsoLanguageIDNorwegianBokmolmsoLanguageIDNorwegianNynorskmsoLanguageIDOriyamsoLanguageIDOromomsoLanguageIDPolish
msoLanguageIDPortuguesemsoLanguageIDPunjabimsoLanguageIDRhaetoRomanicmsoLanguageIDRomanianmsoLanguageIDRomanianMoldovamsoLanguageIDRussianmsoLanguageIDRussianMoldovamsoLanguageIDSamiLappishmsoLanguageIDSanskritmsoLanguageIDSerbianCyrillicmsoLanguageIDSerbianLatinmsoLanguageIDSesothomsoLanguageIDSimplifiedChinesemsoLanguageIDSindhimsoLanguageIDSlovakmsoLanguageIDSlovenianmsoLanguageIDSorbianmsoLanguageIDSpanishmsoLanguageIDSpanishArgentinamsoLanguageIDSpanishBoliviamsoLanguageIDSpanishChilemsoLanguageIDSpanishColombiamsoLanguageIDSpanishCostaRicamsoLanguageIDSpanishDominicanRepublicmsoLanguageIDSpanishEcuadormsoLanguageIDSpanishElSalvadormsoLanguageIDSpanishGuatemalamsoLanguageIDSpanishHondurasmsoLanguageIDSpanishModernSortmsoLanguageIDSpanishNicaraguamsoLanguageIDSpanishPanamamsoLanguageIDSpanishParaguaymsoLanguageIDSpanishPeru
msoLanguageIDSpanishPuertoRicomsoLanguageIDSpanishUruguaymsoLanguageIDSpanishVenezuelamsoLanguageIDSutumsoLanguageIDSwahilimsoLanguageIDSwedishmsoLanguageIDSwedishFinlandmsoLanguageIDSwissFrenchmsoLanguageIDSwissGermanmsoLanguageIDSwissItalianmsoLanguageIDTajikmsoLanguageIDTamilmsoLanguageIDTatarmsoLanguageIDTelugumsoLanguageIDThaimsoLanguageIDTibetanmsoLanguageIDTigrignaEritreamsoLanguageIDTigrignaEthiopicmsoLanguageIDTraditionalChinesemsoLanguageIDTsongamsoLanguageIDTswanamsoLanguageIDTurkishmsoLanguageIDTurkmenmsoLanguageIDUkrainianmsoLanguageIDUrdumsoLanguageIDUzbekCyrillicmsoLanguageIDUzbekLatinmsoLanguageIDVendamsoLanguageIDVietnamesemsoLanguageIDWelshmsoLanguageIDXhosamsoLanguageIDZulu
Comentarios
DebecomprobartodoslosvaloresmsoLanguageIDválidosparaenumerarelconjuntodeidiomaspreferidos.
Ejemplo
EsteejemplomuestraunmensajesielidiomapreferidoparaediciónesInglés(EstadosUnidos).
IfApplication.LanguageSettings._
LanguagePreferredForEditing(msoLanguageIDEnglishUS)Then
MsgBox"OneofthepreferrededitinglanguagesisUSEnglish."
EndIf
PropiedadLargeButtons
Truesisemuestranbotonesgrandesenlabarradeherramientas.BooleandeLectura/Escritura.
Ejemplo
Esteejemploalternaeltamañodepresentacióndelosbotonesdelabarradeherramientasentodaslasbarrasdecomandos.
SetallBars=CommandBars
IfallBars.LargeButtonsThen
allBars.LargeButtons=False
Else
allBars.LargeButtons=True
EndIf
PropiedadLastModified
Devuelveoestableceunaconstantequerepresentaeltiempotranscurridodesdelaúltimavezquesemodificóyguardóelarchivo.ElvalorpredeterminadoesmsoLastModifiedAnyTime.MsoLastModifieddeLectura/Escritura.
MsoLastModifiedpuedeserunadeestasconstantesdeMsoLastModified.msoLastModifiedAnyTimemsoLastModifiedLastMonthmsoLastModifiedLastWeekmsoLastModifiedThisMonthmsoLastModifiedThisWeekmsoLastModifiedTodaymsoLastModifiedYesterday
Ejemplo
Esteejemploestablecelasopcionesparalabúsquedadeunarchivo.LosarchivosquedevolveráestabúsquedahansidopreviamentemodificadosyestánubicadosenlacarpetaC:\Misdocumentosoenunasubcarpetadeésta.
Setfs=Application.FileSearch
Withfs
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.LastModified=msoLastModifiedYesterday
EndWith
Mostrartodo
PropiedadLeft
Puedequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
PropiedadLeftcuandoseaplicaalosobjetosAssistantyCommandBar.
EstableceodevuelvelaposiciónhorizontaldelaventanadelAyudantedeOffice,enpuntos,oladistancia,enpuntos,delabarradecomandos,desdeelbordeizquierdodelobjetoespecificadoconrelaciónalapantalla.LongdeLectura/Escritura.
expresión.Left
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
PropiedadLeftcuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
Estableceodevuelvelaposiciónhorizontaldelcontroldelabarradecomandosespecificado,enpíxeles,conrelaciónalbordeizquierdodelapantalla.Devuelveladistanciadesdeelladoizquierdodeláreadeacoplamiento.Longdesólolectura.
expresión.Left
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Ejemplo
CuandoseaplicaalosobjetosAssistantyCommandBar.
EsteejemplomuestraelAyudantedeOfficeylomuevealaposiciónespecificadadentrodelaventanadelaaplicación.
WithAssistant
.Visible=True
.Left=300
.Top=300
EndWith
EsteejemplomuevelabarradecomandospersonalizadadenominadaCustomdesuposiciónacopladaalolargodelapartesuperiordelaventanahastalaesquinaizquierdadelamisma.
SetmyBar=CommandBars("Custom")
WithmyBar
.Position=1
.RowIndex=2
.Left=0
EndWith
PropiedadLinkSource
Devuelveoestableceelorigendelapropiedaddedocumentopersonalizadavinculadaespecificada.StringdeLectura/Escritura.
Comentarios
Estapropiedadseaplicasóloapropiedadesdedocumentopersonalizadas;nopuedeutilizarseenpropiedadesdedocumentointegradas.
Elorigendelvínculoespecificadoestádefinidoporlaaplicacióncontenedora.
AlestablecerlapropiedadLinkSource,lapropiedadLinkToContentseestableceenTrue.
Ejemplo
Esteejemplomuestraelestadovinculadodeunapropiedaddedocumentopersonalizada.Paraqueelejemplofuncione,dpdebeserunobjetoDocumentPropertyválido.
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
PropiedadLinkToContent
Truesielvalordelapropiedaddedocumentopersonalizadaespecificadaestávinculadoalcontenidodeldocumentocontenedor.Falsesielvaloresestático.BooleandeLectura/Escritura.
Comentarios
Estapropiedadseaplicasóloapropiedadesdedocumentopersonalizadas.Parapropiedadesdedocumentointegradas,estapropiedadessiempreFalse.
UtilicelapropiedadLinkSourceparaestablecerelorigendelapropiedadvinculadaespecificada.AlestablecerlapropiedadLinkSource,lapropiedadLinkToContentseestableceenTrue.
Ejemplo
Esteejemplomuestraelestadovinculadodelapropiedaddedocumentoactual.Paraqueelejemplofuncione,dpdebeserunobjetoDocumentPropertyválido.
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
Mostrartodo
PropiedadList
Devuelveoestableceelvalordeunelementodelistadelcontroldecuadrocombinadodelabarradecomandos.StringdeLectura/Escritura.
NotaEstapropiedadessólodelecturaparacontrolesdecuadrocombinadointegrados.
expresión.List(Index)
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarComboBox.
IndexLongRequerida.Elementodelistaquesevaaestablecer.
Ejemplo
Esteejemplocompruebaelvalordelcuartoelementodelistadelcontroldecuadrocombinadocuyotítuloes"StockData"enlabarradecomandosdenominada"Custom".Sielvalornoes"ViewNews",elejemplomuestraunmensajequeadviertealusuarioqueelcuadrocombinadopuedeestardañadoysolicitándolequevuelvaainstalarlaaplicación.
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
Mostrartodo
PropiedadListCount
Devuelveelnúmerodeelementosdelistadelcontroldecuadrocombinadodelabarradecomandos.Longdesólolectura.
Ejemplo
Esteejemplocompruebaelnúmerodeelementosdelcuadrocombinadoenlabarradecomandosdenominada"Custom".Sinohaytreselementosenlalistaproducidosporelprocedimiento,elejemplomuestraunmensajequeadviertealusuarioqueelcuadrocombinadopuederesultardañadoysolicitándolequevuelvaainstalarlaaplicación.
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
Mostrartodo
PropiedadListHeaderCount
Devuelveoestableceelnúmerodeelementosdelistadelcontroldecuadrocombinadodelabarradecomandosqueapareceencimadelalíneaseparadora.LongdeLectura/Escritura.
NotaEstapropiedadessólodelecturaparacontrolesdecuadrocombinadointegrados.
Comentarios
SilapropiedadListHeaderCounttienevalor-1indicaquenohaylíneaseparadoraenelcontroldecuadrocombinado.
Ejemplo
Esteejemploagregauncontroldecuadrocombinadoalabarradecomandosdenominada"Custom"y,acontinuación,agregadoselementosalcuadrocombinado.ElejemploutilizalapropiedadListHeaderCountparamostrarunalíneadeseparaciónentreelprimerelementoyelsegundoelementoenelcuadrocombinado.Elejemplotambiénestableceelnúmerodeelementosdelínea,elanchodelcuadrocombinadoyunvalorvacíopredeterminadoparaelcuadrocombinado.
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
Mostrartodo
PropiedadListIndex
Devuelveoestableceelnúmerodeíndiceelelementoseleccionadoenlalistadelcontroldecuadrocombinadodelabarradecomandos.Sinoseseleccionaningúnelementodelalista,estapropiedaddevuelvecero.LongdeLectura/Escritura.
NotaEstapropiedadfallacuandoseaplicaacontrolesquenoseancontrolesdelista.
Comentarios
AlestablecerlapropiedadListIndexelcontrolespecificadoseleccionaelelementodadoyejecutalaacciónapropiadaenlaaplicación.
Ejemplo
EsteejemploutilizalapropiedadListIndexparadeterminarlasubrutinacorrectaquesedebeejecutar,apartirdelaseleccióndelcuadrocombinadoenlabarradecomandosdenominada"MyCustomBar".ComoelprocedimientoutilizaListIndex,eltextodelcuadrocombinadopuedesercualquiertexto.
SubprocessSelection()
DimuserChoiceAsLong
userChoice=CommandBars("MyCustomBar").Controls(1).ListIndex
SelectCaseuserChoice
Case1
chartcourse
Case2
displaygraph
CaseElse
MsgBox("Invalidchoice.Pleasechooseagain.")
EndSelect
EndSub
PropiedadLocation
DevuelvelaubicacióndeldelimitadordelasecuenciadecomandosdentrodeldocumentoHTMLespecificado.MsoScriptLocationdesólolectura.
MsoScriptLocationpuedeserunadeestasconstantesdeMsoScriptLocation.msoScriptLocationInBodymsoScriptLocationInHead
Comentarios
LasetiquetasdelassecuenciasdecomandosdeundocumentoHTMLpuedenaparecerencualquierlugarentrelasetiquetas<HTML>deldocumento.EnMicrosoftWord,ExceloPowerPoint,sólosevenlosdelimitadoresdesecuenciasdecomandossituadosentrelasetiquetas<BODY>.LasecuenciadecomandosHTMLadicionalqueapareceantesodespuésdelasetiquetas<BODY>quedaalmacenada,peroelusuarionopuedeverla.
LacolecciónScriptscontienetodoslosdelimitadoresdesecuenciasdecomandosqueapareceneneldocumento,independientementedesiestándentroofueradeltextoprincipal.UtilizandoelargumentoLocationdelmétodoAdd,puedeinsertarlosdelimitadoresdesecuenciasdecomandosdentrodelasetiquetas<HEAD>y<BODY>deldocumentoHTML.TambiénpuedeutilizarlapropiedadLocationparadeterminarellugarenelquedebealmacenarseundelimitadordesecuenciasdecomandosdeterminadodentrodeldocumento.
Ejemplo
EsteejemplocompruebalapropiedadLocationdelaprimerasecuenciadecomandosdelahojadellibroactivoymuestralaubicaciónenuncuadrodemensaje.
IfActiveWorkbook.Worksheets(1).Scripts(1).Location=1Then
MsgBox"Thescriptinlocatedintheheader."
EndIf
IfActiveWorkbook.Worksheets(1).Scripts(1).Location=2Then
MsgBox"Thescriptinlocatedinthebodyoftheworksheet."
EndIf
PropiedadLookIn
Devuelveoestablecelacarpetaenquesebuscarádurantelabúsquedadearchivosespecificada.StringdeLectura/Escritura.
Ejemplo
EsteejemplobuscaenlascarpetasdeMyDocumentstodoslosarchivoscuyosnombrescomiencencon"Cmd"ymuestraelnombreyubicacióndecadaarchivoencontrado.
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
PropiedadMask
DevuelveunobjetoIPictureDispquerepresentalaimagendemáscaradeunobjetoCommandBarButton.Laimagendemáscaradeterminaquépartesdelaimagendelbotónsontransparentes.
expresión.Mask
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarButton.
Comentarios
Alcrearunaimagenparautilizarcomoimagendemáscara,lasáreasquedeseequeseantransparentesdeberánserblancasylasquedeseemostrar,negras.
ConfiguresiemprelamáscaradespuésdeestablecerlaimagenparaelobjetoCommandBarButton.
Ejemplo
ElejemplosiguienteestablecelaimagenylamáscaradelprimerCommandBarButtonquedevuelveelcódigo.Pararealizarestetrabajo,creeunaimagendemáscarayunaimagendebotónysustituyalasrutasdeaccesodelejemploporlasrutasdeaccesoalasimágenes.
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=picButton
'Usethesecondimagetodefinetheareaofthe
'buttonthatshouldbetransparent.
.Mask=picMask
EndWith
EndSub
ElejemplosiguienteobtienelaimagenylamáscaradelprimerCommandBarButtonquedevuelveelcódigoyenvíacadaunaaunarchivo.Pararealizarestetrabajo,especifiqueunarutadeaccesoalosarchivosdesalida.
SubGetButtonImageAndMask()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
WithApplication.CommandBars.FindControl(msoControlButton)
'GetthebuttonimageandmaskofthethisCommandBarButtonobject
SetpicPicture=.Picture
SetpicMask=.Mask
EndWith
'Savethebuttonimageandmaskinafolder.
stdole.SavePicturepicPicture,"c:\temp\image.bmp"
stdole.SavePicturepicMask,"c:\temp\mask.bmp"
EndSub
PropiedadMatchAllWordForms
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Truesielarchivodebúsquedaespecificadoseamplíaparaqueincluyatodaslasformasdelapalabraespecificadaqueaparezcaneneltextooenlaspropiedadesdelarchivo.BooleandeLectura/Escritura.
Comentarios
EstapropiedadsóloestádisponiblesisehainstaladoyregistradoelarchivoMswds_en.lex.Observequeestearchivonoseinstalaconlaconfiguracióntípica.
Ejemplo
Esteejemplodevuelvetodoslosarchivosquecontienenlapalabra"run","running","runs"o"ran"eneltextooenlaspropiedadesdelarchivo.LapropiedadTextOrPropertyestablecelapalabradecomparaciónylimitalabúsquedaaltextoobienalaspropiedadesdelarchivo.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.TextOrProperty="run"
.MatchAllWordForms=True
.FileType=msoFileTypeAllFiles
EndWith
PropiedadMatchTextExactly
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Truesilabúsquedadearchivosespecificadasólobuscaarchivoscuyotextoopropiedadescontenganlapalabraofraseexactaespecificada.BooleandeLectura/Escritura.
Ejemplo
EsteejemplobuscaenlacarpetaC:\MisDocumentosydevuelvetodoslosarchivosquecontienenlapalabra"Run"eneltextooenlaspropiedadesdelarchivo.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.TextOrProperty="Run"
.MatchTextExactly=True
.FileType=msoFileTypeAllFiles
EndWith
Mostrartodo
PropiedadMenuAnimationStyle
Devuelveoestablecelamaneraenqueseanimalabarradecomandos.MsoMenuAnimationdeLectura/Escritura.
MsoMenuAnimationpuedeserunadeestasconstantesdeMsoMenuAnimation.msoMenuAnimationNonemsoMenuAnimationRandommsoMenuAnimationSlidemsoMenuAnimationUnfold
Example
EsteejemploestablecelasopcionesdetodaslasbarrasdecomandosdeMicrosoftOffice.
WithCommandBars
.LargeButtons=True
.DisplayTooltips=True
.DisplayKeysInTooltips=True
.MenuAnimationStyle=msoMenuAnimationUnfold
EndWith
PropiedadMode
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceelcomportamientomodaldelgloboAyudantedeOffice.AlcrearunobjetoBalloon,estapropiedadestáinicialmenteestablecidaenmsoModeModal.MsoModeTypedeLectura/Escritura.
MsoModeTypepuedeserunadeestasconstantesdeMsoModeType.msoModeAutoDownmsoModeModalmsoModeModeless
Comentarios
SilapropiedadModedeungloboseestablecenenmsoModeModeless,elusuariopuedetrabajarenlaaplicaciónmientraselgloboestávisible.SilapropiedadseestableceenmsoModeModal,elusuariodebecerrarelgloboantesdepodervolveratrabajarenlaaplicación.SilapropiedadseestableceenmsoModeAutoDown,elglobosecierracuandoelusuariohaceclicencualquierpartedelapantalla.
SilapropiedadModedeungloboseestableceenmsoModeModelessynosehaproporcionadounvalorparalapropiedadCallback,seproduceunerror.ElmétodoClosesólopuedeutilizarseenelprocedimientoespecificadoporlapropiedadCallbackcuandolapropiedadModeestáestablecidaenmsoModeModeless.
Ejemplo
Esteejemplocreaungloboconuniconodealertaqueindicaalusuarioqueseleccioneunaimpresora.Comoelglobonotienemodo,elusuariotieneaccesoaloscomandosdelaimpresoramientraselgloboestávisible.CuandoelusuariohaceclicenelbotónAceptar,seejecutaelprocedimientoespecificadoenlapropiedadCallback.
WithAssistant.NewBalloon
.Heading="SelectAPrinter"
.Text="Youmustselectaprinterbeforeprinting."
.Icon=msoIconAlert
.CheckBoxes(1).Text="Localprinter"
.CheckBoxes(2).Text="Networkprinter"
.Mode=msoModeModeless
.Callback="ProcessPrinter"
.Show
EndWith
PropiedadMouseTips
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeofrecesugerenciasparautilizarelmouse(ratón)deformamásefectiva.BooleandeLectura/Escritura.
Comentarios
LapropiedadMouseTipscorrespondealaopciónUsomásefectivodelmouse(ratón)deMostrarsugerenciasacercadeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemploconfiguraelAyudantedeOfficeparaofrecersugerenciasparautilizarelmouse(ratón)deformamásefectiva.
Assistant.MouseTips=True
PropiedadMoveWhenInTheWay
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesilaventanadelAyudantedeOfficesemuevecuandoseencuentreeneláreadetrabajodelusuario.Porejemplo,elAyudantesemoverásimolestaparaarrastrarycolocar,oparaescribirconelteclado.BooleandeLectura/Escritura.
Comentarios
ElvalorpredeterminadoesTrue.LapropiedadMoveWhenInTheWaycorrespondealaopciónMovercuandomolestedeUtilizarelAyudantedeOfficeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemplomuestraelAyudantedeOfficeenunaubicaciónespecíficayconfiguravariasopcionesantesdemostrarloyactivarlo.
WithAssistant
.On=True
.Visible=True
.Left=400
IfNotMoveWhenInTheWayThenMoveWhenInTheWay=True
.Animation=msoAnimationGetAttentionMajor
EndWith
Mostrartodo
PropiedadName
Devuelveoestableceelnombredelobjetoespecificado.StringdeLectura/EscrituraparalosobjetosCommandBaryDocumentProperty;Stringdesólolecturaparatodoslosdemásobjetos.
Comentarios
Elnombrelocaldelabarradecomandosintegradaapareceenlabarradetítulo,cuandolabarranoestáacoplada,yenlalistadebarrasdecomandosdisponibles,siemprequesemuestredichalistaenlaaplicacióncontenedora.
Paraunabarradecomandosintegrada,lapropiedadNamedevuelveelnombredelabarradecomandoseninglésdeEE.UU.UtilicelapropiedadNameLocalparadevolverelnombreadaptado.
SicambiaelvalordelapropiedadLocalNamedeunabarradecomandospersonalizada,tambiéncambiaráelvalordeNameyviceversa.
Ejemplo
Esteejemplobuscaenlacoleccióndebarrasdecomandoslabarradecomandosdenominada"Custom".Siseencuentraestabarradecomandos,elejemplolomuestra.
foundFlag=False
ForEachbarInCommandBars
Ifbar.Name="Custom"Then
foundFlag=True
bar.Visible=True
EndIf
Next
IfNotfoundFlagThen
MsgBox"'Custom'barisn'tincollection."
Else
MsgBox"'Custom'barisnowvisible."
EndIf
Esteejemplomuestraelnombre,tipoyvalordeunapropiedaddedocumento.DebepasarunobjetoDocumentPropertyválidoalprocedimiento.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
Mostrartodo
PropiedadNameLocal
Devuelveelnombredeunabarradecomandosintegradatalcomosemuestraenelidiomadelaaplicacióncontenedoraodevuelve,oestableceelnombredeunabarradecomandospersonalizada.StringdeLectura/Escritura.
NotaAltratardeestablecerestapropiedadparaunabarradecomandosintegrada,seproduciráunerror.
Comentarios
Elnombrelocaldelabarradecomandosintegradaapareceenlabarradetítulo,cuandolabarranoestáacoplada,yenlalistadebarrasdecomandosdisponibles,siemprequesemuestredichalistaenlaaplicacióncontenedora.
SicambiaelvalordelapropiedadLocalNamedeunabarradecomandospersonalizada,tambiéncambiaráelvalordeNameyviceversa.
Ejemplo
Esteejemplomuestraelnombreyelnombreadaptadodelaprimerabarradecomandosdelaaplicacióncontenedora.
WithCommandBars(1)
MsgBox"Thenameofthecommandbaris"&.Name
MsgBox"Thelocalizednameofthecommandbaris"&.NameLocal
EndWith
PropiedadNewBalloon
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
CreaunnuevoglobodelAyudantedeOffice.DevuelveunobjetoBalloon.Esdesólolectura.
Ejemplo
Esteejemplocreaungloboconencabezado,textoytresopcionesderegióny,acontinuación,lomuestra.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectoneormoreregions"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
PropiedadObject
EstableceodevuelveelobjetoqueconstituyelabaseparaelobjetoCOMAddInespecificado.Objectdelectura/escritura.
Comentarios
EstapropiedadseutilizasobretodoparapermitirqueunCOMAddInsecomuniqueconotroCOMAddIn.
Ejemplo
ElejemplosiguientedevuelveelobjetoasociadoconelcomplementoCOMmsodraa9.ShapeSelect.
DimobjBaseObjectAsObject
SetobjBaseObject=_
Application.COMAddIns.Item("msodraa9.ShapeSelect")._
Object
Mostrartodo
PropiedadOLEMenuGroup
DevuelveoestableceelgrupodemenúsalqueperteneceelcontrolemergentedelabarradecomandoscuandoelgrupodemenúsdelservidorOLEsecombinaconelgrupodemenúsdeunclienteOLE,esdecir,cuandounobjetodeltipoaplicacióncontenedoraseincrustaenotraaplicación.MsoOLEMenuGroupdeLectura/Escritura.
MsoOLEMenuGrouppuedeserunadeestasconstantesdeMsoOLEMenuGroup.msoOLEMenuGroupContainermsoOLEMenuGroupEditmsoOLEMenuGroupFilemsoOLEMenuGroupHelpmsoOLEMenuGroupNonemsoOLEMenuGroupObjectmsoOLEMenuGroupWindow
NotaEstapropiedadessólodelecturaparacontrolesintegrados.
Comentarios
EstapropiedadpermitequelasaplicacionescomplementariasespecifiquencómoseránrepresentadossuscontrolesdebarradecomandosenlaaplicaciónOffice.Sinilaaplicacióncontenedoranielservidorcontienenbarrasdecomandos,seproduciráunacombinacióndemenúsOLEnormal.Secombinaránlabarrademenúsytodaslasbarrasdeherramientasdelservidoryningunadelasbarrasdeherramientasdelcontenedor.Estapropiedadsóloesrelevanteparacontrolesemergentesdelabarrademenúsyaquelosmenússecombinanporcategoríasdegruposdemenús.
Silasdosaplicacionesquesecombinancontienenbarrasdecomandos,loscontrolesdebarrasdecomandossecombinandeacuerdoconlapropiedadOLEUsage.
Ejemplo
EsteejemplocompruebalapropiedadOLEMenuGroupdeunnuevocontrolemergentepersonalizadoenlabarradecomandosdenominada"Custom"yestablecelapropiedadenmsoOLEMenuGroupNone.
SetmyControl=CommandBars("Custom").Controls_
.Add(Type:=msoControlPopup,Temporary:=False)
myControl.OLEMenuGroup=msoOLEMenuGroupNone
Mostrartodo
PropiedadOLEUsage
DevuelveoestablecelasfuncionesdelclienteOLEydelservidorOLEenqueseutilizaráuncontroldebarradecomandosalcombinarsedosaplicacionesdeMicrosoftOffice.MsoControlOLEUsagedeLectura/Escritura.
MsoControlOLEUsagepuedeserunadeestasconstantesdeMsoControlOLEUsage.msoControlOLEUsageBothmsoControlOLEUsageClientmsoControlOLEUsageNeithermsoControlOLEUsageServer
Comentarios
EstapropiedadpermiteespecificarcómoseránrepresentadosloscontrolesdebarradecomandosdelasaplicacionescomplementariasenunaaplicacióndeOfficecuandosecombinanconotraaplicacióndeOffice.Sitantoelclientecomoelservidorcontienenbarrasdecomandos,loscontrolesdebarradecomandosseincrustanenelclientecontrolacontrol.Loscontrolespersonalizadosmarcadoscomosólodelcliente(onidelclientenidelservidor)seeliminandelservidoryloscontrolesmarcadoscomosólodelservidor(onidelclientenidelservidor)seeliminandelcliente.Elrestodeloscontrolessecombinan.
SiunadelasaplicacionesdecombinaciónnoesunaaplicacióndeOfficeseutilizalacombinacióndemenúsnormal,controladaporlapropiedadOLEMenuGroup.
Ejemplo
EsteejemploagregaunnuevobotónalabarradecomandosdenominadaToolsyestablecesupropiedadOLEUsage.
SetmyControl=CommandBars("Tools").Controls_
.Add(Type:=msoControlButton,Temporary:=True)
myControl.OLEUsage=msoControlOLEUsageNeither
PropiedadOn
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeestáhabilitado.BooleandeLectura/Escritura.
Ejemplo
EsteejemplodeshabilitaelAyudantedeOffice,muestrauncuadrodemensajequepreguntaalusuariosideseahabilitarelAyudanteylohabilitasielusuariohaceclicenSí.SisehabilitaelAyudante,ésteapareceyejecutalaanimaciónmsoAnimationGreeting.
Assistant.On=False
IfMsgBox("EnableOfficeAssistant?",_
vbYesNo,"AssistantisOff")=vbYesThen
Assistant.On=True
Assistant.Visible=True
Assistant.Animation=_
msoAnimationGetAttentionMajor
EndIf
Mostrartodo
PropiedadOnAction
DevuelveoestableceelnombredelamacrodeVisualBasicqueseejecutarácuandoelusuariohagaclicocambieelvalordeuncontroldebarradecomandos.StringdeLectura/Escritura.
NotaLaaplicacióncontenedoradeterminasielvaloresunnombredemacroválido.
Ejemplo
Esteejemploañadeuncontroldebarradecomandosalabarradecomandosdenominada"Custom".Lamacrodenominada"MySub"seejecutasiemprequesehagaclicenelbotón.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls_
.Add(Type:=msocontrolButton)
WithmyControl
.FaceId=2
.OnAction="MySub"
EndWith
myBar.Visible=True
Esteejemploañadeuncontroldebarradecomandosalabarradecomandosdenominada"Custom".ElcomplementoCOMdenominado"FinanceAddIn"seejecutarácadavezquesehagaclicenelcontrol.
SetmyBar=CommandBars("Custom")
SetmyControl=myBar.Controls_
.Add(Type:=msocontrolButton)
WithmyControl
.FaceId=2
.OnAction="!<FinanceAddIn>"
EndWith
myBar.Visible=True
PropiedadParameter
Devuelveoestableceunacadenaqueunaaplicaciónpuedautilizarparaejecutaruncomandoasociadoconuncontroldebarradecomandos.StringdeLectura/Escritura.
Comentarios
Sielparámetroespecificadoseestableceparauncontrolintegrado,laaplicaciónpuedemodificarsucomportamientopredeterminadosipuedeanalizaryutilizarelnuevovalor.Sielparámetroseestableceparacontrolespersonalizados,puedeutilizarseparaenviarinformaciónalosprocedimientosdeVisualBasicoparaguardarlainformaciónacercadelcontrol,deformasimilaraunsegundovalordelapropiedadTag.
Ejemplo
Esteejemploasignaunnuevoparámetroyestableceelfocoenelnuevobotón.
SetmyControl=CommandBars("Custom").Controls(4)
WithmyControl
.Copy,1
.Parameter="2"
.SetFocus
EndWith
PropiedadParent
DevuelveelobjetoParentdelobjetoespecificado.Esdesólolectura.
Ejemplo
Esteejemplomuestraelnombredelobjetomaestrodeunapropiedaddedocumento.DebepasarunobjetoDocumentPropertyválidoalprocedimiento.
SubDisplayParent(dpasDocumentProperty)
MsgBoxdp.Parent.Name
EndSub
PropiedadPath
DevuelveunvalorStringqueindicalarutadeaccesocompletaaunobjetoScopeFolder.Esdesólolectura.
expresión.Path
expresiónRequerida.ExpresiónquedevuelveunobjetoScopeFolder.
Ejemplo
ElejemplosiguientemuestralarutadeaccesoraízacadadirectoriodeMiPC.Pararecuperarestainformación,elejemploobtieneprimeroelobjetoScopeFolderdelaraízdeMiPC.LarutadeaccesodeesteobjetoScopeFolderserásiempre"*".ComocontodoslosobjetosScopeFolder,elobjetoraízcontieneunacolecciónScopeFolders.EsteejemplorecorreestacolecciónScopeFoldersymuestralarutadeaccesoacadaobjetoScopeFolderdelamisma.LasrutasdeaccesoaestosobjetosScopeFolderserán"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
PropiedadPicture
DevuelveunobjetoIPictureDispquerepresentalaimagendeunobjetoCommandBarButton.
expresión.Picture
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarButton.
Comentarios
Alcambiarlaimagendeunbotón,tambiéndesearáutilizarlapropiedadMaskparaestablecerunaimagendemáscara.Laimagendemáscaradeterminaquépartesdelaimagendelbotónsontransparentes.ConfiguresiemprelamáscaradespuésdeestablecerlaimagenparaelobjetoCommandBarButton.
NotaNosepuedencambiarlasimágenesdelosbotonesVeraplicacióndeMicrosofteInsertarelementodelabarradeherramientasEstándardelEditordeVisualBasic.
Ejemplo
ElejemplosiguienteestablecelaimagenylamáscaradelprimerCommandBarButtonquedevuelveelcódigo.Pararealizarestetrabajo,creeunaimagendemáscarayunaimagendebotónysustituyalasrutasdeaccesodelejemploporlasrutasdeaccesoalasimágenes.
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=picButton
'Usethesecondimagetodefinetheareaofthe
'buttonthatshouldbetransparent.
.Mask=picMask
EndWith
EndSub
ElejemplosiguienteobtienelaimagenylamáscaradelprimerCommandBarButtonquedevuelveelcódigoyenvíacadaunaaunarchivo.Pararealizarestetrabajo,especifiqueunarutadeaccesoalosarchivosdesalida.
SubGetButtonImageAndMask()
DimpicPictureAsIPictureDisp
DimpicMaskAsIPictureDisp
WithApplication.CommandBars.FindControl(msoControlButton)
'GetthebuttonimageandmaskofthethisCommandBarButtonobject.
SetpicPicture=.Picture
SetpicMask=.Mask
EndWith
'Savethebuttonimageandmaskinafolder.
stdole.SavePicturepicPicture,"c:\temp\image.bmp"
stdole.SavePicturepicMask,"c:\temp\mask.bmp"
EndSub
Mostrartodo
PropiedadPosition
Devuelveoestablecelaposicióndelabarradecomandospersonalizada.MsoBarPositiondeLectura/Escritura.
MsoBarPositionpuedeserunadeestasconstantesdeMsoBarPosition.msoBarBottommsoBarFloatingmsoBarLeftmsoBarMenuBarmsoBarPopupmsoBarRightmsoBarTop
Ejemplo
Esteejemplorecorrelacoleccióndebarrasdecomandos,acoplandolasbarrasdecomandospersonalizadasenlaparteinferiordelaventanadeaplicaciónyacoplandolasbarrasdecomandosintegradasenlapartesuperiordelaventana.
ForEachbarInCommandBars
Ifbar.Visible=TrueThen
Ifbar.BuiltInThen
bar.Position=msoBarTop
Else
bar.Position=msoBarBottom
EndIf
EndIf
Next
Mostrartodo
PropiedadPriority
Devuelveoestablecelaprioridaddelcontroldebarradecomandosespecificado.Laprioridaddeuncontroldeterminasiéstepuedeeliminarsedeunabarradecomandosacopladasiloscontrolesdelabarradecomandosnopuedeincluirseenunasolalínea.LongdeLectura/Escritura.
Comentarios
Losnúmerosválidosdeprioridadsonloscomprendidosentreel0yel7inclusive.Unaprioridad1indicaqueelcontrolnosepuedeeliminardeunabarradeherramientas.Losdemásvaloresdeprioridadseomiten
LapropiedadPrioritynoesutilizadaporloscontrolesdelabarradecomandosquesonelementosdemenú.
Ejemplo
Esteejemplodesplazauncontrolyleasignaunaprioridadde5,porloqueesposiblequeseaeliminadodelabarradecomandossiloscontrolesnoseajustanaunalínea.
Setallcontrols=CommandBars("Custom").Controls
ForEachctrlInallControls
Ifctrl.Type=msoControlComboBoxThen
Withctrl
.MoveBefore:=7
.Tag="Selectionbox"
.Priority=5
EndWith
ExitFor
EndIf
Next
PropiedadPrivate
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
DevuelveoestableceunnúmeroenteroqueidentificadeformaúnicaelglobodelAyudantedeOfficequeiniciaelprocedimientodedevolucióndellamada.LongdeLectura/Escritura.
Comentarios
Puedeserútilutilizarestapropiedadsiseutilizaelmismoprocedimientodedevolucióndellamadaparadiferentescircunstancias.
Ejemplo
EsteejemploidentificaelglobodelAyudantedeOfficeestableciendolapropiedadPrivateen129.
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
PropiedadProgId
Devuelveelidentificadordemacros(ProgID)delobjetoCOMAddInespecificado.Stringdesólolectura.
Ejemplo
ElejemplosiguientemuestraenuncuadrodemensajeelProgIDyelGUIDdelcomplementoCOMuno.
MsgBox"MyProgIDis"&_
Application.COMAddIns(1).ProgID&_
"andmyGUIDis"&_
Application.COMAddIns(1).Guid
PropiedadPropertyTests
DevuelvelacolecciónPropertyTestsquerepresentatodosloscriteriosdebúsquedadeunabúsquedadearchivos.Esdesólolectura.
Paraobtenermásinformaciónsobrecómodevolverunsolomiembrodeunacolección,veaDevolverunobjetodeunacolección.
Ejemplo
Esteejemplomuestratodosloscriteriosdebúsquedadelaprimerapruebadepropiedadesdelacolección.
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
PropiedadProportionalFont
Estableceodevuelvelaopcióndefuenteproporcionaldelaaplicaciónhost.StringdeLectura/Escritura.
Comentarios
CuandoestablecelapropiedadProportionalFont,laaplicaciónhostnocompruebasielvaloresválido.
Ejemplo
EsteejemploestablecelafuenteproporcionalyeltamañodefuenteproporcionalparaeljuegodecaracteresInglés/Europeooccidental/Otroalfabetolatinodentrodelaaplicaciónactiva.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFont="Tahoma"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFontSize=14.5
PropiedadProportionalFontSize
Estableceodevuelvelaopcióndetamañodefuenteproporcionalenlaaplicaciónhost,enpuntos.Singledelectura/escritura.
Comentarios
CuandoestablecelapropiedadProportionalFontSize,laaplicaciónhostnocompruebasielvaloresválido.Siespecificaunvalornoválido,comopuedeseruncarácternonumérico,laaplicaciónhostestableceráeltamañoen0puntos.Puedeasignarlostamañosdemedioenmediopunto;siinsertaotrasfraccionesdetamañoenpuntos,éstasseredondearánhaciaarribaohaciaabajoalmediopuntomáscercano.
Ejemplo
EsteejemploestablecelafuenteproporcionalyeltamañodefuenteproporcionalparaeljuegodecaracteresInglés/Europeooccidental/Otroalfabetolatinodentrodelaaplicaciónactiva.
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFont="Tahoma"
Application.DefaultWebOptions._
Fonts(msoCharacterSetEnglishWesternEuropeanOtherLatinScript)_
.ProportionalFontSize=14.5
Mostrartodo
PropiedadProtection
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Devuelveoestablecelamaneraenquelabarradecomandosespecificadaestáprotegidacontralapersonalización.MsoBarProtectiondeLectura/Escritura.
MsoBarProtectionpuedeserunadeestasconstantesdeMsoBarProtection.msoBarNoChangeDockmsoBarNoChangeVisiblemsoBarNoCustomizemsoBarNoHorizontalDockmsoBarNoMovemsoBarNoProtectionmsoBarNoResizemsoBarNoVerticalDock
Comentarios
AlutilizarlaconstantemsoBarNoCustomizeseevitaelaccesoalmenúAgregaroquitarbotones(estemenúpermitealosusuariospoderpersonalizarunabarradeherramientas).
Ejemplo
Esteejemplorecorrelacoleccióndebarrasdecomandosparabuscarlabarradenominada"Forms".Siseencuentraestabarradeherramientas,elejemplolamuestrayprotegesuestadodeacoplamiento.
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
PropiedadReduced
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesilaventanadelAyudantedeOfficeaparececonsutamañomáspequeño.BooleandeLectura/Escritura.
Comentarios
EstapropiedadnoseutilizaenMicrosoftOffice.
Ejemplo
EsteejemplomuestraelAyudantedeOfficeenunaubicaciónespecíficayconfiguravariasopcionesantesdemostrarlo.
WithAssistant
.Reduced=True
.Left=400
.MoveWhenInTheWay=True
.TipOfDay=True
.Visible=True
.Animation=msoAnimationGreeting
EndWith
PropiedadRowCount
DevuelveunvalorLongquerepresentaelnúmeroderegistrosdelorigendedatosespecificado.Esdesólolectura.
expresión.RowCount
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemploagregaunfiltronuevoquequitatodoslosregistrosconuncampoRegiónenblancoy,acontinuación,aplicaelfiltroalapublicaciónactiva.
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
Mostrartodo
PropiedadRowIndex
Devuelveoestableceelordendeacoplamientodelabarradecomandosespecificadaenrelaciónconotrasbarrasdecomandodelmismoáreadeacoplamiento.PuedeserunnúmeroenteromayorqueceroocualquieradelassiguientesconstantesMsoBarRow:msoBarRowFirstomsoBarRowLast.LongdeLectura/Escritura.
Comentarios
Variasbarrasdecomandospuedencompartirelmismoíndicedefila.Lasbarrasdecomandosconnúmerosinferioresseacoplanprimero.Sidosomásbarrasdecomandoscompartenelmismoíndicedefila,semostraráprimerolabarradecomandosdelgrupoasignadamásrecientemente.
Ejemplo
Esteejemploajustalaposicióndelabarradecomandosdenominada"Custom"moviéndolaalaizquierda110píxelesmásdelvalorpredeterminadoyhacequesealaprimerabarradecomandosacoplada,cambiandosunúmerodeíndiceamsoBarRowFirst.
SetmyBar=CommandBars("Custom")
WithmyBar
.RowIndex=msoBarRowFirst
.Left=140
EndWith
PropiedadScopeFolder
DevuelveunobjetoScopeFolder.
expresión.ScopeFolder)
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestralarutadeaccesoraízacadadirectoriodeMiPC.Pararecuperarestainformación,elejemploobtieneprimeroelobjetoScopeFolderdelaraízdeMiPC.LarutadeaccesoaesteobjetoScopeFolderserásiempre"*".ComocontodoslosobjetosScopeFolder,elobjetoraízcontieneunacolecciónScopeFolders.EsteejemplorecorreestacolecciónScopeFoldersymuestralarutadeaccesoacadaobjetoScopeFolderdelamisma.LasrutasdeaccesoaestosobjetosScopeFolderserán"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
PropiedadScopeFolders
DevuelveunacolecciónScopeFolders.LoselementosdeestacoleccióncorrespondenalassubcarpetasdelobjetoScopeFoldermaestro.
expresión.ScopeFolders
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestralarutadeaccesoraízacadadirectoriodeMiPC.Pararecuperarestainformación,elejemploobtieneprimeroelobjetoScopeFolderdelaraízdeMiPC.LarutadeaccesoaesteobjetoScopeFolderserásiempre"*".ComocontodoslosobjetosScopeFolder,elobjetoraízcontieneunacolecciónScopeFolders.ElejemplorecorreestacolecciónScopeFoldersymuestralarutadeaccesoacadaobjetoScopeFolderdelamisma.LasrutasdeaccesoaestosobjetosScopeFolderserán"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
PropiedadScriptText
Estableceodevuelveeltextocontenidoenunbloquedesecuenciasdecomandos.StringdeLectura/Escritura.
Comentarios
LaaplicaciónhostdeMicrosoftOfficenocompruebalasintaxisdelasecuenciadecomandos.LapropiedadScriptTexteslapropiedadpredeterminadadelobjetoScript.
Ejemplo
Esteejemploestableceeltextodelaprimerasecuenciadecaracteresdelahojaunodellibroactivo.
ActiveWorkbook.Worksheets(1).Scripts(1).ScriptText=_
"MsgBox""NewScriptText"""
PropiedadSearchFolders
DevuelveunacolecciónSearchFolders.
expresión.SearchFolders
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestraelnúmeroactualdeobjetosScopeFolderdelacolecciónSearchFolders.ConsulteeltemarelativoalacolecciónSearchFolderssideseaunejemplomásdetallado.
MsgBox"NumberofScopeFolderobjectsintheSearchFolderscollection:"&_
Application.FileSearch.SearchFolders.Count
PropiedadSearchScopes
DevuelveunacolecciónSearchScopes.
expresión.SearchScopes
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestratodoslosobjetosSearchScopedelacolecciónSearchScopesdisponiblesactualmente.
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
PropiedadSearchSubFolders
TruesilabúsquedaespecificadaincluyelassubcarpetasdelacarpetaespecificadaporlapropiedadLookIn.BooleandeLectura/Escritura.
Ejemplo
EsteejemplobuscaenlacarpetaMyDocumentsyentodaslassubcarpetastodoslosarchivoscuyosnombrescomiencencon"Cmd".Elejemplotambiénmuestraelnombreyubicacióndecadaarchivoencontrado.
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
PropiedadSearchWhenProgramming
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficemuestraayudaacercadelaaplicaciónasícomolaAyudaacercadelaprogramaciónmientraselusuariotrabajaconVisualBasic.BooleandeLectura/Escritura.
Comentarios
ElvalorpredeterminadoesFalse.LapropiedadSearchWhenProgrammingcorrespondealaopciónBuscarayudadelproductoydeprogramacióndeutilizarelAyudantedeOfficeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemplolepermitebuscarayudadelaaplicaciónydeprogramaciónmientrastrabajaenVisualBasic.
Assistant.SearchWhenProgramming=True
PropiedadSecondValue
Devuelveunsegundovaloropcionaldepruebadepropiedades,comoenunintervalo,delabúsquedadearchivosespecificada.Variantdesólolectura.
Comentarios
EstapropiedadseutilizaenunintervaloespecíficoysólopuedeutilizarseconlasiguienteconstanteMsoCondition:msoConditionAnyTimeBetweenomsoConditionAnyNumberBetween.
Ejemplo
Esteejemplomuestraelsegundovalordeloscriteriosdebúsqueda,siexiste,enuncuadrodediálogo.Sinoexisteelsegundovalor,elejemplomuestraotromensaje.
WithApplication.FileSearch.PropertyTests(1)
If.SecondValue=""Then
MsgBox"Youhaven'tspecifiedasecondvalue."
Else
MsgBox"Thesecondvalueyou'vesetis:"_
&.SecondValue
EndIf
EndWith
PropiedadSelectedItems
DevuelveunacolecciónFileDialogSelectedItems.EstacoleccióncontienelalistadelasrutasdeaccesoalosarchivosqueelusuariohaseleccionadoenuncuadrodediálogodearchivosquesemuestrautilizandoelmétodoShowdelobjetoFileDialog.
expresión.SelectedItem
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
PropiedadShape
DevuelveunobjetoShapeounobjetoInlineShape,dependiendodelaaplicaciónhostdeMicrosoftOfficedequesesetrate.Objectdesólolectura.
Comentarios
LapropiedadShapedevuelveunobjetoShapeenMicrosoftExcelyenPowerPoint.EnWord,lapropiedadShapedevuelveunobjetoShapesieldelimitadordesecuenciasdecomandosesflotante;noobstante,sisetratadeundelimitadorentrelíneas,estapropiedaddevolveráunobjetoInlineShape.
Ejemplo
EsteejemploobtienelaformaasociadaconlaprimerasecuenciadecomandosdelacolecciónScriptsylaeliminadelahojaunodellibroactivo.
DimobjScriptShapeAsObject
SetobjScriptShape=_
ActiveWorkbook.Worksheets(1).Scripts(1).Shape
ObjScriptShape.Delete
Mostrartodo
PropiedadShortcutText
Devuelveoestableceeltextodelateclademétodoabreviadomostradajuntoalcontroldebotónespecificadocuandoestebotónapareceenunmenú,submenúomenúcontextual.StringdeLectura/Escritura.
Comentarios
SóloesposibleestablecerestapropiedadparabotonesdebarrasdecomandosquetenganunamacroOnActionadjunta.
Ejemplo
EsteejemplomuestraeltextodelaccesodirectodelcomandoOpen(menúFile)enuncuadrodemensajedelabarrademenúsdeunahojadecálculodeMicrosoftExcel.
MsgBox(CommandBars("WorksheetMenuBar")._
Controls("File").Controls("New...).ShortcutText)
PropiedadSignDate
DevuelveunavariableVariantquerepresentalafechaylahoraenquesehaadjuntadoaldocumentoelcertificadodigitalcorrespondientealobjetoSignature.Esdesólolectura.
expresión.SignDate
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentoenWordyejecuteestafunción.Lafunciónrealizarálacomprobaciónparaasegurarsedequelafirmadigitalqueseleccionaelusuarionocaducaantesde12meses.Sicaduca,noseadjuntaelcertificado.
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
PropiedadSigner
DevuelveunvalorStringquerepresentaelnombredelapersonaqueadjuntóelcertificadodigitalquecorrespondealobjetoSignaturealdocumento.Esdesólolectura.
expresión.Signer
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EnelejemplosiguientesesolicitaalusuarioqueseleccioneunafirmadigitalparafirmareldocumentoactivodeMicrosoftWord.Parautilizaresteejemplo,abraundocumentodeWordypaseaestafunciónlosnombresdeunemisorydeunfirmantedecertificadosenloscamposEmitidoporyEmitidoparadeuncertificadodigital,enelcuadrodediálogoCertificadosdigitales.Esteejemplocompruebaquelafirmadigitalqueelusuarioseleccionacumpleciertoscriterios,comonohabercaducado,antesdequeseguardelafirmanuevaeneldisco.
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
PropiedadSounds
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficeproduceelsonidoquecorrespondealasanimaciones.BooleandeLectura/Escritura.
Comentarios
ElvalorpredeterminadoesTrue.LapropiedadSoundscorrespondealaopciónConsonidodeUtilizarelAyudantedeOfficedelafichaOpciones,enelcuadrodediálogoAyudantedeOffice.Sinoestáinstaladaunatarjetadesonido,estapropiedadnorealizaningunaacción.
Ejemplo
EsteejemplomuestraelAyudantedeOffice,loanimaygenerasonido.
WithAssistant
.Visible=True
.On=True
IfNotSoundsThenSounds=True
.Animation=msoAnimationGreeting
EndWith
Mostrartodo
PropiedadState
PropiedadStatecuandoseaplicaalobjetoCommandBarButton.
Devuelveoestableceelaspectodelcontroldebotóndelabarradecomandosespecificada.MsoButtonStatedeLectura/Escritura.
MsoButtonStatepuedeserunadeestasconstantesdeMsoButtonState.msoButtonDownmsoButtonMixedmsoButtonUp
expresión.State
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBarButton.
PropiedadStatecuandoseaplicaalobjetoHTMLProject.
DevuelveelestadoactualdeunobjetoHTMLProject.MsoHTMLProjectStatedesólolectura.
MsoHTMLProjectStatepuedeserunadeestasconstantesdeMsoHTMLProjectState.msoHTMLProjectStateDocumentLockedmsoHTMLProjectStateDocumentProjectUnlockedmsoHTMLProjectStateProjectLocked
expresión.State
expresiónRequerida.ExpresiónquedevuelveunobjetoHTMLProject.
Ejemplo
CuandoseaplicaalobjetoCommandBarButton.
EsteejemplocreaunabarradecomandosdenominadaCustomyagregadosbotonesenblancoaesabarra.Acontinuación,elejemploestableceelbotóndelaizquierdaenmsoButtonUpyestableceelbotóndeladerechaenmsoButtonDown.
SetmyBar=CommandBars_
.Add(Name:="Custom",Position:=msoBarTop,_
Temporary:=True)
WithmyBar
.Controls.AddType:=msoControlButton,ID:=1
.Controls.AddType:=msoControlButton,ID:=2
.Visible=True
EndWith
SetmyControl1=CommandBars("Custom").Controls(1)
myControl1.State=msoButtonUp
SetmyControl2=CommandBars("Custom").Controls(2)
myControl2.State=msoButtonDown
Mostrartodo
PropiedadStyle
PropiedadStylecomoseaplicaalobjetoCommandBarButton.
Devuelveoestablecelamaneraenquesemuestraelcontroldebotóndelabarradecomandos.MsoButtonStyledeLectura/Escritura.
MsoButtonStylepuedeserunadeestasconstantesdeMsoButtonStyle.msoButtonAutomaticmsoButtonCaptionmsoButtonIconmsoButtonIconAndCaptionmsoButtonIconAndCaptionBelowmsoButtonIconAndWrapCaptionmsoButtonIconAndWrapCaptionBelowmsoButtonWrapCaption
PropiedadStylecomoseaplicaalobjetoCommandBarComboBox.
Devuelveoestablecelamaneraenquesemuestraelcontroldecuadrocombinadodelabarradecomandos.PuedeserunadelassiguientesconstantesMsoComboStyle:msoComboLabelomsoComboNormal.MsoComboStyledeLectura/Escritura.
MsoComboStylepuedeserunadeestasconstantesdeMsoComboStyle.msoComboLabelmsoComboNormal
Ejemplo
Esteejemplocreaunmenúcontextualquecontieneuncontroldebotónyuncontroldecuadrocombinado,yestableceelestilodecadaunodeellos.
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
PropiedadTable
DevuelveunvalorStringquerepresentaelnombredelatablaenelarchivodeorigendedatosquecontienelosregistrosdecombinacióndecorrespondencia.Elvalordevueltopuedeestarenblancosinoseconoceelnombredelatablaonoesaplicablealorigendedatosactual.Esdesólolectura.
expresión.Table
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
Esteejemploestableceelnombredelatablasiestáenblanco.
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
Mostrartodo
PropiedadTag
Devuelveoestablecelainformaciónacercadelcontroldebarradecomandos,porejemplo,losdatosquepuedenutilizarsecomoargumentosenprocedimientosylainformaciónqueidentificaelcontrol.StringdeLectura/Escritura.
expresión.Tag
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
Paraevitarllamadasduplicadasdelamismaclasecuandoseactivaconeventos,definalapropiedadTagcomoexclusivaenloseventos.Elsiguienteejemplodemuestraesteconceptomediantedosmódulos.
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
Ejemplo
Esteejemploestableceelrótuloparaelbotóndelabarradecomandosen"SpellingButton"ylomuestraenuncuadrodemensaje.
CommandBars("Custom").Controls(1).Tag="SpellingButton"
MsgBox(CommandBars("Custom").Controls(1).Tag)
Mostrartodo
PropiedadText
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
ObjetoBalloonLabeloBalloonCheckbox:DevuelveoestableceeltextomostradojuntoalacasilladeverificaciónorótuloespecificadosdelgloboAyudantedeOffice.StringdeLectura/Escritura.
ObjetoBalloon:DevuelveoestableceeltextomostradodespuésdelencabezadoperoantesdelascasillasdeverificaciónorótulosespecificadosdelgloboAyudantedeOffice.StringdeLectura/Escritura.
ObjetoCommandBarComboBox:Devuelveoestableceeltextoeneláreadepresentaciónomodificacióndelcontroldecuadrocombinadodelabarradecomandos.StringdeLectura/Escritura.
ObjetoHTMLProjectItem:DevuelveoestableceeltextoHTMLeneleditorHTML.StringdeLectura/Escritura.
expresión.Text
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
ParalosobjetosBalloon,BalloonLabelyBalloonCheckboxpuedeespecificarquesemuestreungráficodeterminadoutilizandolasintaxissiguiente:{typelocationsizing_factor},dondetypeesbmp(mapadebits)owmf(metarchivodeWindows);locationeselidentificadorderecursosolarutadeaccesoynombredearchivo;ysizing_factorindicaelanchodelarchivo.wmf(sizing_factorseomiteparalosarchivos.bmp).
ElobjetoGlobotambiénadmitetextosubrayadoytextoquetengaaplicadounodelos16coloresdelapaletadelsistema.Paramostrareltextosubrayado,utilicelasintaxis{ul}o{ul1};utilice{ul0}paradesactivarelsubrayado.Paracambiarelcolordeltexto,coloquedelantelacadenadetextolasecuenciadecaracteres{cfnumber},dondenumbereselnúmerodecolordelsistemaincluidoenlatablasiguiente.
Númerodecolordelsistema Color0 Negro1 Rojooscuro2 Verdeoscuro3 Amarillooscuro4 Azulmarino5 Púrpura6 Verdeazulado7 Plateado248 Grisclaro249 Rojo250 Verde251 Amarillo252 Azul253 Fucsia254 Aguamarina255 Blanco
Siespecificaunnúmeroquenoestéenlosnúmerosdecolordelsistemaprecedentes,eltextodelglobodelAyudantedeOfficeapareceráencolornegro.
Ejemplo
Esteejemplocreaunanuevabarradecomandosdenominada"Personalizada"yagregaaéstauncuadrocombinadoquecontienecuatroelementosdelista.Acontinuación,elejemploutilizalapropiedadTextparaestablecerItem3comoelelementodelistapredeterminado.
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
EsteejemplocreaunnuevogloboAyudantedeOfficeconencabezado,textoytresopcionesderegión.ElejemploutilizalapropiedadTextparaproporcionaralusuarioinstruccionesacercadelgloboyunrótuloparacadacuadrodetexto.
WithAssistant.NewBalloon
.Heading="RegionalSalesData"
.Text="Selectaregion"
Fori=1To3
.CheckBoxes(i).Text="Region"&i
Next
.Show
EndWith
ConesteejemplosecreaunnuevoglobodelAyudantedeOfficequecontieneeltextodeltítulosubrayado,textorojoytextoazulquetambiénestásubrayado.
WithAssistant.NewBalloon
.Heading="Underlined{ul1}Heading{ul0}"
.Text="Some{cf249}Red{cf0}textandsome"&_
"underlined{cf252}{ul1}Blue{ul0}{cf0}text."
.Show
EndWith
EnesteejemplosecreaunnuevoglobodelAyudantedeOfficequecontieneunmetarchivodeWindows.
WithAssistant.NewBalloon
.Heading="Underlined{ul1}Heading{ul0}"
.Text="{WMF""C:\Favorites\MyPicture.WMF""}"
.Show
EndWith
PropiedadTextOrProperty
Devuelveoestablecelapalabraofrasequesevaabuscareneltextooenlaspropiedadesdelarchivo,durantelabúsquedadearchivosespecificada.Lapalabraofrasepuedeincluirloscaracterescomodín*(asterisco)o?(interrogación).StringdeLectura/Escritura.
Comentarios
Utiliceelcaráctercomodíninterrogaciónparabuscarcualquiercarácterindividual.Porejemplo,escribagr?sparabuscartodoslosarchivosquecontenganalmenosunaapariciónde"gris"o"gres".
Utiliceelcaráctercomodínasteriscoparabuscarcualquiernúmerodecaracteres.Porejemplo,escribaSan*parabuscartodoslosarchivosquecontenganalmenosunapalabraquecomiencepor"San".
Ejemplo
EsteejemplobuscaenlacarpetaC:\MisDocumentosytodassussubcarpetasydevuelvetodoslosarchivoscuyotextoopropiedadesdearchivocontengancualquierpalabraquecomiencepor"San".LapropiedadTextOrPropertyestablecelapalabraquesevaabuscarylimitalabúsquedaaltextooalaspropiedadesdelarchivo.
WithApplication.FileSearch
.NewSearch
.LookIn="C:\MyDocuments"
.SearchSubFolders=True
.TextOrProperty="San*"
.FileType=msoFileTypeAllFiles
EndWith
PropiedadTipOfDay
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
TruesielAyudantedeOfficemuestraunasugerenciaespecialcadavezqueseabrelaaplicacióndeOffice.BooleandeLectura/Escritura.
Comentarios
ElvalorpredeterminadoesFalse.LapropiedadTipOfDaycorrespondealaopciónMostrarsugerenciaaliniciodeMostrarsugerenciasacercadeenlafichaOpcionesdelcuadrodediálogoAyudantedeOffice.
Ejemplo
EsteejemplomuestraelAyudantedeOfficeenunaubicaciónespecíficayconfiguravariasopcionesantesdemostrarlo.
WithAssistant
.On=True
.Visible=True
.Left=400
.MoveWhenInTheWay=True
IfNotTipOfDayThenTipOfDay=True
.Animation=msoAnimationGreeting
EndWith
PropiedadTitle
EstableceodevuelveeltítulodeuncuadrodediálogodearchivosquesemuestramedianteelobjetoFileDialog.StringdeLectura/Escritura.
expresión.Title
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
ElejemplosiguientemuestrauncuadrodediálogoSelectordearchivosmedianteelobjetoFileDialog,asícomocadaarchivoseleccionadoenuncuadrodemensaje.
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
PropiedadTooltipText
DevuelveoestableceeltextomostradoenlaSugerenciadelcontroldebarradecomandosespecificado.StringdeLectura/Escritura.
Comentarios
ElvalordeCaptioneselpredeterminadoparalaSugerencia.
Ejemplo
Esteejemploagregaunasugerenciaalúltimocontroldelabarrademenúsactiva.
SetmyMenuBar=CommandBars.ActiveMenuBar
SetlastCtrl=myMenuBar_
.Controls(myMenuBar.Controls.Count)
lastCtrl.BeginGroup=True
lastCtrl.TooltipText="ClickforhelponUIfeature"
Mostrartodo
PropiedadTop
Puedequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
PropiedadTopcuandoseaplicaalosobjetosAssistantyCommandBar.
Estableceodevuelveladistancia,enpuntos,desdelapartesuperiordelAyudantedeOfficeodesdeelbordesuperiordelabarradecomandosespecificadaalbordesuperiordelapantalla.Parabarrasdecomandosacopladas,estapropiedaddevuelveoestableceladistanciadesdelabarradecomandoshastaelbordesuperiordeláreadeacoplamiento.LongdeLectura/Escritura.
expresión.Top
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
PropiedadTopcuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
Devuelveladistancia,enpíxeles,desdeelbordesuperiordelcontroldelabarradecomandosespecificadoalbordesuperiordelapantalla.Longdesólolectura.
expresión.Top
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
Ejemplo
CuandoseaplicaalosobjetosAssistantyCommandBar.
EsteejemplodesplazaelAyudantedeOfficeaotracoordenadayestablecesupropiedadTopparafuturasapariciones.
WithAssistant
.On=True
.Visible=True
.Sounds=True
.Animation=msoAnimationBeginSpeaking
EndWith
Assistant.Top=100
MsgBox"ClickOKtomovetheAssistanttoa"&_
"newlocation."
Assistant.Top=500
EsteejemplositúalaesquinasuperiorizquierdadelabarradecomandosflotantedenominadaCustoma140píxelesdelbordeizquierdodelapantallaya100píxelesdelbordesuperiordelapantalla.
SetmyBar=CommandBars("Custom")
myBar.Position=msoBarFloating
WithmyBar
.Left=140
.Top=100
EndWith
Mostrartodo
PropiedadType
PropiedadTypecuandoseaplicaalobjetoCommandBar.
Devuelveeltipodebarradecomandos.MsoBarTypedesólolectura.
MsoBarTypepuedeserunadeestasconstantesdeMsoBarType.msoBarTypeMenuBarmsoBarTypeNormalmsoBarTypePopup
expresión.Type
expresiónRequerida.ExpresiónquedevuelveunobjetoCommandBar.
PropiedadTypecuandoseaplicaalosobjetosCommandBarButton,CommandBarComboBox,CommandBarControlyCommandBarPopup.
Devuelveeltipodecontroldebarradecomandos.MsoControlTypedesólolectura.
MsoControlTypepuedeserunadeestasconstantesMsoControlType.msoControlActiveXmsoControlAutoCompleteCombomsoControlButtonmsoControlButtonDropdownmsoControlButtonPopupmsoControlComboBoxmsoControlCustommsoControlDropdownmsoControlEditmsoControlExpandingGrid
msoControlGaugemsoControlGenericDropdownmsoControlGraphicCombomsoControlGraphicDropdownmsoControlGraphicPopupmsoControlGridmsoControlLabelmsoControlLabelExmsoControlOCXDropdownmsoControlPanemsoControlPopupmsoControlSpinnermsoControlSplitButtonMRUPopupmsoControlSplitButtonPopupmsoControlSplitDropdownmsoControlSplitExpandingGridmsoControlWorkPane
expresión.Type
expresiónRequerida.Expresiónquedevuelveunodelosobjetosanteriores.
PropiedadTypecuandoseaplicaalobjetoSearchScope.
DevuelveunvalorquecorrespondealtipodeobjetoSearchScope.EltipoindicaenquéáreabuscarálosarchivoselmétodoExecutedelobjetoFileSearch.MsoSearchIndesólolectura.
MsoSearchInpuedeserunadeestasconstantesdeMsoSearchIn.msoSearchInCustommsoSearchInMyComputermsoSearchInMyNetworkPlacesmsoSearchInOutlook
expresión.Type
expresiónRequerida.ExpresiónquedevuelveunobjetoSearchScope.
PropiedadTypecuandoseaplicaalobjetoDocumentProperty.
Devuelveoestableceeltipodepropiedaddeldocumento.Esdesólolecturaparapropiedadesdedocumentointegradas;esdeLectura/Escrituraparapropiedadesdedocumentopersonalizadas.
expresión.Type
expresiónRequerida.ExpresiónquedevuelveunobjetoDocumentProperty.
Comentarios
ElvalordevueltoseráunaconstantedeMsoDocProperties.
MsoFilterConjunctionpuedeserunadeestasconstantesdeMsoFilterConjunction.msoPropertyTypeBooleanmsoPropertyTypeDatemsoPropertyTypeFloatmsoPropertyTypeNumbermsoPropertyTypeString
Ejemplo
CuandoseaplicaalobjetoCommandBar.
EsteejemploencuentraelprimercontroldelabarradecomandosdenominadaCustom.AlutilizarlapropiedadType,elejemplodeterminasielcontrolesunbotón.Siesasí,elejemplocopialaimagendelbotónCopy(delabarradeherramientasStandard)ydespuéslapegaenelcontrol.
SetoldCtrl=CommandBars("Custom").Controls(1)
IfoldCtrl.Type=msoControlButtonThen
SetnewCtrl=CommandBars.FindControl(Type:=_
MsoControlButton,ID:=_
CommandBars("Standard").Controls("Copy").ID)
NewCtrl.CopyFace
OldCtrl.PasteFace
EndIf
CuandoseaplicaalobjetoDocumentProperty.
Esteejemplomuestraelnombre,tipoyvalordeunapropiedaddedocumento.DebepasarunobjetoDocumentPropertyválidoalprocedimiento.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
Mostrartodo
PropiedadValue
PropiedadValuecuandoseaplicaalobjetoDocumentProperty.
Devuelveoestableceelvalordeunapropiedaddedocumento.VariantdeLectura/Escritura.
expresión.Value
expresiónRequerida.ExpresiónquedevuelveunobjetoDocumentProperty.
Comentarios
Silaaplicacióncontenedoranodefineunvalorparaunadelaspropiedadesdedocumentointegradas,alleerlapropiedadValuedeesedocumentoseproduceunerror.
PropiedadValuecuandoseaplicaalobjetoPropertyTest.
Devuelveelvalordeunapruebadepropiedadparaunabúsquedadearchivos.Variantdesólolectura.
expresión.Value
expresiónRequerida.ExpresiónquedevuelveunobjetoPropertyTest.
Ejemplo
CuandoseaplicaalobjetoDocumentProperty.
Esteejemplomuestraelnombre,tipoyvalordeunapropiedaddedocumento.Paraqueelejemplofuncione,dpdebeserunobjetoDocumentPropertyválido.
SubDisplayPropertyInfo(dpAsDocumentProperty)
MsgBox"value="&dp.Value&Chr(13)&_
"type="&dp.Type&Chr(13)&_
"name="&dp.Name
EndSub
CuandoseaplicaalobjetoPropertyTests.
Esteejemplomuestraelvalordeloscriteriosdebúsqueda,siexiste,enuncuadrodemensaje.Sinoexisteelsegundovalor,elejemplomuestraotromensaje.
WithApplication.FileSearch.PropertyTests(1)
If.Value=""Then
MsgBox"Youhaven'tspecifiedavalue."
Else
MsgBox"Thevalueyou'vesetis:"_
&.Value
EndIf
EndWith
PropiedadVisible
Esposiblequealgunaspartesdeestetemanoseanaplicablesaalgunosidiomas.
Truesielobjetoespecificadoesvisible.BooleandeLectura/Escritura.
expresión.Visible
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Comentarios
FalseeselvalorpredeterminadodelapropiedadVisibledelasnuevasbarrasdecomandospersonalizadas.
LapropiedadEnableddeunabarradecomandosdebeestablecerseenTrueantesdeestablecerlapropiedadvisibleenTrue.
Ejemplo
Esteejemplorecorrelacoleccióndebarrasdecomandosparabuscarlabarradecomandos"Forms".Siseencuentralabarradecomandos"Forms",elejemplolomuestrayprotegeelestadodeacoplamiento.
foundFlag=False
ForEachcmdbarInCommandBars
Ifcmdbar.Name="Forms"Then
cmdbar.Protection=msoBarNoChangeDock
cmdbar.Visible=True
foundFlag=True
EndIf
Next
IfNotfoundFlagThen
MsgBox"'Forms'commandbarisnotinthecollection."
EndIf
ElejemplomuestraelAyudantedeOfficeyestablecelaanimación.
WithApplication.Assistant
.Visible=True
.Sounds=True
.Animation=msoAnimationBeginSpeaking
EndWith
Mostrartodo
PropiedadWidth
Devuelveoestableceelancho,enpíxeles,delabarradecomandosodelcontroldelabarradecomandosespecificados.IntegerdeLectura/Escritura.
expresión.Width
expresiónRequerida.ExpresiónquedevuelveunodelosobjetosdelalistaAplicara.
Ejemplo
EsteejemploagregauncontrolpersonalizadoalabarradecomandosdenominadaCustom.Elejemploestableceelaltodelcontrolpersonalizadoeneldobledelaltodelabarradecomandosyestableceelanchoen50píxeles.Observecómolabarradecomandoscambiasutamañodeformaautomáticaparaadaptarloalcontrol.
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
EventoChange
Seproducecuandoelusuariofinalcambialaselecciónenuncuadrocombinadodelabarradecomandos.
PrivateSubCommandBarComboBox_Change
(ByValCtrlAsCommandBarComboBox)
Comentarios
EleventoChangesereconocemedianteelobjetoCommandBarComboBox.ParadevolvereleventoChangedeuncontrolCommandBarComboBoxespecífico,utilicelapalabraclaveWithEventsparadeclararunavariabley,acontinuación,establezcalavariableenelcontrolCommandBarComboBox.CuandoseactiveeleventoChange,ésteejecutarálamacrooelcódigoqueseespecificóconlapropiedadOnActiondelcontrol.
Ejemplo
ElejemplosiguientecreaunabarradecomandosconuncontrolCommandBarComboBoxquecontienecuatroselecciones.ElcuadrocombinadocorrespondealainteraccióndelusuariomedianteeleventoCommandBarComboBox_Change.
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
Elejemploanteriorsebasaenelcódigosiguiente,quesealmacenaenunmódulodeclaseenelproyectoVBA.
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
EventoClick
OcurrecuandoelusuariohaceclicenunobjetoCommandBarButton.
PrivateSubCommandBarButton_Click
(ByValCtrlAsCommandBarButton,
ByValCancelDefaultAsBoolean)
LasintaxisdeleventoClickincluyelosdosargumentosdescritosenlasiguientetabla.
Argumento Descripción
CtrlCommandBarButtonrequerido.AludealcontrolCommandBarButtonqueinicióelevento.
CancelDefault
Booleanrequerido.FalsesiseproduceelcomportamientopredeterminadoasociadoconelcontrolCommandBarButton,salvoqueseacanceladoporotroprocesoocomplemento.
Comentarios
EleventoClickesreconocidoporelobjetoCommandBarButton.ParadevolvereleventoClickdeuncontrolCommandBarButtondeterminado,utilicelapalabraclaveWithEventsparadeclararunavariabley,acontinuación,asignelavariablealcontrol.
Ejemplo
ElejemplosiguientecreaunnuevobotóndebarradecomandosenelmenúArchivodelaaplicaciónhost,quepermitequeelusuarioguardeunlibrocomounarchivodevaloresseparadosporcomas.Esteejemplofuncionaentodaslasaplicaciones,peroelcontextodeguardarcomoCSVesaplicableaMicrosoftExcel.
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
EventoEnvelopeHide
SeproducecuandoestáocultalainterfazdeusuarioquecorrespondealobjetoMsoEnvelope.
PrivateSubobject_EnvelopHide()
objectVariablequehacereferenciaaunobjetodetipoMsoEnvelopedeclaradaconeventosdeunmódulodeclase.
Ejemplo
ElejemplosiguienteconfigurarutinasdemanipulacióndeeventosparaelobjetoMsoEnvelope.
PublicWithEventsenvAsMsoEnvelope
PrivateSubClass_Initialize()
Setenv=Application.ActiveDocument.MailEnvelope
EndSub
PrivateSubenv_EnvelopeShow()
MsgBox"TheMsoEnvelopeUIisshowing."
EndSub
PrivateSubenv_EnvelopeHide()
MsgBox"TheMsoEnvelopeUIishidden."
EndSub
EventoEnvelopeShow
SeproducecuandosemuestralainterfazdeusuarioquecorrespondealobjetoMsoEnvelope.
PrivateSubobject_EnvelopShow()
objectVariablequehacereferenciaaunobjetodetipoMsoEnvelopedeclaradaconeventosdeunmódulodeclase.
Ejemplo
ElejemplosiguienteestablecerutinasdemanipulacióndeeventosparaelobjetoMsoEnvelope.
PublicWithEventsenvAsMsoEnvelope
PrivateSubClass_Initialize()
Setenv=Application.ActiveDocument.MailEnvelope
EndSub
PrivateSubenv_EnvelopeShow()
MsgBox"TheMsoEnvelopeUIisshowing."
EndSub
PrivateSubenv_EnvelopeHide()
MsgBox"TheMsoEnvelopeUIishidden."
EndSub
EventoOnUpdate
Ocurrecuandoseefectúauncambioenlabarradecomandos.
PrivateSubCommandBars_OnUpdate()
Comentarios
EleventoOnUpdateesreconocidoporelobjetoCommandBarentodosloscontrolesdelabarradecomandos.Eleventoseactivaconcualquiercambioproducidoenunabarradecomandosoenuncontroldebarradecomandos,ocualquiercambioenelestadodeunabarradecomandosoenuncontroldeunabarradecomandos.Estoscambiospuedendeberse,porejemplo,aunaseleccióndetextoocelda.PuestoqueungrannúmerodeeventosOnUpdatepuedentenerlugarduranteelusonormal,losdesarrolladoresdebenutilizarconcautelaesteevento.EsmuyrecomendablequeesteeventoseutilicefundamentalmenteparacomprobarquesehaagregadooquitadounabarradecomandospersonalizadamedianteunCOMAddIn.
Devolverunobjetodesdeunacolección
LapropiedadItemdevuelveunsoloobjetodeunacolección.ElsiguienteejemploestablecelavariablecmdbarenunobjetoCommandBarquerepresentalaprimerabarradecomandosdelacolecciónCommandBars.
Setcmdbar=CommandBars.Item(1)
LapropiedadItemeslapropiedadpredeterminadaparalamayoríadelascolecciones,porloquepuedeescribirelmismocomandodeformamásconcisa,omitiendolapalabraclaveItem.
Setcmdbar=CommandBars(1)
Paraobtenermásinformaciónacercadeunacolecciónespecífica,consulteeltemadeAyudaolapropiedadItemdelacolección.