• No se han encontrado resultados

OpenOffice Macros

N/A
N/A
Protected

Academic year: 2021

Share "OpenOffice Macros"

Copied!
168
0
0

Texto completo

(1)

Información importante sobre macros

para OpenOffice

Andrew Pitonyak (Traducción Arturo Garro)

(2)

Gracias

Muchas gracias a mi esposa Michelle por permitirme escribir este libro y por darme coraje. También doy un agradecimiento a aquellos de la comunidad “open-source” y las listas de correos que proveen información de mucha ayuda. Finalmente, un agradecimiento a aquellos que han dado ejemplos incluidos en este documento.

Advertencia

El material en este documento no tiene garantía de aplicación, accuracy, o seguridad. El uso de la información y los macros en este documento es bajo su propio riesgo. Debe asumir que las macros pueden llenar de basura su base de datos, el disco duro, y hacer perder todos sus datos y no me haré responsable.

Licencia

En este momento, debe considerar que todo el material en este documento creado por mi esta sujeto a http://www.openoffice.org/licenses/jca.pdf el cual da a la comunidad OpenOffice community la posibilidad de usarlo en el sitio OpenOffice. Este documento contiene macros que no están escritas por mi. En este momento, he obtenido permiso de incluir estas macros en este documento pero de las que no heobtenido confirmación también tienen esta misma licencia. Tomaré las medidas necesarias para resolver estos problemas en este documento durante las actualizaciones.

Información de contacto

Andrew Pitonyak • 4446 Mobile Drive #105 • Columbus, OH 43220 • USA home: [email protected] • work: [email protected]

home telephone: 614-442-8615

Credenciales

Tengo dos bachilleratos, uno en Informática y otro en Matemáticas. También tengo dos maestrías en Ciencias, uno en Matemática Industrial Aplicada y otro en Informática. He trabajado en Oakland University en Rochester Michigan, The Ohio State University en Columbus Ohio, y en The Technical University Of Dresden en Dresden Germany.

Nota del traductor

Todas las palabras claves de StarBasic dentro del texto han sido puestas en azul para diferenciarlas. Sobra decir que deber ser escritas exactamente igual para evitar errores de sintaxis. Es posible que se me haya quedado alguna palabra en inglés en el texto mientras buscaba su significado.

(3)

Tabla de contenido

1 Introducción...1

2 Recursos disponibles...3

2.1 Material incluido...3

2.2 Recursos en línea (on line)...3

3 Ejemplos...5

3.1 Manipulación de cadenas...5

3.1.1 Remover caracteres de una cadena...5

3.1.2 Reemplazar texto en una cadena...6

3.1.3 Imprimiendo los valores ASCII de una cadena...7

3.2 Depurando e inspeccionando Macros...7

3.2.1 Determinar el tipo de documento...7

3.2.2 Desplegando los métodos y propiedades de un objeto...8

3.2.3 Desplegando las propiedades de un objeto en una hoja de cálculo...9

4 Ejemplos misceláneos...19

4.1 Desplegar texto en la barra de estado...20

4.2 Despliega todos los estilos en el documento actual...21

4.3 Cambiar entre los documentos abiertos...21

4.4 Listar fuentes (Quebrado, no funciona) ...22

4.5 Imprimir el documento actual...23

4.6 Cambiando el tamaño de una lista...25

4.7 Open And Close Documents (And The Desktop)...26

4.7.1 Cerrar documentos OpenOffice...26

4.7.2 Cargar un documento desde una URL...27

4.8 Creando una tabla...29

4.9 Llamando un programa externo...30

4.10 Leer y escribir en un archivo...31

4.11 Creando un estilo de formato numérico...32

4.12 Retorna una matriz Fibonnaci...33

4.13 Insertar texto en un marcador...33

4.14 Campos de usuario...33

5 Macros de Calc...35

5.1 Es este un libro de cálculo?...35

5.2 Imprimiendo el valor de una Celda, Cadena o Fórmula...35

5.3 Estableciendo el valor de una Celda, Formato, Cadena o Fórmula...35

5.4 Limpiar una celda...36

5.5 Texto seleccionado, Qué es?...36

5.6 Dirección imprimible de una Celda...38

5.7 Insertar fechas formateadas en una Celda...39

5.8 Desplegar un rango seleccionado en un cuadro de diálogo...39

5.9 Rellenar un rango seleccionado con texto...40

5.10 Algunos estados del texto seleccionado...41

5.11 Cambiar el rango seleccionado a un rango de Base de Datos...42

5.12 Borrar un rango de Base de Datos...42

(4)

5.14 Ordenar un rango...43

5.15 Imprimir todos los datos en una columna...44

5.16 Usando métodos de bordes (agrupamiento)...44

5.17 Protegiendo sus datos...45

6 Macros de Write ...47

6.1 Texto seleccionado, qué es?...47

6.2 Cursores de texto, qué son?...47

6.3 Andrew's Selected Text Framework...48

6.3.1 Hay texto seleccionado?...48

6.3.2 Cómo obtener una selección...49

6.3.3 Selected Text, Which End Is Which...49

6.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...53

6.3.6 Remover espacios y líneas vacíos, 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 párrafos vacíos, sólo otro ejemplo...55

6.4 Reemplazando espacios seleccionados usando cadenas...56

6.4.1 Comparación de cursores y ejemplos de cadenas...58

6.5 Poniéndo atributos de texto...68

6.6 End Sub Insertar texto...69

6.7 Insertar fecha formateada dentro de un documento de texto...71

6.8 Insertar una nueva página...71

6.8.1 La solución...71

7 Ejemplo de inversión...73

7.1 Página resumen...73

7.2 Hoja de detalles...73

7.3 Chequear duplicados en una columna...74

7.3.1 Dirección imprimible de una celda...74

7.3.2 Conteo de entradas no vacías en una columna...75

7.3.3 Arreglo ordenado...76 7.3.4 Encontrar el duplicado...77 8 Lenguaje...79 8.1 Comentarios...79 8.2 Variables...79 8.2.1 Nombres...79 8.2.2 Declaración...79

8.2.3 Variables globales malas y estáticas...80

(5)

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...84 8.2.6 Areglos o matrices...84 Option Base...84 LBound(NombreMatriz[,Dimensión])...84 UBound(NombreMatriz[,Dimensión])...84 Está esta matriz definida...85

Listas de matrices y ReDim...85

8.2.7 Probando objetos...86

8.2.8 Condicionales...86

8.3 Funciones y SubProcedimientos...87

8.3.1 Parametros opcionales...88

8.3.2 Parámetros por referencia o valor...89

8.3.3 Recursividad...89 8.4 Control de flujo...90 8.4.1 If ... Then ... Else...90 8.4.2 IIF...90 8.4.3 Choose...91 8.4.4 For....Next...91 8.4.5 Do ... Loop...92 8.4.6 Select ... Case...93 8.4.7 Expresiones Case...93 8.4.8 While...Wend...94 8.4.9 GoSub...94 8.4.10 GoTo...95 8.4.11 On GoTo...95 8.4.12 Exit...96 8.4.13 Manejo de errores...97 8.5 Misceláneos...97 9 Operadores y precedencia...101

10 Operadores, Instrucciones y Funciones...103

10.1 Operador - ...103

10.2 Operador * ...103

10.3 Operador + ...103

10.4 Operador ^...104

(6)

10.6 Operador AND...105 10.7 Función Abs...106 10.8 Función Array...106 10.9 Función Asc...107 10.10 Función ATN...108 10.11 Instrucción Beep...108 10.12 Función Blue...108

10.13 Palabra clave ByVal...109

10.14 Palabra clave Call...109

10.15 Función CBool...110 10.16 Función CByte...111 10.17 Función CDate...111 10.18 Función CDateFromIso...112 10.19 Función CDateToIso...112 10.20 Función CDbl...112 10.21 Instrucción ChDir...113 10.22 Instrucción ChDrive...113 10.23 Función Choose...114 10.24 Función Chr...115 10.25 Función CInt...115 10.26 Función CLng...116 10.27 Instrucción Close...116 10.28 Instrucción Const...117 10.29 Función ConvertFromURL...117 10.30 Función ConvertToURL...118 10.31 Función Cos...118 10.32 Función CreateUnoDialog...119 10.33 Función CreateUnoService...120 10.34 Función CreateUnoStruct...120 10.35 Función CSng...121 10.36 Función CStr...121 10.37 Función CurDir...122 10.38 Función Date...122 10.39 Función DateSerial...123 10.40 Función DateValue...124 10.41 Función Day...124 10.42 Instrucción Declare...125 10.43 Instrucción DefBool...125 10.44 Instrucción DefDate...126 10.45 Instrucción DefDbl...126 10.46 Instrucción DefInt...127 10.47 DefLng Statement...127 10.48 Instrucción DefObj...128 iv

(7)

10.49 Instrucción DefVar...128 10.50 Instrucción Dim...128 10.51 Función DimArray...129 10.52 Función Dir...130 10.53 Instrucción Do...Loop...132 10.54 Instrucción End...132 10.55 Función Environ...133 10.56 Función EOF...134 10.57 Función EqualUnoObjects...134 10.58 Operador EQV...135 10.59 Función Erl...136 10.60 Función Err...136 10.61 Función Error...137 10.62 Función Error...138 10.63 Instrucción Exit...138 10.64 Función Exp...139 10.65 Función FileAttr...140 10.66 Instrucción FileCopy...141 10.67 Función FileDateTime...141 10.68 Función FileExists...142 10.69 Función FileLen...142 10.70 Función FindObject...143 10.71 Función FindPropertyObject...143 10.72 Función Fix...144 10.73 For...Next Statement...144 10.74 Función Format...144 10.75 Función FreeFile...147 10.76 FreeLibrary Function...147 10.77 Instrucción Function...148 10.78 Instrucción Get...149 10.79 Función GetAttr...150 10.80 Función GetProcessServiceManager...151 10.81 Función GetSolarVersion...151 10.82 Función GetSystemTicks...152 10.83 Instrucción GlobalScope...152 10.84 Function...153 10.85 Function...153 10.86 Function...153 10.87 Function...154 10.88 Función Green...154

10.89 Palabra clave Private...155

10.90 Palabra clave Public...155

(8)

10.92 Notación y nombres de archivo URL...156

10.92.1 Notación URL...156

10.92.2 Rutas con espacios y otros caracteres especiales...156

11 Index...159

(9)

1Introducción

OpenOffice.org Basic es el nombre del lenguaje de macros incluido con OpenOffice.org. OpenOffice.org Basic tiene mucho en común con Visual Basic de manera que si usted sabe Visual Basic, esto será una gran ventaja.

OpenOffice.org Basic está basada en subrutinas y funciones. Están implementadas con las palabras 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 que “Function” puede retornar un valor y por eso está permitido el uso en la parte derecha de una declaración.

Una colección de procedimientos está contenido en un módulo. Un documento puede contener modulos, y pueden existir globalmente aparte de un documento. Colecciones de módulos están guardados en una librería.

????

En OpenOffice.org Basic, puede accesar el documento o la aplicación a través de las dos variables globales “ThisComponent” y “StarDesktop” respectivamente. Después de tener un documento, puede accesar su interface. Veamos un ejemplo

Dim oText As Object Dim oDoc As Object

oDoc = ThisComponent ' Obtiene el documento activo oText = oDoc.Text ' Obtiene el servicio TextDocument

?? Gracias a Kelvin [email protected] por su aporte en cosas como quitar la palabra clave “ByVal”

(10)
(11)

2Recursos disponibles

2.1Material incluido

No olvide el poder de las páginas de ayuda. Hay mucha información sobre la sintaxis de las macros. Después de abrir las páginas de ayuda, puede accesar el combo en la esquina superior izquierda que dice “Help about OpenOffice.org Basic” Es también instructivo investigar y usar las macros que viene en el OpenOffice. Hay, por ejemplo, macros para las propiedades de impresión y los nombres de objetos. Las he usado para determinar que puedo hacer con un objeto cuando encuentro la documentación confusa.

Abra un documento y seleccione el menú “Herramientas=>Macro”. En la caja de lista, busque un módulo llamado "Tools". Expanda el módulo “Tools”, encontrará otro llamado “Debug”. Estas macros están implementadas para imprimir y mostrar información de depuración, servicios, atributos, etc. Específicamente vea WritedbgInfo(document) o

printdbgInfo(sheet). Son buenos ejemplos.

Para usar la librería de macros “Tools”, deberá primero cargarla. Desde el Basic IDE (Ambiente de Desarrollo Integrado)1 o desde un documento, seleccione

“Herramientas=>Macro”, seleccione la librería “Tools” y presione “F5” o haga click en “Run”.

2.2Recursos en línea (on line)

Hay mucha información disponible en línea, el problema es encontrarla. Mientras usted se siente confortable con este paradigma, las cosas no están lo suficientemente claras. Aquí hay algunos vínculos que he encontrado útiles.

• http://www.openoffice.org es el vínculo principal.

• http://api.openoffice.org contiene información de referencia sobre API2. Mucha información buena, solamente tiene que decifrarla. Cuando esté más a gusto con este paradigma, esto le ayudará grandemente.

• http://api.openoffice.org/basic/man/tutorial/tutorial.pdf Usted deberá tener este documento.

• http://udk.openoffice.org/common/man/tutorial/office_automation.html

• http://api.openoffice.org/common/ref/com/sun/star/module-ix.html información vieja de API que encontré útil.

• http://documentation.openoffice.org el sitio de documentación es muy bueno. Verifique la sección “how to”3. Hay un documento fantástico sobre cómo usar las macros! Está

disponible en

http://documentation.openoffice.org/HOW_TO/various_topics/How_to_use_bas ic_macros.sxw

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

Otros sitios que contienen ejemplos y código generalmente útil son:

1 N.T. Por las siglas de Integrated Development Environment

2 N.T. API son las siglas en inglés Aplication Program Interface, o Interface de programas de aplicación. 3 N.T. “cómo hacerlo”. La página está en inglés y esa expresión en intraducible.

(12)

• http://www.darwinwars.com/lunatic/bugs/oo_macros.html

• http://disemia.com/software/openoffice/

• http://kienlein.com/pages/oo.html

(13)

3 Ejemplos

3.1 Manipulación de cadenas

Basic ofrece algunos métodos para la manipulación de cadenas.

Función Descripción

Asc(s$) Devuelve el valor ASCII (American Standard Code for Information Interchange) del primer caracter de la cadena. Genera un error si la cadena está vacía.

LCase(s$) Devuelve la cadena en minúsculas. La ayuda en línea tiene errores en 1.0.2.

Len(s$) Retorna el tamaño de la cadena s.

Left(s$, n%) Devuelve los primeros n caracteres de s o una cadena vacía si n es cero.

LSet s$ = Text

LTrim(s$) Devuelve una cadena sin los espacios iniciales. Espacios no

significan espacios en blanco, solamente espacios. Esto no modifica la cadena.

Mid(s$, i%[, n%]) Regresa una cadena desde la locación i del tamaño de n. Si n es omitido, retornará todos los caracteres desde i hasta el final de la cadena.

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 serán reemplazados en s.

AddUCase(), RTrim, Trim

En la ayuda en línea, el ejemplo para la conversión de minúsculas/mayúsculas es incorrecto. Aqui está el ejemplo como debería de leerse.

Sub ExampleLUCase Dim sVar As String sVar = "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 cadena

Esto removerá los caracteres de una cadena. Lo disparatado de esta macro es que sería mejor escrita con el método mid(). La diferencia es que el método mid() modifica la cadena actual mientras que esta retorna una nueva cadena. Yo pude hacerla usando el método mid(), pero me di cuenta de esto hasta que fue demasiado tarde.

(14)

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

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

ElseIf index <= 1 Then 'Removing from the start If num >= Len(s) Then

RemoveFromString = "" Else

RemoveFromString = Right(s, Len(s) - num) End If

Else

'Removing from the middle If index + num > Len(s) Then

RemoveFromString = Left(s,index - 1) Else

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

End If End Function

3.1.2 Reemplazar texto en una cadena

Esto puede ser usado para borrar areas de una cadena especificando que la cadena de

reemplazo es una cadena vacía. Inicialmente pensé que podía usar el método mid() para esto también, pero este método no puede hacer que la cadena sea más grande de lo que

actualmente es. Por esto tuve que escribir esta macro. No modifica la cadena actual, pero en su lugar crea una nueva cadena con los reemplazos hechos.

Rem s$ es la cadena a ser modificada

Rem index es un "long" indicando dónde será hecho el reemplazo. (base 1) Rem Si index es <= 1 entonces el texto es insertado al inicio de la cadena. Rem Si index > Len(s) entonces el texto será insertado al final.

Rem num es un "long" indicando cuántos 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 <= 1 Then

'Pone esto al inicio de la cadena If num < 1 Then

ReplaceInString = replaces + s ElseIf num > Len(s) Then

ReplaceInString = replaces Else

ReplaceInString = replaces + Right(s, Len(s) - num) End If

ElseIf index + num > Len(s) Then

ReplaceInString = Left(s,index - 1) + replaces Else

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

(15)

End Function

3.1.3 Imprimiendo los valores ASCII de una cadena

Esto se ve como una macro rara, pero yo la uso para decidir como será guardado el texto en el documento. Esto imprime una cadena completa como una serie de número s ASCII.

Sub PrintAll

PrintAscii(ThisComponent.text.getString()) End Sub

Sub PrintAscii(TheText As String) If Len(TheText) < 1 Then Exit Sub Dim msg$, i% msg = "" For i = 1 To Len(TheText) msg = msg + Asc(Mid(TheText,i,1)) + " " Next i Print msg End Sub

3.2 Depurando e inspeccionando Macros

Frecuentemente es dificil determinar qué métodos y propiedades están disponibles en un objeto. Los métodos en esta sección pueden ser de ayuda.

3.2.1 Determinar el tipo de documento

Esta macro viene con OpenOffice y está incluida aquí como una demostración sobre cómo determinar el tipo de documento.

'****************************************************************** 'Autor: Incluida con OpenOffice

'

Function GetDocumentType(oDoc)

On Local Error GoTo NODOCUMENTTYPE

If 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 If NODOCUMENTTYPE: If Err <> 0 Then GetDocumentType = "" Resume GOON GOON: End If End Function

(16)

3.2.2 Desplegando los métodos y propiedades de un objeto

Esta es una excelente subrutina. El primer parametro es el objeto en cuestión. El segundo parametro puede ser “” para desplegar los métodos y cualquier otra cadena para desplegar las propiedades del objeto. La lista de propiedades o métodos es frecuentemente tan larga que excede el tamaño de la pantalla. Esta subrutina evita esto al partir la lista en piezas pequeñas.

'****************************************************************** 'A subroutine to display all the methods or properties of an input 'Author: Tony Bloomfield

'email: [email protected]

Sub DisplayMethods(oObj As Object, SWhat As String) DIM sMethodList As String, sMsgBox As String DIM fs, ep As Integer

DIM i As Integer DIM EOL As Boolean

if sWhat = "" then sMethodList = oObj.DBG_methods else sMethodList = oObj.DBG_Properties endif fs = 1 EOL = FALSE While fs <= Len(sMethodList) sMsgBox = "" For i = 0 to 15 ep = InStr(fs, sMethodList, ";") if ep = 0 then ep = Len(sMethodList) endif

sMsgBox = sMsgBox & Mid$(sMethodList, fs, ep - fs) & Chr$(13) fs = ep + 1 Next i MsgBox sMsgBox Wend End Sub 8

(17)

3.2.3 Desplegando las propiedades de un objeto en una hoja de

cálculo.

Esta macro debe ser ejecutada para creer. Herr Hermann Kienlein hizo un impresionante trabajo con esto. Esta macro crea una nueva hoja de cálculo y la rellena con información sobre los objetos. Yo modifiqué extensivamente esta macro porque usaba variables globales. Las variables globales interferían con mis propias variables locales. Esto me ayudaba a usarla en mi propio código existente.

'****************************************************************** 'Author: Hermann Kienlein

'email: [email protected]

'online: http://www.kienlein.com/pages/oo.html Option Explicit ' Fuerza a declarar las variables Sub Main

MainObjectDisplay(ThisComponent) End Sub

'

---'Crea un nuevo documento y luego crea nuevas hojas en el documento. ' Da nombres a las hojas e inserta información en las mismas.

Sub MainObjectDisplay(oObject As Object)

Dim oInfo As Object, oDeskNeu As Object, oNewDoc As Object Dim sNewUrl As String, nSheetsUsed As Long

Dim sInterfaces As String

nSheetsUsed = 0

oDeskNeu = createUnoService("com.sun.star.frame.Desktop") 'sNewUrl = "staroffice.factory:scalc" ' This did not work

sNewUrl = "private:factory/scalc"

oNewDoc = oDeskNeu.loadComponentFromURL( sNewUrl,"_blank",0,NoArgs())

ObjInfo(oNewDoc, nSheetsUsed, "ThisComponent", oObject)

On Local Error GoTo AllDone

sInterfaces = oObject.dbg_supportedinterfaces

On Local Error GoTo NoController

If InStr(sInterfaces, "com.sun.star.frame.XModel") <> 0 Then oInfo = oObject.getCurrentController()

ObjInfo(oNewDoc, nSheetsUsed, "getCurrentController", oInfo) End If

NoController:

On Local Error GoTo NoDocInfo '??

' If InStr(sInterfaces, "com.sun.star.document.XDocumentInfoSupplier") <> 0 Then oInfo = oObject.getDocumentInfo()

(18)

' End If NoDocInfo:

On Local Error GoTo NoSelection '??

' If InStr(sInterfaces, "com.sun.star.frame.XSelectionSupplier") <> 0 Then oInfo = oObject.getCurrentSelection()

ObjInfo(oNewDoc, nSheetsUsed, "getCurrentSelection", oInfo) ' End If

NoSelection:

On Local Error GoTo NoLibraryContainer

If InStr(sInterfaces, "com.sun.star.script.XStarBasicAccess") <> 0 Then oInfo = oObject.getLibraryContainer()

ObjInfo(oNewDoc, nSheetsUsed, "getLibraryContainer", oInfo) End If

NoLibraryContainer:

On Local Error GoTo NoViewData

If InStr(sInterfaces, "com.sun.star.document.XViewDataSupplier") <> 0 Then oInfo = oObject.getViewData()

ObjInfo(oNewDoc, nSheetsUsed, "getViewData", oInfo) End If

NoViewData:

On Local Error GoTo NoEvents

If InStr(sInterfaces, "com.sun.star.document.XEventsSupplier") <> 0 Then oInfo = oObject.getEvents()

ObjInfo(oNewDoc, nSheetsUsed, "getEvents", oInfo) End If

NoEvents: AllDone:

On Local Error GoTo 0 End Sub

'

---Sub ObjInfo(oDoc As Object, nSheetsUsed&, sSheetName$, obj As Object) Dim i2 As Integer, bProp As Boolean

Dim nRow&, nCol&, oSheet As Object nRow = 0

ncol = 0

'on error goto err_ObjInfo

If 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)

(19)

i2 = InStr(obj.dbg_methods,"getPropertySetInfo") If i2 > 0 Then bProp = true Else bProp = false End If

ListItems (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 If

If bProp Then

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

End If

MoveRow(nCol, nRow, 1)

ListItems (nCol, nRow, obj.dbg_supportedinterfaces, chr$(10), obj, false, oSheet) 'CleanDbg 'noch keine Ahnung, für was das gut ist

'NextSheet() End If exit_ObjInfo: Exit Sub err_ObjInfo: 'print err If err=423 Then

obName = inputbox("Das Objekt hat keine name-Eigenschaft."_ +" Welchen Namen soll das neue Tabellenblatt haben?") Resume Next Else msgbox error$, 16 Resume exit_ObjInfo End If End 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 Object

Dim frag As String, sleft As String, sPrf As String Dim act As Integer, ex As Integer, nextpos As Integer Dim nextchr As Integer, lstr As Integer, lfrag As Integer Dim ch As Integer

lstr = Len(itemstring) act =1

'Everything left of the first colon

SetCell(nCol, nRow, oSheet, Left(itemstring,InStr(1,itemstring, ":")), 0, 0) 'If there is no colon, then we are done here

(20)

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

End If

act= act+InStr(1,itemstring,":") 'also jetzt auf dem ersten : 'act = act+1 'ein Zeichen weiter positionieren

MoveRow(nCol, nRow, 1) While act<lstr

nextpos=InStr(act,itemstring,sep) 'Position des ersten ; nach : frag = Mid(itemstring,act,nextpos-act)

lfrag = Len(frag) act=act+lfrag+1

frag = LTrim(frag) 'linksbündig ausrichten If frag > "" Then

Do

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

Mid(frag,1,1," ")

frag = LTrim(frag) 'linksbündig ausrichten Else exit Do End If Loop End If MoveRow(nCol, nRow, 1)

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

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

Wend

itemstring = "" End Sub

'

---' Sub um Properties auszulesen, Object muß allerdins ' .PropertySetInfo.Methode

' unterstützen

Sub GetProps(nCol&, nRow&, obj, oSheet As Object) Dim vVariant as Variant

dim nVar As Integer dim mProperties as variant dim mProps1 as variant dim sItemDescription dim nCount As Integer

dim iP As Integer, iP1 As Integer dim n$ dim p dim tmp$ dim j% dim vItem dim sString 12

(21)

MoveRow(nCol, nRow, 2)

mProperties = obj.PropertySetInfo.Properties

nCount = UBound(mProperties)-LBound(mProperties) + 2 SetCell(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.name

vVariant = obj.getPropertyValue(n$) SetCell(nCol, nRow, oSheet, n$, 1, 0) nVar = VarType(vVariant)

Select Case nVar Case 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 If

if not isNull (vVariant.dbg_supportedinterfaces) then

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

MoveRow(nCol, nRow, 2) End If

If Not isNull (vVariant.dbg_methods) Then

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

MoveRow(nCol, nRow, 2) End If

Case Else

If IsArray(vVariant) Then tmp$ = ""

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) Then

sItemDescription = CStr(vItem.dbg_properties) End If Else sItemDescription = cstr(vItem) End If tmp$ = tmp$ & sItemDescription Next j%

ListItems(nCol, nRow, tmp$,";",vVariant,false, oSheet) Else

SetCell(nCol, nRow, oSheet, cstr(vVariant), 0, 1) End If

(22)

MoveRow(nCol, nRow, 1) MoveCol(nCol, nRow, -1) Next iP

End Sub

' ---' GetValue - Inhalte auslesen

'

---Sub GtVal (nCol&, nRow&, sGVal As String, oBje As Object, oSheet As Object) dim is1 As Integer, iAr As Integer

dim s1 As String, s2 As String, s3 As String dim aR1(10) as variant

dim o1 As Object

is1 =InStr(sGVal," ") 'erstes Space suchen s1 = 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 s1 Case "SbxSTRING" Select Case s2 Case "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 = s2 End Select 's3 = oBje.&s2 'msgbox(CStr(oBje)&s2) MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) Case "SbxBOOL" Select Case s2 Case "hasControllersLocked" s3= CStr(oBje.hasControllersLocked()) Case "isModified" s3= CStr(oBje.isModified()) Case "AutoloadEnabled" 14

(23)

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 Select MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) Case "SbxINTEGER" Select Case s2 Case "getUserFieldCount" s3 = CStr(oBje.getUserFieldCount()) Case "EditingCycles" s3 = CStr(oBje.EditingCycles()) Case Else s3 = "" End Select MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) Case "SbxLONG" Select Case s2 Case "getCount" s3 = CStr(oBje.getCount()) Case Else s3 = "" End Select MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) Case "SbxOBJECT"

Select Case s2

Case "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 Else End Select Case "SbxARRAY" Select Case s2 Case "getImplementationId" aR1() = oBje.getImplementationId() MoveCol(nCol, nRow, 4)

(24)

UBound(oBje.getImplementationID()) s3 = CStr(aR1(iAr))

SetCell(nCol, nRow, oSheet, s3, 1, 0) next iAr

MoveCol(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 = s3 MoveCol(nCol, nRow, 1) Next iAr

MoveCol(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 iAr

MoveCol(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 iAr

MoveCol(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 iAr MoveCol(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())

(25)

o1 = aR1(iAr)

s3 = CStr(VarType(aR1(iAr))) '?? We never print this MoveCol(nCol, nRow, 1) Next iAr

MoveCol(nCol, nRow, -(4+1+UBound(oBje.getPrinter()))) Case Else

s3 = " "

MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) End Select

Case Else s3 = " "

MoveCol(nCol, nRow, 4)

SetCell(nCol, nRow, oSheet, s3, -4, 0) End Select

end 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 + i If nCol < 0 Then nRow = nRow + 1 nCol = 0 End If End Sub ' ---Sub MoveRow(nCol&, nRow&, i%)

nRow = nRow + i If nRow < 0 Then nRow = 0 End 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 Object

oSheets = oDoc.Sheets

If isNumeric(nWhichSheet) Then

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

(26)

If nSheetsUsed > oSheets.Count() - 1 Then nSheetsUsed = oSheets.Count() - 1 oSheets.insertNewByName("Sheet"&CStr(oSheets.Count()+1), _ nSheetsUsed) End If oSheet = oSheets.getByIndex(nSheetsUsed) nSheetsUsed = nSheetsUsed + 1 End If oSheet.Name = sSheetName End Sub 18

(27)
(28)

4.1 Desplegar texto en la barra de estado

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

'Hay dos métodos que se pueden usar para obtener 'el indcador de estado

Function ProgressBar

ProgressBar = ThisComponent.CurrentController.StatusIndicator 'o también

'ProgressBar = StarDesktop.getCurrentComponent.StatusIndicator End Function

REM Despliega texto en la barra de estado Sub StatusText(sInformation)

Dim sSpaces As String Dim iLen,iRest As Integer 'sSpaces=SPACE(270) iLen=Len(sInformation) iRest=270-iLen ProgressBar.start(sInformation+SPACE(iRest),0) End Sub 20

(29)

4.2 Despliega todos los estilos en el documento actual

Esto 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] Sub DisplayAllStyles

Dim mFamilyNames As Variant Dim mStyleNames As Variant Dim sMsg As String

Dim oFamilies As Object Dim oStyle As Object Dim oStyles As Object

oFamilies = ThisComponent.StyleFamilies mFamilyNames = 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 If Next i MsgBox sMsg,0,mFamilyNames(n) Next n End Sub

4.3 Cambiar entre los documentos abiertos

Sub Main

Dim oDesktop As Object, oDocs As Object Dim 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

(30)

Sub ListFonts

Dim document As Object Dim Cursor

Dim oText As Object Dim mySelection As Object Dim displayString As String

document=ThisComponent displayString = ""

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

(31)

4.5 Imprimir el documento actual

La ejecuto y puedo imprimir. Me detuve cuando traté de ver como imprimir un documento A4 en mi impresora Letter! Deseo hacerlo por defecto, pero decidí que eso no merece mi tiempo por ahora.

'****************************************************************** 'Author: Andrew Pitonyak

'email: [email protected] Sub 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.PropertyValue

Dim oDocument As Object, oPrinter As Object

oDocument = 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 n

MsgBox 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

(32)

Algo como esto imprime la página actual!

dim aPrintOps(0) as new com.sun.star.beans.PropertyValue oDoc = ThisComponent oViewCursor = oDoc.CurrentController.getViewCursor() aPrintOps(0).Name = "Pages" aPrintOps(0).Value = trim(str(oViewCursor.getPage())) oDoc.print(aPrintOps()) 24

(33)

4.6 Cambiando el tamaño de una lista

Comentario desde el sitio Web.

Para mi, esta macro no lo es.

'****************************************************************** 'Author: Unknown 'email: http://ui.openoffice.org/howto/index.html Option Explicit Sub SetPickListTen ChangePickListSize( 10 ) End Sub

Sub ChangePickListSize( nSize As Integer ) ' access the global configuration provider Dim aConfigProvider As Object

aConfigProvider = createUnoService( "com.sun.star.configuration.ConfigurationProvider" )

' create an access object for the history node Dim aHistorySettings As Object

Dim aParams(0) As new com.sun.star.beans.PropertyValue aParams(0).Name = "nodepath"

aParams(0).Value = "/org.openoffice.Office.Common/History" aHistorySettings = aConfigProvider.createInstanceWithArguments ( "com.sun.star.configuration.ConfigurationUpdateAccess", aParams() )

' set the pick list size

aHistorySettings.replaceByName( "PickListSize", nSize )

' commit the changes done aHistorySettings.commitChanges End Sub

Si desea hacerlo manualmente, aqui está la forma “dificil” de hacerlo

1. 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 archivos XML bien. No use el Block de Notas (Notepad de windows); este obtiene cientos de cuadritos curiosos y mientras se intenta tecnicamente de estar OK, es rrrrrrealmente dificil de leer archivos XML en él.

3. Abra el siguiente archivo, para StarOffice o OpenOffice, cualquiera que esté usando: Bueno, use la macro. Mientras este error no sea corregido, necesitará “terminar la tarea” después de aplicar la macro, como un apagado corriente, los valores escritos por la macro serán sobreescritos.

Hay algunas otras maneras para lograr lo mismo, pero involucra meterse con archivos locales que son una implementación detallada de la configuración del “backend”, que no voy a mencionar aqui :).

(34)

~/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 <History>; las entradas son alfabéticas. Verá algo como lo siguiente: <History>

<List cfg:element-type="HistoryType">

<HistoryType state="replaced" cfg:name="h0">

<Filter cfg:type="string">StarOffice XML (Writer)</Filter> <Password cfg:type="string"/>

4. <Title cfg:type="string">file:///C:/docs/newdocs/story.sxw</Title> <URL cfg:type="string">file:///C:/docs/newdocs/story.sxw</URL> </HistoryType>

[y luego, un poco más entradas <HistoryType>...] </List>

<PickList cfg:element-type="HistoryType"> <HistoryType state="replaced" cfg:name="h0">

<Filter cfg:type="string">StarOffice XML (Writer)</Filter> <Password cfg:type="string"/>

<Title cfg:type="string">file:///C:/docs/newdocs/story.sxw</Title> <URL cfg:type="string">file:///C:/docs/newdocs/story.sxw</URL> </HistoryType>

[y luego, con tres entradas <HistoryType> más; esta es la lista de archivos recientes desplegada bajo el menú archivo...]

</PickList> </History>

5. Reemplace en contenido entero de la etiqueta <History>, es decir desde <History> a </History> inclusive, con el siguiente texto. El ejemplo cambia StarOffice para desplegar los 9 archivos más recientes; digite el número que desee. Imagino que no es buena idea hacerlo muy grande, pero no conozco si existe un límite de archivos, si hay alguno. <History>

<PickListSize cfg:type="int">9</PickListSize> </History>

4.7 Open And Close Documents (And The Desktop)

4.7.1 Cerrar documentos OpenOffice

Todos los documentos OpenOffice y los objetos en marcos (servicios) soportan la interface Xcerrable. Para cerrar estos objetos deberá llamar close(bForce As Boolean). Si bForce es falso, entonces el objeto puede rehusar a cerrarse. Si bForce es verdadero, entonces el objeto no puede rehusarse a cerrarse.

El escritorio no soporta la interface Xcerrable por razones de herencia. El método terminate() es usado para esto. Este método causa un evento-terminación que será transmitido a todos los que escuchen. Si no se devuelve TerminationVetoException, una notificación de

(35)

terminación es transmitido y se devuelve un valor verdadero. De lo contrario, se transmite un aborte-evento-terminación y se devuelve un valor falso. Para citar a Mathias Bauer, “el método terminate() estuvo ahi por mucho tiempo, mucho antes que descubrimos que no es la manera correcta de manejar el cierre de documentos o ventanas. Si este no hubiera estado ahí, podríamos haber usado Xcerrable para el escritorio también.”[Bauer001]

If HasUnoInterfaces(oDoc, "com.sun.star.util.XCloseable") Then oDoc.close(true)

Else

oDoc.dispose End If

Obtuve los siguientes metodos de Sasa Kelecevic [[email protected]] que no he probado??

'--- salvar_y_cerrar ---'Use uno de estos métodos

'oDocClose=StarDesktop.CurrentFrame.Close 'oDocClose=StarDesktop.ActiveFrame.Close '--- cerrar_no_salvar ---'Use uno de estos métodos

'oDocClose=ThisComponent.Dispose

'oDocClose=StarDesktop.ActiveFrame.Dispose

4.7.2 Cargar un documento desde una URL

Para cargar un documento desde una URL, use el método LoadComponentFromURL() del escritorio. 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::XComponent Parámetros:

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 la ruta actual en el árbol.

nSearchFlags: Usa los valores de FrameSearchFlag para especificar cómo encontrar el nombre del marco destino (aTargetFrameName). Normalmente, simplemente use 0.

(36)

# Nombre Descripción

0 Auto SELF+CHILDREN 1 PARENT Incluye el marco padre 2 SELF Incluye el marco inicial

4 CHILDREN Incluye los marcos hijos del marco inicial 8 CREATE Será creado un marco, si no existe

16 SIBLINGS Incluye otros marcos hijos del marco inicial

32 TASKS Incluye todos los marcos en todas las tareas de la actual jerarquía de marcos.

23 ALL

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

55 GLOBAL

Busca en toda la jerarquía de marcos. 55 = 1+2+4+16+32 = PARENT + SELF + CHILDREN + SIBLINGS + TASKS.

63 GLOBAL + CREATE

aArgs: Especifica el comportamiento especifico del componente o filtro. "ReadOnly" con un valor boleano especifica que el documento está abierto en modo sólo lectura.

"FilterName" especifica el tipo de componente para crear y el tipo de filtro a usar, por ejemplo: "scalc: Text - csv". Ver

http://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 puede usar:

oDoc = oDesk.LoadComponentFromUrl(sUrl_1, "_blank", 0, Noargs()) oFrame = oDoc.CurrentController.Frame

oDoc = 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)

(37)

Dim oCur As Object Dim oProperties As Object

oCur=oText.createTextCursorByRange(oDoc.getCurrentController().getViewCursor().getStart()) oCur.insertDocumentFromURL(sFileURL,oProperties) End Sub Ejemplo: '--- 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 tabla

No 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 cursor sName = oCursor.getRangeName()

' The cell name will be something like D3 oCelle = oTable.getCellByName(sName) oCelle.String = what

oCursor.goRight(1,FALSE) End Sub

Function CreateTable() As Object

oDocument = StarDesktop.ActiveComponent

oTextTable = oDocument.createInstance("com.sun.star.text.TextTable") CreateTable = oTextTable

(38)

4.9 Llamando un programa externo

Este ejemplo de llamada de un programa externo y salvar la salida fue muy lento por el creador 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 mejor manera de hacerlo.Cómo puedo canalizar una cadena por medio de un programa externo? Algún ejemplo? ?? Pruebe esto!

'****************************************************************** 'Author: Pavel Janík

'email: [email protected]

Sub CallExternalProgram () Dim Document As Object Document = ThisComponent

' Andrew says that this looks like an extra text para = Document.text.Text.getText()

shell ("/home/pavel/my_filter", 2, "'" & para.getString() & "'", True) wait (9000) para.setString(ReturnContentsOfFile("/tmp/output.txt"))

End Sub

(39)

4.10 Leer y escribir en un archivo

Este ejemplo lee un número desde un archivo de texto. Este valor es convertido en número e incrementado. El número es escrito de nuevo en el archivo como una cadena.

'****************************************************************** 'Author: Andrew Pitonyak

'email: [email protected] Sub Read_Write_Number_In_File

DIM CountFileName As String, NumberString As String DIM LongNumber As Long, iNum As Integer

Dim oDocument As Object

CountFileName = "C:\Andy\My Documents\oo\NUMBER.TXT" NumberString = "00000000"

LongNumber = 0

'On Local Error Goto NoFile If FileExists(CountFileName) Then

ON ERROR GOTO NoFile iNum = FreeFile

OPEN CountFileName for input as #iNum LINE INPUT #iNum ,NumberString

CLOSE #iNum

MsgBox("Read " & NumberString, 64, "Read") NoFile:

If Err <> 0 Then

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

End If

On Local Error Goto 0 Else

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

End If

ON ERROR GOTO BadNumber LongNumber = Int(NumberString) LongNumber = LongNumber + 1 BadNumber:

If Err <> 0 Then

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

End If

On Local Error Goto 0

NumberString=Trim(Str(LongNumber)) While LEN(NumberString) < 8

NumberString="0"&NumberString Wend

MsgBox("Number is (" & NumberString & ")", 64, "Information") iNum = FreeFile

OPEN CountFileName for output as #iNum PRINT #iNum,NumberString

(40)

CLOSE #iNum End Sub

(41)

4.11 Creando un estilo de formato numérico

Si desea un formato particular de número, entonces puede observar si existe y crearlo si no lo tiene. Para más información sobre fomatos validos, vea los contenidos de la ayuda en los tópicos “number formats; formats”. Estos pueden ser bastante complejos.

'****************************************************************** 'Author: Andrew Pitonyak

'email: [email protected]

Function FindCreateNumberFormatStyle (_

sFormat As String, Optional doc, Optional locale) Dim oDocument As Object

Dim aLocale as new com.sun.star.lang.Locale Dim oFormats As Object

oDocument = 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 exists

If ( Not IsMissing(locale)) Then aLocale = locale

End If

formatNum = oFormats.queryKey (sFormat, aLocale, TRUE) MsgBox "Current Format number is" & formatNum

'If the number format does not exist then add it If (formatNum = -1) Then

formatNum = oFormats.addNew(sFormat, aLocale) If (formatNum = -1) Then formatNum = 0

MsgBox "new Format number is " & formatNum End If

FindCreateNumberFormatStyle = formatNum End Function

(42)

4.12 Retorna una matriz Fibonnaci

Esta función retorna una matriz con números Fibonnaci.

'****************************************************************** ' http://disemia.com/software/openoffice/macro_arrays.html ' Return the sequence of fibonnaci numbers

' assume that count >=2 is to make this code simpler Function Fibonnaci( Count As Integer )

Dim result( 1 to Count, 1 ) As Double result( 1, 1 ) = 0

result( 2, 1 ) = 1

For 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 marcador

oDoc.getBookmarks().getByName("<yourBookmarkName>").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 = ThisComponent oInfo = oDoc.Document.Info oVal = 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 iCount

La respuesta fue:

> Conoce alguno como (si es posible) incrementar el número de campos de usuario a más de 4?

AFAIK no. Qué encontraste sobre campos de usuario de documento de información. AFAIK Ellos son fijados.

> Y si esto no es posible – Creo que encontré un segundo juego de campos de usuario, > pero no estoy seguro exactamente si están en el objeto Odoc.

Puede obtenerlos con el getTextFields() y getTextFieldMasters()

(43)

DocInfo = ThisComponent.DocumentInfo

nCount = 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.

También puede usar getUserFieldName(index) o getUserFieldValue(index) para leer estos campos.

(44)
(45)

5 Macros de Calc

5.1 Es este un libro de cálculo?

Un libro de cálculo está compuesto de un conjunto de hojas. Antes de poder usar los métodos específicos del libro de cálculo, debe tener un documento libro de cálculo. Puede verificar esto 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 = False Resume GOON GOON: End If End Function

5.2 Imprimiendo el valor de una Celda, Cadena o Fórmula.

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

Sub ExampleGetValue

Dim oDocument As Object, oSheet As Object, oCell As Object oDocument=ThisComponent oSheet=oDocument.Sheets.getByName("Sheet1") oCell=oSheet.getCellByposition(0,0) 'A1 print oCell.getValue 'print oCell.getString 'print oCell.getFormula End sub

5.3 Estableciendo el valor de una Celda, Formato, Cadena o

Fórmula.

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

Sub ExampleSetValue

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

(46)

End Sub

5.4 Limpiar una celda

Una lista de cosas que pueden ser limpiadas se encuentra en

http://api.openoffice.org/5.2/reference/com/sun/star/sheet/CellFlags.html '******************************************************************

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

Dim oDocument As Object, oSheet As Object, oSheets As Object Dim oCellRange As Object

Dim nSheets As Long

oDocument = ThisComponent oSheets = oDocument.Sheets nSheets = oDocument.Sheets.Count

oSheet = oSheets.getByIndex(2) Rem the range is from 0 to n-1 oCellRange = 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 cálculo puede ser diferentes cosas; algunas las entiendo y otras no.

1. Una celda seleccionada. Haga click en una celda y luego presione mayúsculas 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. Múltiples celdas seleccionadas. Click sencillo y arrastre el cursor.

5. Selecciones múltiples no continuas. Seleccione algunas celdas. Presione la tecla control y seleccione otras.

No sé como distinguir los primeros tres casos. Si me puedo imaginar cómo extraer el texto seleccionado del caso 2, entonces resolveré el problema.

Function CalcIsAnythingSelected(oDoc As Object) As Boolean

Dim oSelections As Object, oSel As Object, oText As Object, oCursor As Object IsAnythingSelected = False

If IsNull(oDoc) Then Exit Function

' The current selection in the current controller.

(47)

'If there is no current controller, it returns NULL. oSelections = oDoc.getCurrentSelection() If IsNull(oSelections) Then Exit Function

If 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") Then Print "One Cell Range selected = " & oSelections.getImplementationName() ElseIf oSelections.supportsService("com.sun.star.sheet.SheetCellRanges") Then

Print "Multiple Cell Ranges selected = " & oSelections.getImplementationName() Print "Count = " & oSelections.getCount()

Else

Print "Somethine else selected = " & oSelections.getImplementationName() End If

(48)

5.6 Dirección 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 1 Function 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 If

End 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 find Do

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

Loop Until the_column = 0 ColumnNumberToString = s$ End Function

(49)

5.7 Insertar fechas formateadas en una Celda

Inserte la fecha en la celda actual. Da un mensaje de error si el documento actual no es una hoja de cálculo. El código provee la manera de formatear la fecha con el estilo que elija. Lolo necesita pero quitele el comentario.

'****************************************************************** 'Author: Andrew Pitonyak

'email: [email protected]

'uses: FindCreateNumberFormatStyle Sub InsertDateIntoCell

Dim oDesktop As Object, oController As Object, oSelection As Object Dim doc As Object

oDesktop = createUnoService("com.sun.star.frame.Desktop") oController = oDesktop.CurrentFrame.Controller

doc = oController.Model

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

' set the date value

oFunction = CreateUnoService("com.sun.star.sheet.FunctionAccess") oFunction.NullDate = doc.NullDate

Dim aEmpty()

oSelection.Value = oFunction.callFunction("NOW", aEmpty())

' Set the date number format to default oFormats = doc.NumberFormats

dim aLocale as new com.sun.star.lang.Locale

oSelection.NumberFormat = oFormats.getStandardFormat(_ com.sun.star.util.NumberFormat.DATETIME, aLocale)

' Set the format to something completely different

'oSelection.NumberFormat = FindCreateNumberFormatStyle(_ ' "YYYYMMDD.hhmmss", doc) Else

MsgBox "This macro must be run in a spreadsheet document" End If

End Sub

5.8 Desplegar un rango seleccionado en un cuadro de diálogo

'****************************************************************** '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 'cells

Sub SelectedCells

(50)

oSelectColumn=ThisComponent.CurrentSelection.Columns oSelectRow=ThisComponent.CurrentSelection.Rows CountColumn=oSelectColumn.getCount CountRow=oSelectRow.getCount oSelectSC=oSelectColumn.getByIndex(0).getName oSelectEC=oSelectColumn.getByIndex(CountColumn-1).getName oSelectSR=oSelect.StartRow+1 oSelectER=oSelect.EndRow+1 NoCell=(CountColumn*CountRow)

If CountColumn=1 AND CountRow=1 Then

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

Else

MsgBox("Range(" + oSelectSC + oSelectSR + ":" + oSelectEC + oSelectER + ")" + chr(13) + "Cell No = " + NoCell,, "SelectedCells")

End If End Sub

5.9 Rellenar un rango seleccionado con texto

Esta simple macro cambia a través del texto seleccionado poniéndo el texto en “OOPS”.

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected] Sub FillCells oSelect=ThisComponent.CurrentSelection oColumn=oselect.Columns oRow=oSelect.Rows For nc= 0 To oColumn.getCount-1 For nr = 0 To oRow.getCount-1

oCell=oselect.getCellByPosition (nc,nr).setString ("OOOPS") Next nr

Next nc End Sub

(51)

5.10 Algunos estados del texto seleccionado

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

'Esta macro toma la selección actual e imprime un mensaje 'indicando el rango seleccionado y el número de celdas 'seleccionadas Sub 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=2 CellPos(7,10).setFormula(sAverage) CellPos(7,10).NumberFormat=2 CellPos(7,12).setFormula(sMin) CellPos(7,12).NumberFormat=2 CellPos(7,14).setFormula(sMax) CellPos(7,14).NumberFormat=2 End sub

Function GetAddress 'selected cell(s)

oSelect=ThisComponent.CurrentSelection.getRangeAddress oSelectColumn=ThisComponent.CurrentSelection.Columns oSelectRow=ThisComponent.CurrentSelection.Rows CountColumn=oSelectColumn.getCount CountRow=oSelectRow.getCount oSelectSC=oSelectColumn.getByIndex(0).getName oSelectEC=oSelectColumn.getByIndex(CountColumn-1).getName oSelectSR=oSelect.StartRow+1 oSelectER=oSelect.EndRow+1 NoCell=(CountColumn*CountRow)

If CountColumn=1 AND CountRow=1 then GetAddress=oSelectSC+oSelectSR Else

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

End Function

Function CellPos(lColumn As Long,lRow As Long)

CellPos= ActiveSheet.getCellByPosition (lColumn,lRow) End Function

Function ActiveSheet

ActiveSheet=StarDesktop.CurrentComponent.CurrentController.ActiveSheet End Function

(52)

oRange=ThisComponent.DatabaseRanges oRange.removeByName (sRangeName) End Sub

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

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

Sub DefineDbRange(sRangeName As String) 'selected range On Error GoTo DUPLICATENAME

oSelect=ThisComponent.CurrentSelection.RangeAddress oRange=ThisComponent.DatabaseRanges.addNewByName (sRangeName,oSelect ) DUPLICATENAME: If Err <> 0 Then MsgBox("Duplicate name",,"INFORMATION") End If End Sub

5.12 Borrar un rango de Base de Datos

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

Sub DeleteDbRange(sRangeName As String) oRange=ThisComponent.DatabaseRanges oRange.removeByName (sRangeName) End Sub

5.13 Rango bordes de línea

?? Está modificando la estructura temporal aqui. Use algo como esto.

'****************************************************************** 'Author: Niklas Nebel

'email: [email protected] ' setting_borders_in_calc oRange = ThisComponent.Sheets(0).getCellRangeByPosition(0,1,0,63) aBorder = oRange.TableBorder aBorder.BottomLine = lHor oRange.TableBorder = aBorder

He 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 = 0

ThisComponent.Sheets(0).getCellRangeByPosition(0,1,0,63).TableBorder.BottomLine = lHor

(53)

5.14 Ordenar un rango

'****************************************************************** 'Author: Sasa Kelecevic

'email: [email protected]

Sub SortRange

Dim oSheetDSC,oDSCRange As Object

Dim aSortFields(0) as new com.sun.star.util.SortField

Dim aSortDesc(0) as new com.sun.star.beans.PropertyValue

'set your sheet name

oSheetDSC = ThisComponent.Sheets.getByName("Sheet1")

'set your range address

oDSCRange = oSheetDSC.getCellRangeByName("A1:L16") ThisComponent.getCurrentController.select(oDSCRange) aSortFields(0).Field = 0 aSortFields(0).SortAscending = FALSE aSortDesc(0).Name = "SortFields" aSortDesc(0).Value = aSortFields() oDSCRange.Sort(aSortDesc()) End sub

Referencias

Documento similar

Entre nosotros anda un escritor de cosas de filología, paisano de Costa, que no deja de tener ingenio y garbo; pero cuyas obras tienen de todo menos de ciencia, y aun

The part I assessment is coordinated involving all MSCs and led by the RMS who prepares a draft assessment report, sends the request for information (RFI) with considerations,

o Si dispone en su establecimiento de alguna silla de ruedas Jazz S50 o 708D cuyo nº de serie figura en el anexo 1 de esta nota informativa, consulte la nota de aviso de la

Zonas de encuesta Zonas

Ciaurriz quien, durante su primer arlo de estancia en Loyola 40 , catalogó sus fondos siguiendo la división previa a la que nos hemos referido; y si esta labor fue de

Gastos derivados de la recaudación de los derechos económicos de la entidad local o de sus organis- mos autónomos cuando aquélla se efectúe por otras enti- dades locales o

1. LAS GARANTÍAS CONSTITUCIONALES.—2. C) La reforma constitucional de 1994. D) Las tres etapas del amparo argentino. F) Las vías previas al amparo. H) La acción es judicial en

Volviendo a la jurisprudencia del Tribunal de Justicia, conviene recor- dar que, con el tiempo, este órgano se vio en la necesidad de determinar si los actos de los Estados