openoffice macros

168
Información importante sobre macros para OpenOffice Andrew Pitonyak (Traducción Arturo Garro)

Upload: juan-carlos-guartasaca-ordonez

Post on 25-Nov-2015

324 views

Category:

Documents


9 download

TRANSCRIPT

  • Informacin importante sobre macrospara OpenOffice

    Andrew Pitonyak(Traduccin Arturo Garro)

  • GraciasMuchas gracias a mi esposa Michelle por permitirme escribir este libro y por darme coraje.Tambin doy un agradecimiento a aquellos de la comunidad open-source y las listas decorreos que proveen informacin de mucha ayuda. Finalmente, un agradecimiento a aquellosque han dado ejemplos incluidos en este documento.

    AdvertenciaEl material en este documento no tiene garanta de aplicacin, accuracy, o seguridad. El usode la informacin y los macros en este documento es bajo su propio riesgo. Debe asumir quelas macros pueden llenar de basura su base de datos, el disco duro, y hacer perder todos susdatos y no me har responsable.

    LicenciaEn este momento, debe considerar que todo el material en este documento creado por mi estasujeto a http://www.openoffice.org/licenses/jca.pdf el cual da a la comunidad OpenOfficecommunity la posibilidad de usarlo en el sitio OpenOffice. Este documento contiene macrosque no estn escritas por mi. En este momento, he obtenido permiso de incluir estas macrosen este documento pero de las que no heobtenido confirmacin tambin tienen esta mismalicencia. Tomar las medidas necesarias para resolver estos problemas en este documentodurante las actualizaciones.

    Informacin de contactoAndrew Pitonyak 4446 Mobile Drive #105 Columbus, OH 43220 USA

    home: [email protected] work: [email protected] telephone: 614-442-8615

    CredencialesTengo dos bachilleratos, uno en Informtica y otro en Matemticas. Tambin tengo dosmaestras en Ciencias, uno en Matemtica Industrial Aplicada y otro en Informtica. Hetrabajado en Oakland University en Rochester Michigan, The Ohio State University enColumbus Ohio, y en The Technical University Of Dresden en Dresden Germany.

    Nota del traductorTodas las palabras claves de StarBasic dentro del texto han sido puestas en azul paradiferenciarlas. Sobra decir que deber ser escritas exactamente igual para evitar errores desintaxis. Es posible que se me haya quedado alguna palabra en ingls en el texto mientrasbuscaba su significado.

  • Tabla de contenido1 Introduccin...........................................................................................................................12 Recursos disponibles..............................................................................................................3

    2.1 Material incluido............................................................................................................32.2 Recursos en lnea (on line).............................................................................................3

    3 Ejemplos...............................................................................................................................53.1 Manipulacin de cadenas..............................................................................................5

    3.1.1 Remover caracteres de una cadena........................................................................53.1.2 Reemplazar texto en una cadena...........................................................................63.1.3 Imprimiendo los valores ASCII de una cadena.....................................................7

    3.2 Depurando e inspeccionando Macros...........................................................................73.2.1 Determinar el tipo de documento..........................................................................73.2.2 Desplegando los mtodos y propiedades de un objeto..........................................83.2.3 Desplegando las propiedades de un objeto en una hoja de clculo.......................9

    4 Ejemplos miscelneos.........................................................................................................194.1 Desplegar texto en la barra de estado..........................................................................204.2 Despliega todos los estilos en el documento actual....................................................214.3 Cambiar entre los documentos abiertos......................................................................214.4 Listar fuentes (Quebrado, no funciona) .....................................................................224.5 Imprimir el documento actual.....................................................................................234.6 Cambiando el tamao de una lista..............................................................................254.7 Open And Close Documents (And The Desktop).......................................................26

    4.7.1 Cerrar documentos OpenOffice...........................................................................264.7.2 Cargar un documento desde una URL.................................................................27

    4.8 Creando una tabla........................................................................................................294.9 Llamando un programa externo..................................................................................304.10 Leer y escribir en un archivo.....................................................................................314.11 Creando un estilo de formato numrico....................................................................324.12 Retorna una matriz Fibonnaci...................................................................................334.13 Insertar texto en un marcador....................................................................................334.14 Campos de usuario....................................................................................................33

    5 Macros de Calc...................................................................................................................355.1 Es este un libro de clculo?.........................................................................................355.2 Imprimiendo el valor de una Celda, Cadena o Frmula.............................................355.3 Estableciendo el valor de una Celda, Formato, Cadena o Frmula............................355.4 Limpiar una celda........................................................................................................365.5 Texto seleccionado, Qu es?.......................................................................................365.6 Direccin imprimible de una Celda............................................................................385.7 Insertar fechas formateadas en una Celda...................................................................395.8 Desplegar un rango seleccionado en un cuadro de dilogo........................................395.9 Rellenar un rango seleccionado con texto...................................................................405.10 Algunos estados del texto seleccionado....................................................................415.11 Cambiar el rango seleccionado a un rango de Base de Datos...................................425.12 Borrar un rango de Base de Datos.............................................................................425.13 Rango bordes de lnea...............................................................................................42

    i

  • 5.14 Ordenar un rango.......................................................................................................435.15 Imprimir todos los datos en una columna.................................................................445.16 Usando mtodos de bordes (agrupamiento)..............................................................445.17 Protegiendo sus datos................................................................................................45

    6 Macros de Write .................................................................................................................476.1 Texto seleccionado, qu es?........................................................................................476.2 Cursores de texto, qu son?.........................................................................................476.3 Andrew's Selected Text Framework...........................................................................48

    6.3.1 Hay texto seleccionado?......................................................................................486.3.2 Cmo obtener una seleccin................................................................................496.3.3 Selected Text, Which End Is Which....................................................................496.3.4 Sistema Macro de texto seleccionado..................................................................50

    El sistema rechazado ................................................................................................51 El sistema aceptable .................................................................................................51 El trabajo principal ..................................................................................................52

    6.3.5 Desplegando caracteres, un ejemplo simple........................................................536.3.6 Remover espacios y lneas vacos, un gran ejemplo...........................................53

    Qu es un espacio en blanco? ..................................................................................53 Rangos de caracteres para borrar .............................................................................53 El interativo seleccionador de texto .........................................................................54 La macro principal ...................................................................................................55

    6.3.7 Removiendo prrafos vacos, slo otro ejemplo.................................................556.4 Reemplazando espacios seleccionados usando cadenas.............................................56

    6.4.1 Comparacin de cursores y ejemplos de cadenas................................................586.5 Ponindo atributos de texto.........................................................................................686.6 End Sub Insertar texto.................................................................................................696.7 Insertar fecha formateada dentro de un documento de texto......................................716.8 Insertar una nueva pgina............................................................................................71

    6.8.1 La solucin..........................................................................................................717 Ejemplo de inversin..........................................................................................................73

    7.1 Pgina resumen...........................................................................................................737.2 Hoja de detalles...........................................................................................................737.3 Chequear duplicados en una columna.........................................................................74

    7.3.1 Direccin imprimible de una celda......................................................................747.3.2 Conteo de entradas no vacas en una columna....................................................757.3.3 Arreglo ordenado.................................................................................................767.3.4 Encontrar el duplicado.........................................................................................77

    8 Lenguaje..............................................................................................................................798.1 Comentarios................................................................................................................798.2 Variables.....................................................................................................................79

    8.2.1 Nombres..............................................................................................................798.2.2 Declaracin..........................................................................................................798.2.3 Variables globales malas y estticas....................................................................80

    ii

  • 8.2.4 Tipos....................................................................................................................81 Variables Booleanas ................................................................................................82 Variables enteras ......................................................................................................83 Variables Entero largo .............................................................................................83 Variables de moneda ................................................................................................83 Variables de Sencillos ..............................................................................................83 Variables de Dobles .................................................................................................83 Variables de Cadena ................................................................................................84

    8.2.5 Constantes............................................................................................................848.2.6 Areglos o matrices...............................................................................................84

    Option Base .............................................................................................................84 LBound(NombreMatriz[,Dimensin]) .....................................................................84 UBound(NombreMatriz[,Dimensin]) ....................................................................84 Est esta matriz definida ..........................................................................................85 Listas de matrices y ReDim .....................................................................................85

    8.2.7 Probando objetos.................................................................................................868.2.8 Condicionales......................................................................................................86

    8.3 Funciones y SubProcedimientos.................................................................................878.3.1 Parametros opcionales.........................................................................................888.3.2 Parmetros por referencia o valor........................................................................898.3.3 Recursividad........................................................................................................89

    8.4 Control de flujo...........................................................................................................908.4.1 If ... Then ... Else.................................................................................................908.4.2 IIF........................................................................................................................908.4.3 Choose.................................................................................................................918.4.4 For....Next............................................................................................................918.4.5 Do ... Loop...........................................................................................................928.4.6 Select ... Case.......................................................................................................938.4.7 Expresiones Case.................................................................................................938.4.8 While...Wend.......................................................................................................948.4.9 GoSub..................................................................................................................948.4.10 GoTo..................................................................................................................958.4.11 On GoTo............................................................................................................958.4.12 Exit....................................................................................................................968.4.13 Manejo de errores...............................................................................................97

    8.5 Miscelneos.................................................................................................................979 Operadores y precedencia.................................................................................................10110 Operadores, Instrucciones y Funciones..........................................................................103

    10.1 Operador - ..............................................................................................................10310.2 Operador * ..............................................................................................................10310.3 Operador + .............................................................................................................10310.4 Operador ^...............................................................................................................10410.5 Operador /................................................................................................................104

    iii

  • 10.6 Operador AND........................................................................................................10510.7 Funcin Abs............................................................................................................10610.8 Funcin Array.........................................................................................................10610.9 Funcin Asc............................................................................................................10710.10 Funcin ATN........................................................................................................10810.11 Instruccin Beep....................................................................................................10810.12 Funcin Blue.........................................................................................................10810.13 Palabra clave ByVal..............................................................................................10910.14 Palabra clave Call..................................................................................................10910.15 Funcin CBool......................................................................................................11010.16 Funcin CByte......................................................................................................11110.17 Funcin CDate......................................................................................................11110.18 Funcin CDateFromIso.........................................................................................11210.19 Funcin CDateToIso.............................................................................................11210.20 Funcin CDbl........................................................................................................11210.21 Instruccin ChDir..................................................................................................11310.22 Instruccin ChDrive..............................................................................................11310.23 Funcin Choose.....................................................................................................11410.24 Funcin Chr...........................................................................................................11510.25 Funcin CInt..........................................................................................................11510.26 Funcin CLng........................................................................................................11610.27 Instruccin Close...................................................................................................11610.28 Instruccin Const..................................................................................................11710.29 Funcin ConvertFromURL...................................................................................11710.30 Funcin ConvertToURL.......................................................................................11810.31 Funcin Cos..........................................................................................................11810.32 Funcin CreateUnoDialog....................................................................................11910.33 Funcin CreateUnoService...................................................................................12010.34 Funcin CreateUnoStruct......................................................................................12010.35 Funcin CSng........................................................................................................12110.36 Funcin CStr.........................................................................................................12110.37 Funcin CurDir.....................................................................................................12210.38 Funcin Date.........................................................................................................12210.39 Funcin DateSerial................................................................................................12310.40 Funcin DateValue................................................................................................12410.41 Funcin Day..........................................................................................................12410.42 Instruccin Declare...............................................................................................12510.43 Instruccin DefBool..............................................................................................12510.44 Instruccin DefDate..............................................................................................12610.45 Instruccin DefDbl................................................................................................12610.46 Instruccin DefInt.................................................................................................12710.47 DefLng Statement..................................................................................................12710.48 Instruccin DefObj................................................................................................128

    iv

  • 10.49 Instruccin DefVar................................................................................................12810.50 Instruccin Dim.....................................................................................................12810.51 Funcin DimArray................................................................................................12910.52 Funcin Dir...........................................................................................................13010.53 Instruccin Do...Loop...........................................................................................13210.54 Instruccin End.....................................................................................................13210.55 Funcin Environ....................................................................................................13310.56 Funcin EOF.........................................................................................................13410.57 Funcin EqualUnoObjects....................................................................................13410.58 Operador EQV......................................................................................................13510.59 Funcin Erl............................................................................................................13610.60 Funcin Err............................................................................................................13610.61 Funcin Error........................................................................................................13710.62 Funcin Error........................................................................................................13810.63 Instruccin Exit.....................................................................................................13810.64 Funcin Exp..........................................................................................................13910.65 Funcin FileAttr....................................................................................................14010.66 Instruccin FileCopy.............................................................................................14110.67 Funcin FileDateTime..........................................................................................14110.68 Funcin FileExists.................................................................................................14210.69 Funcin FileLen....................................................................................................14210.70 Funcin FindObject...............................................................................................14310.71 Funcin FindPropertyObject.................................................................................14310.72 Funcin Fix...........................................................................................................14410.73 For...Next Statement..............................................................................................14410.74 Funcin Format.....................................................................................................14410.75 Funcin FreeFile...................................................................................................14710.76 FreeLibrary Function.............................................................................................14710.77 Instruccin Function..............................................................................................14810.78 Instruccin Get......................................................................................................14910.79 Funcin GetAttr....................................................................................................15010.80 Funcin GetProcessServiceManager....................................................................15110.81 Funcin GetSolarVersion......................................................................................15110.82 Funcin GetSystemTicks......................................................................................15210.83 Instruccin GlobalScope.......................................................................................15210.84 Function.................................................................................................................15310.85 Function.................................................................................................................15310.86 Function.................................................................................................................15310.87 Function.................................................................................................................15410.88 Funcin Green.......................................................................................................15410.89 Palabra clave Private.............................................................................................15510.90 Palabra clave Public..............................................................................................15510.91 Funcin Red..........................................................................................................156

    v

  • 10.92 Notacin y nombres de archivo URL....................................................................15610.92.1 Notacin URL...............................................................................................15610.92.2 Rutas con espacios y otros caracteres especiales..........................................156

    11 Index................................................................................................................................159

    vi

  • 1IntroduccinOpenOffice.org Basic es el nombre del lenguaje de macros incluido con OpenOffice.org.OpenOffice.org Basic tiene mucho en comn con Visual Basic de manera que si usted sabeVisual Basic, esto ser una gran ventaja.OpenOffice.org Basic est basada en subrutinas y funciones. Estn implementadas con laspalabras clave Sub y Function. Me referir genericamente a estos como procedimientos.Cada procedimiento proveer alguna funcionalidad y puede llamar a otros procedimientos.(No est permitida la recursividad). La diferencia entre un Sub y una Function es queFunction puede retornar un valor y por eso est permitido el uso en la parte derecha de unadeclaracin.Una coleccin de procedimientos est contenido en un mdulo. Un documento puedecontener modulos, y pueden existir globalmente aparte de un documento. Colecciones demdulos estn guardados en una librera.

    ????En OpenOffice.org Basic, puede accesar el documento o la aplicacin a travs de las dosvariables globales ThisComponent y StarDesktop respectivamente. Despus de tener undocumento, puede accesar su interface. Veamos un ejemplo

    Dim oText As ObjectDim oDoc As ObjectoDoc = ThisComponent ' Obtiene el documento activooText = oDoc.Text ' Obtiene el servicio TextDocument

    ?? Gracias a Kelvin [email protected] por su aporte en cosas como quitarla palabra clave ByVal

    1

  • 2Recursos disponibles2.1Material incluidoNo olvide el poder de las pginas de ayuda. Hay mucha informacin sobre la sintaxis de lasmacros. Despus de abrir las pginas de ayuda, puede accesar el combo en la esquinasuperior izquierda que dice Help about OpenOffice.org Basic Es tambin instructivoinvestigar y usar las macros que viene en el OpenOffice. Hay, por ejemplo, macros para laspropiedades de impresin y los nombres de objetos. Las he usado para determinar que puedohacer con un objeto cuando encuentro la documentacin confusa.Abra un documento y seleccione el men Herramientas=>Macro. En la caja de lista,busque un mdulo llamado "Tools". Expanda el mdulo Tools, encontrar otro llamadoDebug. Estas macros estn implementadas para imprimir y mostrar informacin dedepuracin, servicios, atributos, etc. Especficamente vea WritedbgInfo(document) oprintdbgInfo(sheet). Son buenos ejemplos.Para usar la librera de macros Tools, deber primero cargarla. Desde el Basic IDE(Ambiente de Desarrollo Integrado)1 o desde un documento, seleccioneHerramientas=>Macro, seleccione la librera Tools y presione F5 o haga click enRun.

    2.2Recursos en lnea (on line)Hay mucha informacin disponible en lnea, el problema es encontrarla. Mientras usted sesiente confortable con este paradigma, las cosas no estn lo suficientemente claras. Aqu hayalgunos vnculos que he encontrado tiles. http://www.openoffice.org es el vnculo principal. http://api.openoffice.org contiene informacin de referencia sobre API2. Mucha

    informacin buena, solamente tiene que decifrarla. Cuando est ms a gusto con esteparadigma, esto le ayudar grandemente.

    http://api.openoffice.org/basic/man/tutorial/tutorial.pdf Usted deber tener estedocumento.

    http://udk.openoffice.org/common/man/tutorial/office_automation.html http://api.openoffice.org/common/ref/com/sun/star/module-ix.html informacin vieja de

    API que encontr til. http://documentation.openoffice.org el sitio de documentacin es muy bueno. Verifique la

    seccin how to3. Hay un documento fantstico sobre cmo usar las macros! Estdisponible enhttp://documentation.openoffice.org/HOW_TO/various_topics/How_to_use_basic_macros.sxw

    http://docs.sun.com/db/coll/999.2?q=star+office le permite bajar los manuales deStarOffice. Yo encontr el tutorial de starbasic til por los ejemplos.

    Otros sitios que contienen ejemplos y cdigo generalmente til son:

    1 N.T. Por las siglas de Integrated Development Environment 2 N.T. API son las siglas en ingls Aplication Program Interface, o Interface de programas de aplicacin.3 N.T. cmo hacerlo. La pgina est en ingls y esa expresin en intraducible.

    3

  • http://www.darwinwars.com/lunatic/bugs/oo_macros.html http://disemia.com/software/openoffice/ http://kienlein.com/pages/oo.html

    4

  • 3 Ejemplos3.1 Manipulacin de cadenasBasic ofrece algunos mtodos para la manipulacin de cadenas.

    Funcin DescripcinAsc(s$) Devuelve el valor ASCII (American Standard Code for Information

    Interchange) del primer caracter de la cadena. Genera un error si lacadena est vaca.

    LCase(s$) Devuelve la cadena en minsculas. La ayuda en lnea tiene errores en1.0.2.

    Len(s$) Retorna el tamao de la cadena s.Left(s$, n%) Devuelve los primeros n caracteres de s o una cadena vaca si n es

    cero.

    LSet s$ = TextLTrim(s$) Devuelve una cadena sin los espacios iniciales. Espacios no

    significan espacios en blanco, solamente espacios. Esto no modificala cadena.

    Mid(s$, i%[, n%]) Regresa una cadena desde la locacin i del tamao de n. Si n esomitido, retornar todos los caracteres desde i hasta el final de lacadena.

    Mid(s$, i%, n%, r$) Reemplaza la cadena del medio especificada arriba con la cadena r.Esto no modifica la cadena s. Si el valor de r es mayor que n,entonces solamente los primeros n caracteres en r sern reemplazadosen s.

    Add UCase(), RTrim, TrimEn la ayuda en lnea, el ejemplo para la conversin de minsculas/maysculas es incorrecto.Aqui est el ejemplo como debera de leerse.Sub ExampleLUCase

    Dim sVar As StringsVar = "Las Vegas"Print LCase(sVar) REM Returns "las vegas"Print UCase(sVar) REM Returns "LAS VEGAS"

    end Sub

    3.1.1 Remover caracteres de una cadenaEsto remover los caracteres de una cadena. Lo disparatado de esta macro es que sera mejorescrita con el mtodo mid(). La diferencia es que el mtodo mid() modifica la cadena actualmientras que esta retorna una nueva cadena. Yo pude hacerla usando el mtodo mid(), perome di cuenta de esto hasta que fue demasiado tarde.'Remueve cierto nmero de caracteres de una cadena

    5

  • Function RemoveFromString(s$, index&, num&) As StringIf num = 0 Or Len(s) < index Then

    'Si no se remueve nada o est fuera del rango, se devuelve la cadenaRemoveFromString = s

    ElseIf index Len(s) Then

    RemoveFromString = Left(s,index - 1)Else

    RemoveFromString = Left(s,index - 1) + Right(s, Len(s) - index - num + 1)End If

    End IfEnd Function

    3.1.2 Reemplazar texto en una cadenaEsto puede ser usado para borrar areas de una cadena especificando que la cadena dereemplazo es una cadena vaca. Inicialmente pens que poda usar el mtodo mid() para estotambin, pero este mtodo no puede hacer que la cadena sea ms grande de lo queactualmente es. Por esto tuve que escribir esta macro. No modifica la cadena actual, pero ensu lugar crea una nueva cadena con los reemplazos hechos.Rem s$ es la cadena a ser modificadaRem index es un "long" indicando dnde ser hecho el reemplazo. (base 1)Rem Si index es Len(s) entonces el texto ser insertado al final.Rem num es un "long" indicando cuntos caracteres reemplazar.Rem Si num es cero entonces nada es removido, pero la nueva cadena es insertada.Rem replaces es la cadena a reemplazar dentro de la cadena original.Function ReplaceInString(s$, index&, num&, replaces$) As String

    If index

  • End Function

    3.1.3 Imprimiendo los valores ASCII de una cadenaEsto se ve como una macro rara, pero yo la uso para decidir como ser guardado el texto enel documento. Esto imprime una cadena completa como una serie de nmero s ASCII.Sub PrintAll

    PrintAscii(ThisComponent.text.getString())End SubSub PrintAscii(TheText As String)

    If Len(TheText) < 1 Then Exit SubDim msg$, i%msg = ""For i = 1 To Len(TheText)

    msg = msg + Asc(Mid(TheText,i,1)) + " "Next iPrint msg

    End Sub

    3.2 Depurando e inspeccionando MacrosFrecuentemente es dificil determinar qu mtodos y propiedades estn disponibles en unobjeto. Los mtodos en esta seccin pueden ser de ayuda.

    3.2.1 Determinar el tipo de documentoEsta macro viene con OpenOffice y est incluida aqu como una demostracin sobre cmodeterminar el tipo de documento.'******************************************************************

    'Autor: Incluida con OpenOffice'

    Function GetDocumentType(oDoc)On Local Error GoTo NODOCUMENTTYPEIf oDocument.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Then

    GetDocumentType() = "scalc"ElseIf oDocument.SupportsService("com.sun.star.text.TextDocument") Then

    GetDocumentType() = "swriter"ElseIf oDocument.SupportsService("com.sun.star.drawing.DrawingDocument") Then

    GetDocumentType() = "sdraw"ElseIf oDocument.SupportsService("com.sun.star.formula.FormulaProperties") Then

    GetDocumentType() = "smath"End IfNODOCUMENTTYPE:If Err 0 Then

    GetDocumentType = ""Resume GOONGOON:

    End IfEnd Function

    7

  • 3.2.2 Desplegando los mtodos y propiedades de un objetoEsta es una excelente subrutina. El primer parametro es el objeto en cuestin. El segundoparametro puede ser para desplegar los mtodos y cualquier otra cadena para desplegar laspropiedades del objeto. La lista de propiedades o mtodos es frecuentemente tan larga queexcede el tamao de la pantalla. Esta subrutina evita esto al partir la lista en piezas pequeas.'******************************************************************

    'A subroutine to display all the methods or properties of an input 'Author: Tony Bloomfield'email: [email protected] DisplayMethods(oObj As Object, SWhat As String)

    DIM sMethodList As String, sMsgBox As StringDIM fs, ep As IntegerDIM i As IntegerDIM EOL As Boolean

    if sWhat = "" thensMethodList = oObj.DBG_methods

    elsesMethodList = oObj.DBG_Properties

    endiffs = 1EOL = FALSE

    While fs

  • 3.2.3 Desplegando las propiedades de un objeto en una hoja declculo.Esta macro debe ser ejecutada para creer. Herr Hermann Kienlein hizo un impresionantetrabajo con esto. Esta macro crea una nueva hoja de clculo y la rellena con informacinsobre los objetos. Yo modifiqu extensivamente esta macro porque usaba variables globales.Las variables globales interferan con mis propias variables locales. Esto me ayudaba a usarlaen mi propio cdigo existente.'******************************************************************

    'Author: Hermann Kienlein'email: [email protected]'online: http://www.kienlein.com/pages/oo.htmlOption Explicit ' Fuerza a declarar las variablesSub Main

    MainObjectDisplay(ThisComponent)End Sub

    ' ------------------------------------------------------

    'Crea un nuevo documento y luego crea nuevas hojas en el documento.' Da nombres a las hojas e inserta informacin en las mismas.Sub MainObjectDisplay(oObject As Object)

    Dim oInfo As Object, oDeskNeu As Object, oNewDoc As ObjectDim sNewUrl As String, nSheetsUsed As LongDim sInterfaces As String

    nSheetsUsed = 0oDeskNeu = createUnoService("com.sun.star.frame.Desktop")'sNewUrl = "staroffice.factory:scalc" ' This did not worksNewUrl = "private:factory/scalc"oNewDoc = oDeskNeu.loadComponentFromURL( sNewUrl,"_blank",0,NoArgs())ObjInfo(oNewDoc, nSheetsUsed, "ThisComponent", oObject)

    On Local Error GoTo AllDonesInterfaces = oObject.dbg_supportedinterfacesOn Local Error GoTo NoControllerIf InStr(sInterfaces, "com.sun.star.frame.XModel") 0 Then

    oInfo = oObject.getCurrentController()ObjInfo(oNewDoc, nSheetsUsed, "getCurrentController", oInfo)

    End IfNoController:

    On Local Error GoTo NoDocInfo'??

    ' If InStr(sInterfaces, "com.sun.star.document.XDocumentInfoSupplier") 0 ThenoInfo = oObject.getDocumentInfo()ObjInfo(oNewDoc, nSheetsUsed, "getDocumentInfo", oInfo)

    9

  • ' End IfNoDocInfo:

    On Local Error GoTo NoSelection'??

    ' If InStr(sInterfaces, "com.sun.star.frame.XSelectionSupplier") 0 ThenoInfo = oObject.getCurrentSelection()ObjInfo(oNewDoc, nSheetsUsed, "getCurrentSelection", oInfo)

    ' End IfNoSelection:

    On Local Error GoTo NoLibraryContainerIf InStr(sInterfaces, "com.sun.star.script.XStarBasicAccess") 0 Then

    oInfo = oObject.getLibraryContainer()ObjInfo(oNewDoc, nSheetsUsed, "getLibraryContainer", oInfo)

    End IfNoLibraryContainer:

    On Local Error GoTo NoViewDataIf InStr(sInterfaces, "com.sun.star.document.XViewDataSupplier") 0 Then

    oInfo = oObject.getViewData()ObjInfo(oNewDoc, nSheetsUsed, "getViewData", oInfo)

    End IfNoViewData:

    On Local Error GoTo NoEventsIf InStr(sInterfaces, "com.sun.star.document.XEventsSupplier") 0 Then

    oInfo = oObject.getEvents()ObjInfo(oNewDoc, nSheetsUsed, "getEvents", oInfo)

    End IfNoEvents:AllDone:On Local Error GoTo 0

    End Sub

    ' ------------------------------------------------------

    Sub ObjInfo(oDoc As Object, nSheetsUsed&, sSheetName$, obj As Object)Dim i2 As Integer, bProp As BooleanDim nRow&, nCol&, oSheet As ObjectnRow = 0ncol = 0'on error goto err_ObjInfoIf Not isNull(obj) Then

    GoToNextSheet(oDoc, nSheetsUsed, sSheetName)oSheet = oDoc.Sheets.getByIndex(nSheetsUsed-1)'oCell.String=CStr(obj.WindowServiceName)SetCell(nCol, nRow, oSheet, TypeName(obj), 1, 0)SetCell(nCol, nRow, oSheet, VarType(obj), -1, 2)

    10

  • i2 = InStr(obj.dbg_methods,"getPropertySetInfo")If i2 > 0 Then

    bProp = trueElse

    bProp = falseEnd IfListItems (nCol, nRow, obj.dbg_methods, ";", obj, true, oSheet)MoveRow(nCol, nRow, 2)If Not isNull (obj.dbg_properties) Then

    'NextSheet()ListItems (nCol, nRow, obj.dbg_properties, ";", obj, false, oSheet)

    End IfIf bProp Then

    GetProps(nCol, nRow, obj, oSheet)bProp = false

    End IfMoveRow(nCol, nRow, 1)ListItems (nCol, nRow, obj.dbg_supportedinterfaces, chr$(10), obj, false, oSheet)'CleanDbg 'noch keine Ahnung, fr was das gut ist'NextSheet()

    End Ifexit_ObjInfo:

    Exit Suberr_ObjInfo:

    'print errIf err=423 Then

    obName = inputbox("Das Objekt hat keine name-Eigenschaft."_+" Welchen Namen soll das neue Tabellenblatt haben?")

    Resume NextElse

    msgbox error$, 16Resume exit_ObjInfo

    End IfEnd Sub

    ' ------------------------------------------------------

    ' ListItems - bergebenen String nach Trennzeichen durchsuchen ' und Zeilenweise ausgeben' ------------------------------------------------------

    Sub ListItems(nCol&, nRow&, itemstring$, sep$, oBj As Object, gt As Boolean, oSheet As Object)'dim oCurs As ObjectDim frag As String, sleft As String, sPrf As StringDim act As Integer, ex As Integer, nextpos As IntegerDim nextchr As Integer, lstr As Integer, lfrag As IntegerDim ch As Integerlstr = Len(itemstring)act =1'Everything left of the first colonSetCell(nCol, nRow, oSheet, Left(itemstring,InStr(1,itemstring, ":")), 0, 0)'If there is no colon, then we are done hereIf InStr(1,itemstring,":") < 1 Then

    11

  • SetCell(nCol, nRow, oSheet, itemstring, 0, 0)Exit Sub

    End Ifact= act+InStr(1,itemstring,":") 'also jetzt auf dem ersten :'act = act+1 'ein Zeichen weiter positionierenMoveRow(nCol, nRow, 1)While act "" Then

    Donextchr = Asc(Mid(frag,1,1)If nextchr = "10" Then

    Mid(frag,1,1," ")frag = LTrim(frag) 'linksbndig ausrichten

    Elseexit Do

    End IfLoop

    End IfMoveRow(nCol, nRow, 1)SetCell(nCol, nRow, oSheet, frag, 0, 0)If gt Then

    GtVal(nCol, nRow, frag,oBj, oSheet)End If

    Wenditemstring = ""

    End Sub

    ' ------------------------------------------------------

    ' Sub um Properties auszulesen, Object mu allerdins' .PropertySetInfo.Methode' untersttzenSub GetProps(nCol&, nRow&, obj, oSheet As Object)

    Dim vVariant as Variantdim nVar As Integerdim mProperties as variantdim mProps1 as variantdim sItemDescriptiondim nCount As Integerdim iP As Integer, iP1 As Integerdim n$dim pdim tmp$dim j%dim vItemdim sString

    12

  • MoveRow(nCol, nRow, 2)mProperties = obj.PropertySetInfo.PropertiesnCount = UBound(mProperties)-LBound(mProperties) + 2SetCell(nCol, nRow, oSheet, "Properties With Values", 0, 1)SetCell(nCol, nRow, oSheet, "Name", 1, 0)SetCell(nCol, nRow, oSheet, "Value", -1, 1)For iP = LBound(mProperties) To UBound(mProperties)

    p = mProperties(iP)n$ = p.namevVariant = obj.getPropertyValue(n$)SetCell(nCol, nRow, oSheet, n$, 1, 0)

    nVar = VarType(vVariant)Select Case nVarCase 1 'isNull

    SetCell(nCol, nRow, oSheet, "NULL-VALUE", 0, 1)Case 9 'object

    If Not isNull (vVariant.dbg_properties) Then ListItems (nCol, nRow, vVariant.dbg_properties, ";", vVariant, false, oSheet)MoveRow(nCol, nRow, 2)

    End Ifif not isNull (vVariant.dbg_supportedinterfaces) then

    ListItems (nCol, nRow, vVariant.dbg_supportedinterfaces, _chr$(10), vVariant, false, oSheet)

    MoveRow(nCol, nRow, 2)End IfIf Not isNull (vVariant.dbg_methods) Then

    ListItems (nCol, nRow, vVariant.dbg_methods, ";", _vVariant, false, oSheet)

    MoveRow(nCol, nRow, 2)End If

    Case ElseIf IsArray(vVariant) Thentmp$ = ""For j% = LBound(vVariant) To UBound(vVariant)

    vItem = vVariant(j%)If IsNull(vItem) Then

    sItemDescription = "NULL-Value"ElseIf IsObject(vItem) Then

    If Not isNull(vItem.dbg_properties) ThensItemDescription = CStr(vItem.dbg_properties)

    End IfElse

    sItemDescription = cstr(vItem)End Iftmp$ = tmp$ & sItemDescription

    Next j%ListItems(nCol, nRow, tmp$,";",vVariant,false, oSheet)

    ElseSetCell(nCol, nRow, oSheet, cstr(vVariant), 0, 1)

    End Ifend select

    13

  • MoveRow(nCol, nRow, 1)MoveCol(nCol, nRow, -1)

    Next iPEnd Sub

    ' ------------------------------------------------------

    ' GetValue - Inhalte auslesen' ------------------------------------------------------

    Sub GtVal (nCol&, nRow&, sGVal As String, oBje As Object, oSheet As Object)dim is1 As Integer, iAr As Integerdim s1 As String, s2 As String, s3 As Stringdim aR1(10) as variantdim o1 As Objectis1 =InStr(sGVal," ") 'erstes Space suchens1 = Mid(sGval,1,is1)s2 = Mid(sGVal,1,is1," ")sGVal = LTrim(sGVal)is1 = InStr(sGVal," ")s2 = Mid(sGVal,1,is1)s1 = LTrim(s1)s1= RTrim(s1)s2 = LTrim(s2)s2 = RTrim(s2)Select Case s1Case "SbxSTRING"

    Select Case s2Case "getURL"

    s3 = oBje.getURL()Case "getLocation"

    s3 = oBje.getLocation()Case "getImplementationName"

    s3 = oBje.getImplementationName()Case "getUserFieldName"

    s3 = oBje.getUserFieldName(0)Case "getUserFieldValue"

    s3 = oBje.getUserFieldValue(0)Case Else

    s3 = s2End Select's3 = oBje.&s2'msgbox(CStr(oBje)&s2)MoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    Case "SbxBOOL"Select Case s2Case "hasControllersLocked"

    s3= CStr(oBje.hasControllersLocked())Case "isModified"

    s3= CStr(oBje.isModified())Case "AutoloadEnabled"

    14

  • s3= CStr(oBje.AutoloadEnabled())Case "hasElements"

    s3= CStr(oBje.hasElements())Case "IsEncrypted"

    s3= CStr(oBje.IsEncrypted())Case "isReadonly"

    s3= CStr(oBje.isReadonly())Case Else

    s3 = " "End SelectMoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    Case "SbxINTEGER"Select Case s2Case "getUserFieldCount"

    s3 = CStr(oBje.getUserFieldCount())Case "EditingCycles"

    s3 = CStr(oBje.EditingCycles())Case Else

    s3 = ""End SelectMoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    Case "SbxLONG"Select Case s2Case "getCount"

    s3 = CStr(oBje.getCount())Case Else

    s3 = ""End SelectMoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    Case "SbxOBJECT"Select Case s2Case "getElementType"

    s3 = CStr(VarType(oBje.getElementType()))MoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    Case "getText"o1 = oBje.getText()MoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, o1.dbg_properties, 3, 0)SetCell(nCol, nRow, oSheet, o1.dbg_methods, -7, 0)

    Case ElseEnd Select

    Case "SbxARRAY"Select Case s2Case "getImplementationId"

    aR1() = oBje.getImplementationId()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getImplementationID()) To _

    15

  • UBound(oBje.getImplementationID())s3 = CStr(aR1(iAr))SetCell(nCol, nRow, oSheet, s3, 1, 0)

    next iArMoveCol(nCol, nRow, -(4+1+UBound(oBje.getImplementationID())))

    Case "getArgs"'?? Why is this commented out to print?aR1() = oBje.getArgs()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getArgs()) To UBound(oBje.getArgs())

    o1 = aR1(iAr)s3 = o1.dbg_properties'GetProps(aR1(iAr)'oCell.String = s3MoveCol(nCol, nRow, 1)

    Next iArMoveCol(nCol, nRow, -(4+1+UBound(oBje.getArgs())))

    Case "getTypes"aR1() = oBje.getTypes()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getTypes()) To UBound(oBje.getTypes())

    o1 = aR1(iAr)s3 = VarType(o1)SetCell(nCol, nRow, oSheet, s3, 1, 0)

    Next iArMoveCol(nCol, nRow, -(4+1+UBound(oBje.getTypes())))

    Case "getElementNames"aR1() = oBje.getElementNames()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getElementNames()) To _

    UBound(oBje.getElementNames())'o1 = aR1(iAr)'s3 = VarType(o1)SetCell(nCol, nRow, oSheet, aR1(iAr), 1, 0)

    Next iArMoveCol(nCol, nRow, -(4+1+UBound(oBje.getElementNames())))

    Case "getSupportedServiceNames"aR1() = oBje.getSupportedServiceNames()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getSupportedServiceNames()) To _

    UBound(oBje.getSupportedServiceNames())'o1 = aR1(iAr)'s3 = VarType(o1)SetCell(nCol, nRow, oSheet, aR1(iAr), 1, 0)

    Next iArMoveCol(nCol, nRow, _ -(4+1+UBound(oBje.getSupportedServiceNames())))

    Case "getPrinter"aR1() = oBje.getPrinter()MoveCol(nCol, nRow, 4)For iAr = LBound(oBje.getPrinter()) To UBound(oBje.getPrinter())

    16

  • o1 = aR1(iAr)s3 = CStr(VarType(aR1(iAr)))'?? We never print thisMoveCol(nCol, nRow, 1)

    Next iArMoveCol(nCol, nRow, -(4+1+UBound(oBje.getPrinter())))

    Case Elses3 = " "MoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    End SelectCase Else

    s3 = " "MoveCol(nCol, nRow, 4)SetCell(nCol, nRow, oSheet, s3, -4, 0)

    End Selectend sub

    ' -----------------------------------------------------

    Sub SetCell(nCol&, nRow&, oSheet As Object, s$, colInc%, rowInc%)oSheet.getCellByPosition(nCol, nRow).String = s$If colInc 0 Then MoveCol(nCol, nRow, colInc%)If rowInc 0 Then MoveRow(nCol, nRow, rowInc)

    End Sub

    ' ------------------------------------------------------

    Sub MoveCol(nCol&, nRow&, i%)nCol = nCol + iIf nCol < 0 Then

    nRow = nRow + 1nCol = 0

    End IfEnd Sub

    ' ------------------------------------------------------

    Sub MoveRow(nCol&, nRow&, i%)nRow = nRow + iIf nRow < 0 Then

    nRow = 0End If

    End Sub

    ' ------------------------------------------------------

    'Create a new sheet if required with the given name.Sub GoToNextSheet(oDoc As Object, nSheetsUsed&, sSheetName$, Optional nWhichSheet%)

    Dim oSheets As Object, oSheet As ObjectoSheets = oDoc.SheetsIf isNumeric(nWhichSheet) Then

    oSheets.insertNewByName("Sheet"&CStr(oSheets.Count()+1), nWhichSheet)oSheet = oSheet.getByIndex(nWhichSheet)

    Else

    17

  • If nSheetsUsed > oSheets.Count() - 1 ThennSheetsUsed = oSheets.Count() - 1oSheets.insertNewByName("Sheet"&CStr(oSheets.Count()+1), _

    nSheetsUsed)End IfoSheet = oSheets.getByIndex(nSheetsUsed)nSheetsUsed = nSheetsUsed + 1

    End IfoSheet.Name = sSheetName

    End Sub

    18

  • 4 Ejemplos miscelneos

    19

  • 4.1 Desplegar texto en la barra de estado'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected]'Hay dos mtodos que se pueden usar para obtener 'el indcador de estadoFunction ProgressBar

    ProgressBar = ThisComponent.CurrentController.StatusIndicator'o tambin'ProgressBar = StarDesktop.getCurrentComponent.StatusIndicator

    End Function

    REM Despliega texto en la barra de estadoSub StatusText(sInformation)

    Dim sSpaces As StringDim iLen,iRest As Integer'sSpaces=SPACE(270)iLen=Len(sInformation)iRest=270-iLenProgressBar.start(sInformation+SPACE(iRest),0)

    End Sub

    20

  • 4.2 Despliega todos los estilos en el documento actualEsto no es tan grato como parece. Los siguientes estilos existen en un documento de texto:CharacterStyles, FrameStyles, NumberingStyles, PageStyles, y ParagraphStyles. '******************************************************************

    'Author: Andrew Pitonyak'email: [email protected] DisplayAllStyles

    Dim mFamilyNames As VariantDim mStyleNames As VariantDim sMsg As StringDim oFamilies As ObjectDim oStyle As ObjectDim oStyles As ObjectoFamilies = ThisComponent.StyleFamiliesmFamilyNames = oFamilies.getElementNames()For n = LBound(mFamilyNames) To UBound(mFamilyNames)

    sMsg = ""oStyles = oFamilies.getByName(mFamilyNames(n))mStyleNames = oStyles.getElementNames()For i = LBound(mStyleNames) To UBound (mStyleNames)

    sMsg=sMsg + i + " : " + mStyleNames(i) + Chr(13)If ((i + 1) Mod 20 = 0) Then

    MsgBox sMsg,0,mFamilyNames(n)sMsg = ""

    End IfNext iMsgBox sMsg,0,mFamilyNames(n)

    Next nEnd Sub

    4.3 Cambiar entre los documentos abiertosSub Main

    Dim oDesktop As Object, oDocs As ObjectDim oDoc As Object, oComponents As Object'The hasMoreElements() will fail with the oDesktop,'I do not know why!'oDesktop = createUnoService("com.sun.star.frame.Desktop")oComponents = StarDesktop.getComponents()oDocs = oComponents.createEnumeration()Do While oDocs.hasMoreElements()

    oDoc = oDocs.nextElement()Loop

    End Sub

    4.4 Listar fuentes (Quebrado, no funciona) Esto no funciona... solo para que lo sepan

    21

  • Sub ListFontsDim document As ObjectDim CursorDim oText As ObjectDim mySelection As ObjectDim displayString As String

    document=ThisComponentdisplayString = ""oStyleFamilies = document.StyleFamilies'CharacterStyles, ParagraphStyles, FrameStyles, PageStyles 'NumberingStyles, CellStyles, ShapeStyles oStyles = oStyleFamilies.getByName("CharacterStyles")For n = 0 to oStyles.Count - 1

    oStyle = oStyles(n) displayString = displayString & "name = (" & oStyle.Name & ") Font = (" & oStyle.CharFontName& ") Style = (" & CharStyleName & ")" & chr(13)

    Next n

    Msgbox(displayString, 64, "Styles")End Sub

    22

  • 4.5 Imprimir el documento actualLa ejecuto y puedo imprimir. Me detuve cuando trat de ver como imprimir un documentoA4 en mi impresora Letter! Deseo hacerlo por defecto, pero decid que eso no merece mitiempo por ahora.'******************************************************************

    'Author: Andrew Pitonyak'email: [email protected] PrintCurrentDocument

    Dim mPrintopts1(), x as Variant'Dimensioned at 0, if you set any other properties, be certain to set this to a higher value....Dim mPrintopts2(0) As New com.sun.star.beans.PropertyValueDim oDocument As Object, oPrinter As ObjectoDocument = ThisComponent

    '***********************************

    'Do you want to choose a certain printer'Dim mPrinter(0) As New com.sun.star.beans.PropertyValue'mPrinter(0).Name="Name"'mPrinter(0).value="Other printer"'oDocument.Printer = mPrinter()'***********************************

    'To simply print the document do the following:'oDocument.Print(mPrintopts1())'***********************************

    'To print pages 1-3, 7, and 9'mPrintopts2(0).Name="Pages"'mPrintopts2(0).Value="1-3; 7; 9"'oDocument.Printer.PaperFormat=com.sun.star.view.PaperFormat.LETTER'DisplayMethods(oDocument, "propr")'DisplayMethods(oDocument, "")oPrinter = oDocument.getPrinter()MsgBox "printer is from " + LBound(oPrinter) + " to " + UBound(oPrinter)sMsg = ""For n = LBound(oPrinter) To UBound(oPrinter)

    sMsg = sMsg + oPrinter(n).Name + Chr(13)Next nMsgBox sMsg,0,"Print Settings"

    'DisplayMethods(oPrinter, "propr")'DisplayMethods(oPrinter, "")'mPrintopts2(0).Name="PaperFormat"'mPrintopts2(0).Value=com.sun.star.view.PaperFormat.LETTER'oDocument.Print(mPrintopts2())

    End Sub

    23

  • Algo como esto imprime la pgina actual!dim aPrintOps(0) as new com.sun.star.beans.PropertyValueoDoc = ThisComponentoViewCursor = oDoc.CurrentController.getViewCursor()aPrintOps(0).Name = "Pages"aPrintOps(0).Value = trim(str(oViewCursor.getPage()))oDoc.print(aPrintOps())

    24

  • 4.6 Cambiando el tamao de una listaComentario desde el sitio Web.

    Para mi, esta macro no lo es.'******************************************************************

    'Author: Unknown'email: http://ui.openoffice.org/howto/index.htmlOption ExplicitSub SetPickListTen

    ChangePickListSize( 10 )End Sub

    Sub ChangePickListSize( nSize As Integer )' access the global configuration providerDim aConfigProvider As ObjectaConfigProvider = createUnoService( "com.sun.star.configuration.ConfigurationProvider" )

    ' create an access object for the history nodeDim aHistorySettings As ObjectDim aParams(0) As new com.sun.star.beans.PropertyValueaParams(0).Name = "nodepath"aParams(0).Value = "/org.openoffice.Office.Common/History"aHistorySettings = aConfigProvider.createInstanceWithArguments

    ( "com.sun.star.configuration.ConfigurationUpdateAccess", aParams() )

    ' set the pick list sizeaHistorySettings.replaceByName( "PickListSize", nSize )

    ' commit the changes doneaHistorySettings.commitChanges

    End SubSi desea hacerlo manualmente, aqui est la forma dificil de hacerlo1. Haga una o dos copias completas de los archivos apropiados antes de empezar

    ~/staroffice6.0/user/config/registry/instance/org/openoffice/Office/common.xml~/openoffice/user/config/registry/instance/org/openoffice/Office/common.xml

    2. Inicie TextPad (www.textpad.com) o cualquier otro editor de texto que maneje archivosXML bien. No use el Block de Notas (Notepad de windows); este obtiene cientos decuadritos curiosos y mientras se intenta tecnicamente de estar OK, es rrrrrrealmente dificilde leer archivos XML en l.

    3. Abra el siguiente archivo, para StarOffice o OpenOffice, cualquiera que est usando:

    25

    Bueno, use la macro. Mientras este error no sea corregido, necesitar terminarla tarea despus de aplicar la macro, como un apagado corriente, los valoresescritos por la macro sern sobreescritos.Hay algunas otras maneras para lograr lo mismo, pero involucra meterse conarchivos locales que son una implementacin detallada de la configuracin delbackend, que no voy a mencionar aqui :).

  • ~/staroffice6.0/user/config/registry/instance/org/openoffice/Office/common.xml~/openoffice/user/config/registry/instance/org/openoffice/Office/common.xml

    4. Busque la etiqueta ; las entradas son alfabticas. Ver algo como lo siguiente:

    StarOffice XML (Writer) 4. file:///C:/docs/newdocs/story.sxw file:///C:/docs/newdocs/story.sxw [y luego, un poco ms entradas ...] StarOffice XML (Writer) file:///C:/docs/newdocs/story.sxw file:///C:/docs/newdocs/story.sxw [y luego, con tres entradas ms; esta es la lista de archivos recientesdesplegada bajo el men archivo...]

    5. Reemplace en contenido entero de la etiqueta , es decir desde a inclusive, con el siguiente texto. El ejemplo cambia StarOffice para desplegarlos 9 archivos ms recientes; digite el nmero que desee. Imagino que no es buena ideahacerlo muy grande, pero no conozco si existe un lmite de archivos, si hay alguno.

    9

    4.7 Open And Close Documents (And The Desktop)4.7.1 Cerrar documentos OpenOfficeTodos los documentos OpenOffice y los objetos en marcos (servicios) soportan la interfaceXcerrable. Para cerrar estos objetos deber llamar close(bForce As Boolean). Si bForce esfalso, entonces el objeto puede rehusar a cerrarse. Si bForce es verdadero, entonces el objetono puede rehusarse a cerrarse.El escritorio no soporta la interface Xcerrable por razones de herencia. El mtodo terminate()es usado para esto. Este mtodo causa un evento-terminacin que ser transmitido a todos losque escuchen. Si no se devuelve TerminationVetoException, una notificacin de evento-

    26

  • terminacin es transmitido y se devuelve un valor verdadero. De lo contrario, se transmite unaborte-evento-terminacin y se devuelve un valor falso. Para citar a Mathias Bauer, elmtodo terminate() estuvo ahi por mucho tiempo, mucho antes que descubrimos que no es lamanera correcta de manejar el cierre de documentos o ventanas. Si este no hubiera estadoah, podramos haber usado Xcerrable para el escritorio tambin.[Bauer001]If HasUnoInterfaces(oDoc, "com.sun.star.util.XCloseable") Then

    oDoc.close(true)Else

    oDoc.disposeEnd IfObtuve los siguientes metodos de Sasa Kelecevic [[email protected]] que no he probado??'------------- salvar_y_cerrar --------------'Use uno de estos mtodos'oDocClose=StarDesktop.CurrentFrame.Close'oDocClose=StarDesktop.ActiveFrame.Close '------------- cerrar_no_salvar ---------------------'Use uno de estos mtodos'oDocClose=ThisComponent.Dispose'oDocClose=StarDesktop.ActiveFrame.Dispose

    4.7.2 Cargar un documento desde una URLPara cargar un documento desde una URL, use el mtodo LoadComponentFromURL() delescritorio. Esto carga un componente dentro de un marco, nuevo o existente.Sintaxis:loadComponentFromURL(

    string aURL,string aTargetFrameName, long nSearchFlags, sequence< com::sun::star::beans::PropertyValue > aArgs)

    Returna:com::sun::star::lang::XComponentParmetros:aURL: URL para el documento a cargar. Para crear un nuevo documento, use

    "private:factory/scalc", "private:factory/swriter", etc. aTargetFrameName: Nombre del marco que contendr el documento. Si el nombre delmarco

    existe, ser usado , de lo contrario ser creado. "_blank" crea un nuevo marco, "_self"usa el marco actual, "_parent" usa el marco padre, y "_top" usa el primer marco de laruta actual en el rbol.

    nSearchFlags: Usa los valores de FrameSearchFlag para especificar cmo encontrar elnombre del marco destino (aTargetFrameName). Normalmente, simplemente use 0.http://api.openoffice.org/common/ref/com/sun/star/frame/FrameSearchFlag.html

    27

  • # Nombre Descripcin0 Auto SELF+CHILDREN1 PARENT Incluye el marco padre2 SELF Incluye el marco inicial4 CHILDREN Incluye los marcos hijos del marco inicial8 CREATE Ser creado un marco, si no existe16 SIBLINGS Incluye otros marcos hijos del marco inicial32 TASKS Incluye todos los marcos en todas las tareas de la actualjerarqua de marcos.

    23 ALLIncluye todos los marcos de las otras tareas. 23 =1+2+4+16 = PARENT + SELF + CHILDREN +SIBLINGS.

    55 GLOBALBusca en toda la jerarqua de marcos. 55 = 1+2+4+16+32= PARENT + SELF + CHILDREN + SIBLINGS +TASKS.

    63 GLOBAL + CREATEaArgs: Especifica el comportamiento especifico del componente o filtro. "ReadOnly" con un

    valor boleano especifica que el documento est abierto en modo slo lectura."FilterName" especifica el tipo de componente para crear y el tipo de filtro a usar, porejemplo: "scalc: Text - csv". Verhttp://api.openoffice.org/common/ref/com/sun/star/document/MediaDescriptor.html

    Ejemplo:Rem Cargar dos documentos en el mismo marco!oDesk = createUnoService("com.sun.star.frame.Desktop")Dim NoArgs()Rem marco "MyName" ser creado si no existe porque incluye "CREATE"oDoc1 = oDesk.LoadComponentFromUrl(sUrl_1, "MyName", 63, Noargs())Rem Usar el marco existente "MyName" oDoc2 = oDesk.LoadComponentFromUrl(sUrl_2, "MyName", 55, Noargs())

    Tip En 1.1 el marco implementa loadComponentFromURL por eso puedeusar:

    oDoc = oDesk.LoadComponentFromUrl(sUrl_1, "_blank", 0, Noargs())oFrame = oDoc.CurrentController.FrameoDoc = oFrame.LoadComponentFromUrl(sUrl_2, "", 2, Noargs())Note the search flag arguments and the empty frame name argument.

    Advertencia En 1.1 solamente puede volver a usar un marco si conoce su nombre.Ejemplo:Sub insertDocumentAtCursor(sFileUrl As String, oText As Object, oDoc As Object)

    28

  • Dim oCur As ObjectDim oProperties As ObjectoCur=oText.createTextCursorByRange(oDoc.getCurrentController().getViewCursor().getStart()) oCur.insertDocumentFromURL(sFileURL,oProperties)

    End SubEjemplo:'------------- open_new --------------------'Dim NoArgs()'oDocNew=StarDesktop.loadComponentFromURL("private:factory/swriter","_blank",0,NoArgs())'------------- open_old_file ---------------'Dim NoArg()'oDocOldFile=StarDesktop.loadComponentFromURL(sUrl,"_blank",0,NoArg())

    4.8 Creando una tablaNo tengo nada que hacer con estas macros de Kienlein??Sub InsertNextItem(what, oCursor, oTable)

    Dim oCelle As Object'name of the cell range that is selected by this cursorsName = oCursor.getRangeName()' The cell name will be something like D3oCelle = oTable.getCellByName(sName)oCelle.String = whatoCursor.goRight(1,FALSE)

    End Sub

    Function CreateTable() As ObjectoDocument = StarDesktop.ActiveComponentoTextTable = oDocument.createInstance("com.sun.star.text.TextTable") CreateTable =

    oTextTableEnd Function

    29

  • 4.9 Llamando un programa externoEste ejemplo de llamada de un programa externo y salvar la salida fue muy lento por elcreador de la macro. Aun no lo he probado. El programa my_filter pone su salida en /tmp/output.txt. Pero el filtro es muy lento y debo esperar a que termine. Pero esta no es la mejormanera de hacerlo. Cmo puedo canalizar una cadena por medio de un programa externo?Algn ejemplo? ?? Pruebe esto!'******************************************************************

    'Author: Pavel Jank'email: [email protected] CallExternalProgram ()

    Dim Document As ObjectDocument = ThisComponent' Andrew says that this looks like an extra textpara = Document.text.Text.getText()shell ("/home/pavel/my_filter", 2, "'" & para.getString() & "'", True) wait (9000)para.setString(ReturnContentsOfFile("/tmp/output.txt"))

    End Sub

    30

  • 4.10 Leer y escribir en un archivoEste ejemplo lee un nmero desde un archivo de texto. Este valor es convertido en nmero eincrementado. El nmero es escrito de nuevo en el archivo como una cadena.'******************************************************************

    'Author: Andrew Pitonyak'email: [email protected] Read_Write_Number_In_File

    DIM CountFileName As String, NumberString As StringDIM LongNumber As Long, iNum As IntegerDim oDocument As ObjectCountFileName = "C:\Andy\My Documents\oo\NUMBER.TXT"NumberString = "00000000"LongNumber = 0'On Local Error Goto NoFileIf FileExists(CountFileName) Then

    ON ERROR GOTO NoFileiNum = FreeFileOPEN CountFileName for input as #iNum LINE INPUT #iNum ,NumberStringCLOSE #iNum MsgBox("Read " & NumberString, 64, "Read")

    NoFile:If Err 0 Then

    Msgbox("Can not read " & CountFileName, 64, "Error")NumberString = "00000001"

    End IfOn Local Error Goto 0

    ElseMsgbox(CountFileName & " does NOT exists", 64, "Warning")NumberString = "00000001"

    End If

    ON ERROR GOTO BadNumberLongNumber = Int(NumberString)LongNumber = LongNumber + 1

    BadNumber:If Err 0 Then

    Msgbox(NumberString & " is not a number", 64, "Error")LongNumber = 1

    End IfOn Local Error Goto 0NumberString=Trim(Str(LongNumber))While LEN(NumberString) < 8

    NumberString="0"&NumberStringWendMsgBox("Number is (" & NumberString & ")", 64, "Information")iNum = FreeFileOPEN CountFileName for output as #iNumPRINT #iNum,NumberString

    31

  • CLOSE #iNumEnd Sub

    32

  • 4.11 Creando un estilo de formato numricoSi desea un formato particular de nmero, entonces puede observar si existe y crearlo si no lotiene. Para ms informacin sobre fomatos validos, vea los contenidos de la ayuda en lostpicos number formats; formats. Estos pueden ser bastante complejos.'******************************************************************

    'Author: Andrew Pitonyak'email: [email protected] FindCreateNumberFormatStyle (_

    sFormat As String, Optional doc, Optional locale)Dim oDocument As ObjectDim aLocale as new com.sun.star.lang.LocaleDim oFormats As ObjectoDocument = IIf(IsMissing(doc), ThisComponent, doc)oFormats = oDocument.getNumberFormats()'If you choose to query on types, you need to use the type 'com.sun.star.util.NumberFormat.DATE'I could set the locale from values stored at'http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt'http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html'I use a NULL locale and let it use what ever it likes.'First, see if the number format existsIf ( Not IsMissing(locale)) Then

    aLocale = localeEnd IfformatNum = oFormats.queryKey (sFormat, aLocale, TRUE)MsgBox "Current Format number is" & formatNum'If the number format does not exist then add itIf (formatNum = -1) Then

    formatNum = oFormats.addNew(sFormat, aLocale)If (formatNum = -1) Then formatNum = 0MsgBox "new Format number is " & formatNum

    End IfFindCreateNumberFormatStyle = formatNum

    End Function

    33

  • 4.12 Retorna una matriz FibonnaciEsta funcin retorna una matriz con nmeros Fibonnaci.'******************************************************************

    ' http://disemia.com/software/openoffice/macro_arrays.html' Return the sequence of fibonnaci numbers' assume that count >=2 is to make this code simplerFunction Fibonnaci( Count As Integer )

    Dim result( 1 to Count, 1 ) As Doubleresult( 1, 1 ) = 0result( 2, 1 ) = 1For i = 3 to Count

    result( i, 1 ) = result( i - 2, 1 ) + result( i - 1, 1 )Next i

    Fibonnaci = result()End Function

    4.13 Insertar texto en un marcadoroDoc.getBookmarks().getByName("").getAnchor.setString("What you want to insert")

    4.14 Campos de usuario?? No he hecho nada con esto!Encontr datos de usuario en el documento -- de estos puede obtener algo como esto:

    oDoc = ThisComponentoInfo = oDoc.Document.InfooVal = oData.ElementNames

    iCount = oInfo.GetUserFieldCount()For iCount = 0 to oInfo.GetUserFieldCount() - 1

    sKey = oInfo.GetUserFieldName(iCount)sVal = oInfo.GetUserFieldValue(iCount)msgbox "Name: " & sKey & ", Value: " & sVal

    Next iCountLa respuesta fue:> Conoce alguno como (si es posible) incrementar el nmero de campos de usuario a ms de4?AFAIK no. Qu encontraste sobre campos de usuario de documento de informacin. AFAIKEllos son fijados.

    > Y si esto no es posible Creo que encontr un segundo juego de campos de usuario,> pero no estoy seguro exactamente si estn en el objeto Odoc.Puede obtenerlos con el getTextFields() y getTextFieldMasters()

    34

  • DocInfo = ThisComponent.DocumentInfonCount = DocInfo.getUserFieldCount()for i=0 to nCount-1 DocInfo.setUserFieldName(i,name) DocInfo.setUserFieldValue(index,value)next i

    donde [name], [value] son cadenas que usted elije.

    Tambin puede usar getUserFieldName(index) o getUserFieldValue(index) para leer estoscampos.

    35

  • 5 Macros de Calc5.1 Es este un libro de clculo?Un libro de clculo est compuesto de un conjunto de hojas. Antes de poder usar los mtodosespecficos del libro de clculo, debe tener un documento libro de clculo. Puede verificaresto de la siguiente manera:Function IsSpreadhsheetDoc(oDoc) As Boolean

    On Local Error GoTo NODOCUMENTTYPE IsSpreadhsheetDoc =oDoc.SupportsService(_

    "com.sun.star.sheet.SpreadsheetDocument")NODOCUMENTTYPE:If Err 0 Then

    IsSpreadhseetDoc = FalseResume GOONGOON:

    End IfEnd Function

    5.2 Imprimiendo el valor de una Celda, Cadena o Frmula.'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] ExampleGetValue

    Dim oDocument As Object, oSheet As Object, oCell As ObjectoDocument=ThisComponentoSheet=oDocument.Sheets.getByName("Sheet1")oCell=oSheet.getCellByposition(0,0) 'A1print oCell.getValue'print oCell.getString'print oCell.getFormula

    End sub

    5.3 Estableciendo el valor de una Celda, Formato, Cadena oFrmula.'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] ExampleSetValue

    Dim oDocument As Object, oSheet As Object, oCell As ObjectoDocument=ThisComponentoSheet=oDocument.Sheets.getByName("Sheet1")oCell=oSheet.getCellByPosition(0,0) 'A1oCell.setValue(23658)'oCell..NumberFormat=2 '23658.00'oCell.SetString("oops")'oCell.setFormula("=FUNCTION()")'oCell.IsCellBackgroundTransparent = TRUE'oCell.CellBackColor = RGB(255,141,56)

    37

  • End Sub

    5.4 Limpiar una celdaUna lista de cosas que pueden ser limpiadas se encuentra enhttp://api.openoffice.org/5.2/reference/com/sun/star/sheet/CellFlags.html'******************************************************************

    'Author: Andrew Pitonyak'email: [email protected] ClearDefinedRange

    Dim oDocument As Object, oSheet As Object, oSheets As ObjectDim oCellRange As ObjectDim nSheets As Long

    oDocument = ThisComponentoSheets = oDocument.SheetsnSheets = oDocument.Sheets.CountoSheet = oSheets.getByIndex(2) Rem the range is from 0 to n-1oCellRange = oSheet.getCellRangeByName("range_you_set")oCellRange.clearContents(_

    com.sun.star.sheet.CellFlags.VALUE | _com.sun.star.sheet.CellFlags.DATETIME | _com.sun.star.sheet.CellFlags.STRING | _com.sun.star.sheet.CellFlags.ANNOTATION | _com.sun.star.sheet.CellFlags.FORMULA | _com.sun.star.sheet.CellFlags.HARDATTR | _com.sun.star.sheet.CellFlags.STYLES | _com.sun.star.sheet.CellFlags.OBJECTS | _com.sun.star.sheet.CellFlags.EDITATTR)

    End Sub

    5.5 Texto seleccionado, Qu es?Un texto seleccionado en una hoja de clculo puede ser diferentes cosas; algunas las entiendo yotras no.1. Una celda seleccionada. Haga click en una celda y luego presione maysculas y haga click de

    nuevo.2. Texto parcialmente seleccionado en una celda. Haga doble click en una celda y selecciona una

    parte del texto.3. Nada seleccionado. Un click sencillo o tabulador entre celdas.4. Mltiples celdas seleccionadas. Click sencillo y arrastre el cursor.5. Selecciones mltiples no continuas. Seleccione algunas celdas. Presione la tecla control y

    seleccione otras.No s como distinguir los primeros tres casos. Si me puedo imaginar cmo extraer el textoseleccionado del caso 2, entonces resolver el problema.

    Function CalcIsAnythingSelected(oDoc As Object) As BooleanDim oSelections As Object, oSel As Object, oText As Object, oCursor As ObjectIsAnythingSelected = FalseIf IsNull(oDoc) Then Exit Function' The current selection in the current controller.

    38

  • 'If there is no current controller, it returns NULL.oSelections = oDoc.getCurrentSelection()If IsNull(oSelections) Then Exit FunctionIf oSelections.supportsService("com.sun.star.sheet.SheetCell") Then

    Print "One Cell selected = " & oSelections.getImplementationName()MsgBox "getString() = " & oSelections.getString()

    ElseIf oSelections.supportsService("com.sun.star.sheet.SheetCellRange") ThenPrint "One Cell Range selected = " & oSelections.getImplementationName()

    ElseIf oSelections.supportsService("com.sun.star.sheet.SheetCellRanges") ThenPrint "Multiple Cell Ranges selected = " & oSelections.getImplementationName()Print "Count = " & oSelections.getCount()

    ElsePrint "Somethine else selected = " & oSelections.getImplementationName()

    End IfEnd Function

    39

  • 5.6 Direccin imprimible de una Celda.'Given a cell, extract the normal looking address of a cell'First, the name of the containing sheet is extracted.'Second, the column number is obtained and turned into a letter'Lastly, the row is obtained. Rows start at 0 but are displayed as 1Function PrintableAddressOfCell(the_cell As Object) As String

    PrintableAddressOfCell = "Unknown"If Not IsNull(the_cell) Then

    PrintableAddressOfCell = the_cell.getSpreadSheet().getName + ":" + _ColumnNumberToString(the_cell.CellAddress.Column) + (the_cell.CellAddress.Row+1)

    End IfEnd Function

    ' Columns are numbered starting at 0 where 0 corresponds to A' They run as A-Z,AA-AZ,BA-BZ,...,IV' This is esentially a question of how do you convert a Base 10 number to' a base 26 number. ' Note that the_column is passed by value!Function ColumnNumberToString(ByVal the_column As Long) As String

    Dim s$'Save this so I do NOT modify the parameter.'This was an icky bug that took me a while to findDo

    s$ = Chr(65 + the_column MOD 26) + s$ the_column = the_column / 26

    Loop Until the_column = 0ColumnNumberToString = s$

    End Function

    40

  • 5.7 Insertar fechas formateadas en una CeldaInserte la fecha en la celda actual. Da un mensaje de error si el documento actual no es unahoja de clculo. El cdigo provee la manera de formatear la fecha con el estilo que elija. Lolonecesita pero quitele el comentario.'******************************************************************

    'Author: Andrew Pitonyak'email: [email protected]'uses: FindCreateNumberFormatStyleSub InsertDateIntoCell

    Dim oDesktop As Object, oController As Object, oSelection As ObjectDim doc As ObjectoDesktop = createUnoService("com.sun.star.frame.Desktop")oController = oDesktop.CurrentFrame.Controllerdoc = oController.Model

    If doc.SupportsService("com.sun.star.sheet.SpreadsheetDocument") ThenoSelection = oController.Selection

    ' set the date valueoFunction = CreateUnoService("com.sun.star.sheet.FunctionAccess")oFunction.NullDate = doc.NullDateDim aEmpty()oSelection.Value = oFunction.callFunction("NOW", aEmpty())' Set the date number format to defaultoFormats = doc.NumberFormatsdim aLocale as new com.sun.star.lang.LocaleoSelection.NumberFormat = oFormats.getStandardFormat(_

    com.sun.star.util.NumberFormat.DATETIME, aLocale)' Set the format to something completely different'oSelection.NumberFormat = FindCreateNumberFormatStyle(_' "YYYYMMDD.hhmmss", doc) ElseMsgBox "This macro must be run in a spreadsheet document"

    End IfEnd Sub

    5.8 Desplegar un rango seleccionado en un cuadro de dilogo

    '******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected]'This macro will take the current selection and print a message'box indicating the selected range and the number of selected'cellsSub SelectedCells

    oSelect=ThisComponent.CurrentSelection.getRangeAddress

    41

  • oSelectColumn=ThisComponent.CurrentSelection.ColumnsoSelectRow=ThisComponent.CurrentSelection.Rows

    CountColumn=oSelectColumn.getCountCountRow=oSelectRow.getCount

    oSelectSC=oSelectColumn.getByIndex(0).getNameoSelectEC=oSelectColumn.getByIndex(CountColumn-1).getNameoSelectSR=oSelect.StartRow+1oSelectER=oSelect.EndRow+1NoCell=(CountColumn*CountRow)If CountColumn=1 AND CountRow=1 Then

    MsgBox("Cell " + oSelectSC + oSelectSR + chr(13) + "Cell No = " + NoCell,,"SelectedCells")

    ElseMsgBox("Range(" + oSelectSC + oSelectSR + ":" + oSelectEC + oSelectER + ")" + chr(13) +

    "Cell No = " + NoCell,, "SelectedCells") End If

    End Sub

    5.9 Rellenar un rango seleccionado con textoEsta simple macro cambia a travs del texto seleccionado ponindo el texto en OOPS.'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] FillCells

    oSelect=ThisComponent.CurrentSelectionoColumn=oselect.Columns oRow=oSelect.RowsFor nc= 0 To oColumn.getCount-1

    For nr = 0 To oRow.getCount-1oCell=oselect.getCellByPosition (nc,nr).setString ("OOOPS")

    Next nrNext nc

    End Sub

    42

  • 5.10 Algunos estados del texto seleccionado'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected]'Esta macro toma la seleccin actual e imprime un mensaje'indicando el rango seleccionado y el nmero de celdas 'seleccionadasSub Analize

    sSum="=SUM("+GetAddress+")"sAverage="=AVERAGE("+GetAddress+")"sMin="=MIN("+GetAddress+")"sMax="=MAX("+GetAddress+")"CellPos(7,6).setString(GetAddress)CellPos(7,8).setFormula(sSum)CellPos(7,8).NumberFormat=2CellPos(7,10).setFormula(sAverage)CellPos(7,10).NumberFormat=2CellPos(7,12).setFormula(sMin)CellPos(7,12).NumberFormat=2CellPos(7,14).setFormula(sMax)CellPos(7,14).NumberFormat=2

    End subFunction GetAddress 'selected cell(s)

    oSelect=ThisComponent.CurrentSelection.getRangeAddressoSelectColumn=ThisComponent.CurrentSelection.ColumnsoSelectRow=ThisComponent.CurrentSelection.Rows

    CountColumn=oSelectColumn.getCountCountRow=oSelectRow.getCount

    oSelectSC=oSelectColumn.getByIndex(0).getNameoSelectEC=oSelectColumn.getByIndex(CountColumn-1).getNameoSelectSR=oSelect.StartRow+1oSelectER=oSelect.EndRow+1NoCell=(CountColumn*CountRow)If CountColumn=1 AND CountRow=1 then

    GetAddress=oSelectSC+oSelectSR Else

    GetAddress=oSelectSC+oSelectSR+":"+oSelectEC+oSelectER End If

    End FunctionFunction CellPos(lColumn As Long,lRow As Long)

    CellPos= ActiveSheet.getCellByPosition (lColumn,lRow)End FunctionFunction ActiveSheet ActiveSheet=StarDesktop.CurrentComponent.CurrentController.ActiveSheetEnd FunctionSub DeleteDbRange(sRangeName As String)

    43

  • oRange=ThisComponent.DatabaseRangesoRange.removeByName (sRangeName)

    End Sub

    5.11 Cambiar el rango seleccionado a un rango de Base de Datos'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] DefineDbRange(sRangeName As String) 'selected range

    On Error GoTo DUPLICATENAME oSelect=ThisComponent.CurrentSelection.RangeAddress

    oRange=ThisComponent.DatabaseRanges.addNewByName (sRangeName,oSelect )DUPLICATENAME:

    If Err 0 ThenMsgBox("Duplicate name",,"INFORMATION")

    End If End Sub

    5.12 Borrar un rango de Base de Datos'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] DeleteDbRange(sRangeName As String)

    oRange=ThisComponent.DatabaseRangesoRange.removeByName (sRangeName)

    End Sub

    5.13 Rango bordes de lnea?? Est modificando la estructura temporal aqui. Use algo como esto.'******************************************************************

    'Author: Niklas Nebel'email: [email protected]' setting_borders_in_calcoRange = ThisComponent.Sheets(0).getCellRangeByPosition(0,1,0,63)aBorder = oRange.TableBorder

    aBorder.BottomLine = lHoroRange.TableBorder = aBorderHe goes on to say that the following will not work because it modifies a temporary struct.lHor.Color = 0: lHor.InnerLineWidth = 0: lHor.OuterLineWidth = 150: dim lHor as New com.sun.star.table.BorderLinelHor.LineDistance = 0ThisComponent.Sheets(0).getCellRangeByPosition(0,1,0,63).TableBorder.BottomLine = lHor

    44

  • 5.14 Ordenar un rango'******************************************************************

    'Author: Sasa Kelecevic 'email: [email protected] SortRange

    Dim oSheetDSC,oDSCRange As ObjectDim aSortFields(0) as new com.sun.star.util.SortFieldDim aSortDesc(0) as new com.sun.star.beans.PropertyValue'set your sheet nameoSheetDSC = ThisComponent.Sheets.getByName("Sheet1")'set your range addressoDSCRange = oSheetDSC.getCellRangeByName("A1:L16")ThisComponent.getCurrentController.select(oDSCRange)aSortFields(0).Field = 0aSortFields(0).SortAscending = FALSEaSortDesc(0).Name = "SortFields"aSortDesc(0).Value = aSortFields()oDSCRange.Sort(aSortDesc())

    End sub

    45

  • 5.15 Imprimir todos los datos en una columnaMientras cambiaba la celda y los valores a imprimir, quera imprimir informacin sobre lasceldas. He aqui cmo lo hice.Sub PrintDataInColumn (a_column As Integer)

    Dim oCells As Object, aCell As Object, oDocument As ObjectDim oColumn As Object, oRanges As ObjectoDocument = ThisComponentoColumn = oDocument.Sheets(0).Columns(a_column)Print "Using column " + oColumn.getNameoRanges = oDocument.createInstance("com.sun.star.sheet.SheetCellRanges")oRanges.insertByName("", oColumn)oCells = oRanges.Cells.createEnumerationIf Not oCells.hasMoreElements Then Print "Sorry, no text to display"While oCells.hasMoreElements

    aCell = oCells.nextElement'This next Function is defined elsewhere in this document!MsgBox PrintableAddressOfCell(aCell) + " = " + aCell.String

    WendEnd Sub

    5.16 Usando mtodos de bordes (agrupamiento)Ryan Nelson [[email protected]] me dijo sobre la capacidad de bordes y luego mecont cmo hacer esta macro. Hay dos cosas que debe tener en mente. La primera es que esla hoja que agrega y remueve el arupamiento, y la segunda es que los parmetros deben serlos correctos.http://api.openoffice.org/common/ref/com/sun/star/sheet/XSheetOutline.html http://api.openoffice.org/common/ref/com/sun/star/table/TableOrientation.htmlOption ExplicitSub CalcGroupingExample

    Dim oDoc As Object, oRange As Object, oSheet As ObjectoDoc = ThisComponentIf Not oDoc.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Then

    MsgBox "This macro must be run from a spreadsheet document", 64, "Error"End IfoSheet=oDoc.Sheets.getByName("Sheet1")' Parms are (left, top, right, bottom)oRange = oSheet.getCellRangeByPosition(2,1,3,2)'Could also use COLUMNSoSheet.group(oRange.getRangeAddress(), com.sun.star.table.TableOrientation.ROWS)Print "I just grouped the range"oSheet.unGroup(oRange.getRangeAddress(), com.sun.star.table.TableOrientation.ROWS)Print "I just ungrouped the range"

    End Sub

    46

  • 5.17 Protegiendo sus datosEs fcil proteger sus hojas de clculo, solamente tiene que llamar su hoja y protegerla. Miexperimento indica que sin embargo no genera un error cuando elige proteger un documentoentero, pero no proteger el documento entero.Sub ProtectSpreadsheet

    dim oDoc As Object, oSheet As ObjectoDoc = ThisComponentoSheet=oDoc.Sheets.getByName("Sheet1")oSheet.protect("password")Print "Protect value = " & oSheet.isProtected()oSheet.unprotect("password")Print "Protect value = " & oSheet.isProtected()

    End Sub

    47

  • 6 Macros de Write 6.1 Texto seleccionado, qu es?Texto seleccionado es esencialmente un rango de texto, nada ms. Despus de que laseleccin es obtenida. Es posible obtener el texto [getString()] y cambiar el texto [setString()]. Mientras las cadenas estn limitadas a 64K de tamao, las selecciones no. Hay algunasinstancias, sin embargo, con los resultados de los mtodos getString() y setString() que noentiendo. Sin embargo, es probablemente mejor usar un cursor para cambiar el textoseleccionado y despus usar los mtodos insertString() y insertControlCharacter() del objetode texto. La documentacin especficamente indica que los siguientes caracteres blancosson soportados por el mtodo insertString(): blank, tab, cr (que inserta un cambio de parrfo),y lf (que inserta una nueva lnea).El texto puede ser manualmente seleccionado mientras el cursor esta a la derecha o a laizquierda de la seleccin. Una seleccin tiene un punto de inicio y punto final y no se puedesaber cual esta a la izquierda y cual est a la derecha del texto seleccionado. Un mtodomostrado abajo corrige este problema.Ver tambin:http://api.openoffice.org/common/ref/com/sun/star/text/TextRange.html http://api.openoffice.org/common/ref/com/sun/star/text/XTextRange.html

    6.2 Cursores de texto, qu son?Un cursor de texto es un rango de texto que puede ser movido dentro de un objeto de texto.Los movimientos standars incluyen goLeft, goRight, goUp, y goDown. El primer parametroes un entero indicando cuntos caracteres o lineas se movern. El segundo parmetro es unvalor boleano para indicar si el texto seleccionado se puede expandir (true) o no. El valor deTrue (verdadero) es retornado mientras ocurre el movimiento. Si un cursor ha seleccionadotexto por el movimiento izquierdo y desea moverlo a la derecha, probablemente quiera usaroCursor.goRight(0, False) para indicar al cursor que empiece a moverse a la derecha y noseleccione texto. Esto dejar el texto sin seleccionarse.Un cursor de texto tiene un inicio y un final. Si la posicin inicial es la misma que la posicinfinal entonces no hay texto seleccionado y la propiedad IsCollapsed ser verdadera.Un cursor de texto implementa interfaces que permite movimientos y reconocimiento deposiciones especficas a palabras, oraciones, y prafos. Esto pu