Sei sulla pagina 1di 168

Informacin importante sobre macros para OpenOffice

Andrew Pitonyak (Traduccin Arturo Garro)

Gracias
Muchas 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 de correos que proveen informacin de mucha ayuda. Finalmente, un agradecimiento a aquellos que han dado ejemplos incluidos en este documento.

Advertencia
El material en este documento no tiene garanta de aplicacin, accuracy, o seguridad. El uso de la informacin 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 estn escritas por mi. En este momento, he obtenido permiso de incluir estas macros en este documento pero de las que no heobtenido confirmacin tambin tienen esta misma licencia. Tomar las medidas necesarias para resolver estos problemas en este documento durante las actualizaciones.

Informacin de contacto
Andrew Pitonyak 4446 Mobile Drive #105 Columbus, OH 43220 USA home: andrew@pitonyak.org work: andrew.pitonyak@qwest.com home telephone: 614-442-8615

Credenciales
Tengo dos bachilleratos, uno en Informtica y otro en Matemticas. Tambin tengo dos maestras en Ciencias, uno en Matemtica Industrial Aplicada y otro en Informtica. 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 ingls en el texto mientras buscaba su significado.

Tabla de contenido
1 Introduccin...........................................................................................................................1 2 Recursos disponibles..............................................................................................................3 2.1 Material incluido............................................................................................................3 2.2 Recursos en lnea (on line).............................................................................................3 3 Ejemplos...............................................................................................................................5 3.1 Manipulacin 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 mtodos y propiedades de un objeto..........................................8 3.2.3 Desplegando las propiedades de un objeto en una hoja de clculo.......................9 4 Ejemplos miscelneos.........................................................................................................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 tamao 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 numrico....................................................................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 clculo?.........................................................................................35 5.2 Imprimiendo el valor de una Celda, Cadena o Frmula.............................................35 5.3 Estableciendo el valor de una Celda, Formato, Cadena o Frmula............................35 5.4 Limpiar una celda........................................................................................................36 5.5 Texto seleccionado, Qu es?.......................................................................................36 5.6 Direccin imprimible de una Celda............................................................................38 5.7 Insertar fechas formateadas en una Celda...................................................................39 5.8 Desplegar un rango seleccionado en un cuadro de dilogo........................................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 5.13 Rango bordes de lnea...............................................................................................42 i

5.14 Ordenar un rango.......................................................................................................43 5.15 Imprimir todos los datos en una columna.................................................................44 5.16 Usando mtodos 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 Cmo obtener una seleccin................................................................................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 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.................................................55 6.4 Reemplazando espacios seleccionados usando cadenas.............................................56 6.4.1 Comparacin de cursores y ejemplos de cadenas................................................58 6.5 Ponindo 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 pgina............................................................................................71 6.8.1 La solucin..........................................................................................................71 7 Ejemplo de inversin..........................................................................................................73 7.1 Pgina resumen...........................................................................................................73 7.2 Hoja de detalles...........................................................................................................73 7.3 Chequear duplicados en una columna.........................................................................74 7.3.1 Direccin imprimible de una celda......................................................................74 7.3.2 Conteo de entradas no vacas 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 Declaracin..........................................................................................................79 8.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............................................................................................................84 8.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.................................................................................................86 8.2.8 Condicionales......................................................................................................86 8.3 Funciones y SubProcedimientos.................................................................................87 8.3.1 Parametros opcionales.........................................................................................88 8.3.2 Parmetros 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 Miscelneos.................................................................................................................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 10.5 Operador /................................................................................................................104 iii

10.6 Operador AND........................................................................................................105 10.7 Funcin Abs............................................................................................................106 10.8 Funcin Array.........................................................................................................106 10.9 Funcin Asc............................................................................................................107 10.10 Funcin ATN........................................................................................................108 10.11 Instruccin Beep....................................................................................................108 10.12 Funcin Blue.........................................................................................................108 10.13 Palabra clave ByVal..............................................................................................109 10.14 Palabra clave Call..................................................................................................109 10.15 Funcin CBool......................................................................................................110 10.16 Funcin CByte......................................................................................................111 10.17 Funcin CDate......................................................................................................111 10.18 Funcin CDateFromIso.........................................................................................112 10.19 Funcin CDateToIso.............................................................................................112 10.20 Funcin CDbl........................................................................................................112 10.21 Instruccin ChDir..................................................................................................113 10.22 Instruccin ChDrive..............................................................................................113 10.23 Funcin Choose.....................................................................................................114 10.24 Funcin Chr...........................................................................................................115 10.25 Funcin CInt..........................................................................................................115 10.26 Funcin CLng........................................................................................................116 10.27 Instruccin Close...................................................................................................116 10.28 Instruccin Const..................................................................................................117 10.29 Funcin ConvertFromURL...................................................................................117 10.30 Funcin ConvertToURL.......................................................................................118 10.31 Funcin Cos..........................................................................................................118 10.32 Funcin CreateUnoDialog....................................................................................119 10.33 Funcin CreateUnoService...................................................................................120 10.34 Funcin CreateUnoStruct......................................................................................120 10.35 Funcin CSng........................................................................................................121 10.36 Funcin CStr.........................................................................................................121 10.37 Funcin CurDir.....................................................................................................122 10.38 Funcin Date.........................................................................................................122 10.39 Funcin DateSerial................................................................................................123 10.40 Funcin DateValue................................................................................................124 10.41 Funcin Day..........................................................................................................124 10.42 Instruccin Declare...............................................................................................125 10.43 Instruccin DefBool..............................................................................................125 10.44 Instruccin DefDate..............................................................................................126 10.45 Instruccin DefDbl................................................................................................126 10.46 Instruccin DefInt.................................................................................................127 10.47 DefLng Statement..................................................................................................127 10.48 Instruccin DefObj................................................................................................128 iv

10.49 10.50 10.51 10.52 10.53 10.54 10.55 10.56 10.57 10.58 10.59 10.60 10.61 10.62 10.63 10.64 10.65 10.66 10.67 10.68 10.69 10.70 10.71 10.72 10.73 10.74 10.75 10.76 10.77 10.78 10.79 10.80 10.81 10.82 10.83 10.84 10.85 10.86 10.87 10.88 10.89 10.90 10.91

Instruccin DefVar................................................................................................128 Instruccin Dim.....................................................................................................128 Funcin DimArray................................................................................................129 Funcin Dir...........................................................................................................130 Instruccin Do...Loop...........................................................................................132 Instruccin End.....................................................................................................132 Funcin Environ....................................................................................................133 Funcin EOF.........................................................................................................134 Funcin EqualUnoObjects....................................................................................134 Operador EQV......................................................................................................135 Funcin Erl............................................................................................................136 Funcin Err............................................................................................................136 Funcin Error........................................................................................................137 Funcin Error........................................................................................................138 Instruccin Exit.....................................................................................................138 Funcin Exp..........................................................................................................139 Funcin FileAttr....................................................................................................140 Instruccin FileCopy.............................................................................................141 Funcin FileDateTime..........................................................................................141 Funcin FileExists.................................................................................................142 Funcin FileLen....................................................................................................142 Funcin FindObject...............................................................................................143 Funcin FindPropertyObject.................................................................................143 Funcin Fix...........................................................................................................144 For...Next Statement..............................................................................................144 Funcin Format.....................................................................................................144 Funcin FreeFile...................................................................................................147 FreeLibrary Function.............................................................................................147 Instruccin Function..............................................................................................148 Instruccin Get......................................................................................................149 Funcin GetAttr....................................................................................................150 Funcin GetProcessServiceManager....................................................................151 Funcin GetSolarVersion......................................................................................151 Funcin GetSystemTicks......................................................................................152 Instruccin GlobalScope.......................................................................................152 Function.................................................................................................................153 Function.................................................................................................................153 Function.................................................................................................................153 Function.................................................................................................................154 Funcin Green.......................................................................................................154 Palabra clave Private.............................................................................................155 Palabra clave Public..............................................................................................155 Funcin Red..........................................................................................................156 v

10.92 Notacin y nombres de archivo URL....................................................................156 10.92.1 Notacin URL...............................................................................................156 10.92.2 Rutas con espacios y otros caracteres especiales..........................................156 11 Index................................................................................................................................159

vi

1Introduccin
OpenOffice.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 sabe Visual Basic, esto ser una gran ventaja. OpenOffice.org Basic est basada en subrutinas y funciones. Estn 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 declaracin. Una coleccin de procedimientos est contenido en un mdulo. Un documento puede contener modulos, y pueden existir globalmente aparte de un documento. Colecciones de mdulos estn guardados en una librera. ???? En OpenOffice.org Basic, puede accesar el documento o la aplicacin a travs de las dos variables globales ThisComponent y StarDesktop respectivamente. Despus de tener un documento, puede accesar su interface. Veamos un ejemplo
Dim oText As Object Dim oDoc As Object oDoc = ThisComponent oText = oDoc.Text ' Obtiene el documento activo ' Obtiene el servicio TextDocument

?? Gracias a Kelvin demo@onlineconnections.com.au por su aporte en cosas como quitar la palabra clave ByVal

2Recursos disponibles
2.1Material incluido
No olvide el poder de las pginas de ayuda. Hay mucha informacin sobre la sintaxis de las macros. Despus de abrir las pginas de ayuda, puede accesar el combo en la esquina superior izquierda que dice Help about OpenOffice.org Basic Es tambin instructivo investigar y usar las macros que viene en el OpenOffice. Hay, por ejemplo, macros para las propiedades de impresin y los nombres de objetos. Las he usado para determinar que puedo hacer 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 llamado Debug. Estas macros estn implementadas para imprimir y mostrar informacin de depuracin, servicios, atributos, etc. Especficamente vea WritedbgInfo(document) o printdbgInfo(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, seleccione Herramientas=>Macro, seleccione la librera Tools y presione F5 o haga click en Run.

2.2Recursos en lnea (on line)


Hay mucha informacin disponible en lnea, el problema es encontrarla. Mientras usted se siente confortable con este paradigma, las cosas no estn lo suficientemente claras. Aqu hay algunos 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 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 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! 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 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.

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

3 Ejemplos
3.1 Manipulacin de cadenas
Basic ofrece algunos mtodos para la manipulacin de cadenas. Funcin Asc(s$) Descripcin Devuelve el valor ASCII (American Standard Code for Information Interchange) del primer caracter de la cadena. Genera un error si la cadena est vaca. Devuelve la cadena en minsculas. La ayuda en lnea tiene errores en 1.0.2. Retorna el tamao de la cadena s. Devuelve los primeros n caracteres de s o una cadena vaca si n es cero. Devuelve una cadena sin los espacios iniciales. Espacios no significan espacios en blanco, solamente espacios. Esto no modifica la cadena. Regresa una cadena desde la locacin i del tamao de n. Si n es omitido, retornar todos los caracteres desde i hasta el final de la cadena.

LCase(s$) Len(s$) Left(s$, n%) LSet s$ = Text LTrim(s$)

Mid(s$, i%[, n%])

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 reemplazados en s. Add UCase(), RTrim, Trim En 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 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 sera mejor escrita con el mtodo mid(). La diferencia es que el mtodo mid() modifica la cadena actual mientras que esta retorna una nueva cadena. Yo pude hacerla usando el mtodo mid(), pero me di cuenta de esto hasta que fue demasiado tarde.
'Remueve cierto nmero de caracteres de una cadena

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 vaca. Inicialmente pens que poda usar el mtodo mid() para esto tambin, pero este mtodo no puede hacer que la cadena sea ms 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 dnde 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 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 <= 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

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 nmero 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 mtodos y propiedades estn disponibles en un objeto. Los mtodos en esta seccin pueden ser de ayuda.

3.2.1 Determinar el tipo de documento


Esta macro viene con OpenOffice y est incluida aqu como una demostracin sobre cmo 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

3.2.2 Desplegando los mtodos y propiedades de un objeto


Esta es una excelente subrutina. El primer parametro es el objeto en cuestin. El segundo parametro puede ser para desplegar los mtodos y cualquier otra cadena para desplegar las propiedades del objeto. La lista de propiedades o mtodos es frecuentemente tan larga que excede 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: tonyb.lx@btinternet.com 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

3.2.3 Desplegando las propiedades de un objeto en una hoja de clculo.


Esta macro debe ser ejecutada para creer. Herr Hermann Kienlein hizo un impresionante trabajo con esto. Esta macro crea una nueva hoja de clculo y la rellena con informacin sobre los objetos. Yo modifiqu extensivamente esta macro porque usaba variables globales. Las variables globales interferan con mis propias variables locales. Esto me ayudaba a usarla en mi propio cdigo existente.
'****************************************************************** 'Author: Hermann Kienlein 'email: info@kienlein.com '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 informacin 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() ObjInfo(oNewDoc, nSheetsUsed, "getDocumentInfo", oInfo)

'

'

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)

10

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, fr 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 If InStr(1,itemstring,":") < 1 Then

11

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) 'linksbndig ausrichten If frag > "" Then Do nextchr = Asc(Mid(frag,1,1) If nextchr = "10" Then Mid(frag,1,1," ") frag = LTrim(frag) 'linksbndig 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 ' untersttzen 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

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 end select

13

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

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) For iAr = LBound(oBje.getImplementationID()) To _

15

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

16

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

17

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

4 Ejemplos miscelneos

19

4.1 Desplegar texto en la barra de estado


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 'Hay dos mtodos que se pueden usar para obtener 'el indcador de estado Function ProgressBar ProgressBar = ThisComponent.CurrentController.StatusIndicator 'o tambin '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

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: andrew@pitonyak.org 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 21

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

22

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: andrew@pitonyak.org 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

23

Algo como esto imprime la pgina 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

4.6 Cambiando el tamao de una lista


Comentario desde el sitio Web. Bueno, use la macro. Mientras este error no sea corregido, necesitar terminar la tarea despus de aplicar la macro, como un apagado corriente, los valores escritos por la macro sern sobreescritos. Hay algunas otras maneras para lograr lo mismo, pero involucra meterse con archivos locales que son una implementacin detallada de la configuracin del backend, que no voy a mencionar aqui :). 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: 25

~/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 alfabticas. 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 ms 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> ms; 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 ms recientes; digite el nmero que desee. Imagino que no es buena idea hacerlo muy grande, pero no conozco si existe un lmite 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 mtodo terminate() es usado para esto. Este mtodo causa un evento-terminacin que ser transmitido a todos los que escuchen. Si no se devuelve TerminationVetoException, una notificacin de evento26

terminacin es transmitido y se devuelve un valor verdadero. De lo contrario, se transmite un aborte-evento-terminacin y se devuelve un valor falso. Para citar a Mathias Bauer, el mtodo 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, podramos haber usado Xcerrable para el escritorio tambin.[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 [scat@teol.net] 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 URL


Para cargar un documento desde una URL, use el mtodo 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 Parmetros: 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 cmo encontrar el nombre del marco destino (aTargetFrameName). Normalmente, simplemente use 0. http://api.openoffice.org/common/ref/com/sun/star/frame/FrameSearchFlag.html

27

Nombre SELF+CHILDREN Incluye el marco padre

Descripcin

0 Auto 1 PARENT 2 4 8 SELF CREATE

Incluye el marco inicial Ser creado un marco, si no existe Incluye otros marcos hijos del marco inicial Incluye todos los marcos en todas las tareas de la actual jerarqua de marcos. Incluye todos los marcos de las otras tareas. 23 = 1+2+4+16 = PARENT + SELF + CHILDREN + SIBLINGS. Busca en toda la jerarqua de marcos. 55 = 1+2+4+16+32 = PARENT + SELF + CHILDREN + SIBLINGS + TASKS. GLOBAL + CREATE

CHILDREN Incluye los marcos hijos del marco inicial

16 SIBLINGS 32 23 TASKS ALL

55 63

GLOBAL

aArgs: 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, 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)

28

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 End Function

29

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. Cmo puedo canalizar una cadena por medio de un programa externo? Algn ejemplo? ?? Pruebe esto!
'****************************************************************** 'Author: Pavel Jank 'email: Pavel@Janik.cz 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

30

4.10 Leer y escribir en un archivo


Este ejemplo lee un nmero desde un archivo de texto. Este valor es convertido en nmero e incrementado. El nmero es escrito de nuevo en el archivo como una cadena.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 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

31

CLOSE #iNum End Sub

32

4.11 Creando un estilo de formato numrico


Si desea un formato particular de nmero, entonces puede observar si existe y crearlo si no lo tiene. Para ms informacin sobre fomatos validos, vea los contenidos de la ayuda en los tpicos number formats; formats. Estos pueden ser bastante complejos.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 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

33

4.12 Retorna una matriz Fibonnaci


Esta 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 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 nmero de campos de usuario a ms de 4? AFAIK no. Qu encontraste sobre campos de usuario de documento de informacin. 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 estn en el objeto Odoc. Puede obtenerlos con el getTextFields() y getTextFieldMasters() 34

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. Tambin puede usar getUserFieldName(index) o getUserFieldValue(index) para leer estos campos.

35

5 Macros de Calc
5.1 Es este un libro de clculo?
Un libro de clculo est compuesto de un conjunto de hojas. Antes de poder usar los mtodos especficos del libro de clculo, debe tener un documento libro de clculo. 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 Frmula.


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 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 Frmula.


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 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)

37

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: andrew@pitonyak.org 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 clculo puede ser diferentes cosas; algunas las entiendo y otras 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 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.

38

'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 End 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 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

40

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 clculo. El cdigo provee la manera de formatear la fecha con el estilo que elija. Lolo necesita pero quitele el comentario.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org '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 dilogo


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 'This macro will take the current selection and print a message 'box indicating the selected range and the number of selected 'cells Sub SelectedCells oSelect=ThisComponent.CurrentSelection.getRangeAddress

41

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 travs del texto seleccionado ponindo el texto en OOPS.
'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 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

42

5.10 Algunos estados del texto seleccionado


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 'Esta macro toma la seleccin actual e imprime un mensaje 'indicando el rango seleccionado y el nmero 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 Sub DeleteDbRange(sRangeName As String)

43

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: scat@teol.net 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: scat@teol.net Sub DeleteDbRange(sRangeName As String) oRange=ThisComponent.DatabaseRanges oRange.removeByName (sRangeName) End Sub

5.13 Rango bordes de lnea


?? Est modificando la estructura temporal aqui. Use algo como esto.
'****************************************************************** 'Author: Niklas Nebel 'email: niklas.nebel@sun.com ' 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

44

5.14 Ordenar un rango


'****************************************************************** 'Author: Sasa Kelecevic 'email: scat@teol.net 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

45

5.15 Imprimir todos los datos en una columna


Mientras cambiaba la celda y los valores a imprimir, quera imprimir informacin sobre las celdas. He aqui cmo lo hice.
Sub PrintDataInColumn (a_column As Integer) Dim oCells As Object, aCell As Object, oDocument As Object Dim oColumn As Object, oRanges As Object oDocument = ThisComponent oColumn = oDocument.Sheets(0).Columns(a_column) Print "Using column " + oColumn.getName oRanges = oDocument.createInstance("com.sun.star.sheet.SheetCellRanges") oRanges.insertByName("", oColumn) oCells = oRanges.Cells.createEnumeration If 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 Wend End Sub

5.16 Usando mtodos de bordes (agrupamiento)


Ryan Nelson [ryan@aurelius-mfg.com] me dijo sobre la capacidad de bordes y luego me cont cmo hacer esta macro. Hay dos cosas que debe tener en mente. La primera es que es la hoja que agrega y remueve el arupamiento, y la segunda es que los parmetros deben ser los correctos. http://api.openoffice.org/common/ref/com/sun/star/sheet/XSheetOutline.html http://api.openoffice.org/common/ref/com/sun/star/table/TableOrientation.html
Option Explicit Sub CalcGroupingExample Dim oDoc As Object, oRange As Object, oSheet As Object oDoc = ThisComponent If Not oDoc.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Then MsgBox "This macro must be run from a spreadsheet document", 64, "Error" End If oSheet=oDoc.Sheets.getByName("Sheet1") ' Parms are (left, top, right, bottom) oRange = oSheet.getCellRangeByPosition(2,1,3,2) 'Could also use COLUMNS oSheet.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 datos


Es fcil proteger sus hojas de clculo, solamente tiene que llamar su hoja y protegerla. Mi experimento indica que sin embargo no genera un error cuando elige proteger un documento entero, pero no proteger el documento entero.
Sub ProtectSpreadsheet dim oDoc As Object, oSheet As Object oDoc = ThisComponent oSheet=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 la seleccin 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 algunas instancias, sin embargo, con los resultados de los mtodos getString() y setString() que no entiendo. Sin embargo, es probablemente mejor usar un cursor para cambiar el texto seleccionado y despus usar los mtodos insertString() y insertControlCharacter() del objeto de texto. La documentacin especficamente indica que los siguientes caracteres blancos son 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 la izquierda de la seleccin. Una seleccin tiene un punto de inicio y punto final y no se puede saber cual esta a la izquierda y cual est a la derecha del texto seleccionado. Un mtodo mostrado 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 parametro es un entero indicando cuntos caracteres o lineas se movern. El segundo parmetro es un valor boleano para indicar si el texto seleccionado se puede expandir (true) o no. El valor de True (verdadero) es retornado mientras ocurre el movimiento. Si un cursor ha seleccionado texto por el movimiento izquierdo y desea moverlo a la derecha, probablemente quiera usar oCursor.goRight(0, False) para indicar al cursor que empiece a moverse a la derecha y no seleccione 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 posicin final entonces no hay texto seleccionado y la propiedad IsCollapsed ser verdadera. Un cursor de texto implementa interfaces que permite movimientos y reconocimiento de posiciones especficas a palabras, oraciones, y prafos. Esto puede ahorrar bastante tiempo.

Advertencia Cursor.gotoStart() y Cursor.gotoEnd() va al inicio o al final del


documento aun si el cursor est creado sobre un rango. Ver tambin: http://api.openoffice.org/common/ref/com/sun/star/view/XViewCursor.html http://api.openoffice.org/common/ref/com/sun/star/text/TextCursor.html http://api.openoffice.org/common/ref/com/sun/star/text/XWordCursor.html http://api.openoffice.org/common/ref/com/sun/star/text/XSentenceCursor.html http://api.openoffice.org/common/ref/com/sun/star/text/XParagraphCursor.html 49

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.3 Andrew's Selected Text Framework


Muchos problemas al usar texto seleccionado se ven en un nivel abstracto.
If nothing is selected then do work on entire document else for each selected area do work on selected area

The difficult part that will change each time is writing a worker macro that will iterate over a selection or between two cursors.

6.3.1 Hay texto seleccionado?


Los estados del documentacin son si no hay controlador actual, entonces getCurrentSelection() regresar un valor nulo que cuando hay selecciones. Tengo un conocimiento limitado de esto pero tratar de explicarlo y verificarlo. Si la seleccin es cero, nada est seleccionado. Nunca he vista un conteo de seleccin de cero, pero chequeelo de cualquier manera. Si no hay texto seleccionado, Tengo una seleccin de tamao cero. He visto ejemplos donde la seleccin es cero y se determina de la siguiente manera:
If Len(oSel.getString()) = 0 Then nothing is selected

El problema con esto es que es posible que el texto seleccionado pueda contener ms de 64K en caracteres y una cadena no puede contener ms de 64 caracteres. Yo considero que esto no es seguro. La mejor solucin es crear un cursor de texto del rango seleccionado y luego chequearlo para ver si las posiciones de inicio y final son iguales.
oCursor = oDoc.Text.CreateTextCursorByRange(oSel) If oCursor.IsCollapsed() Then nothing is selected

Aqui hay una funcin que har la verificacin completa:


Function IsAnythingSelected(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. 'If there is no current controller, it returns NULL. oSelections = oDoc.getCurrentSelection() If IsNull(oSelections) Then Exit Function If oSelections.getCount() = 0 Then Exit Function If oSelections.getCount() > 1 Then IsAnythingSelected = True Else oSel = oSelections.getByIndex(0) oCursor = oDoc.Text.CreateTextCursorByRange(oSel) If Not oCursor.IsCollapsed() Then IsAnythingSelected = True

50

End If End Function

6.3.2 Cmo obtener una seleccin


Obtener una seleccin es complicado porque es posible que tenga multiples selecciones no contiguas o adyacentes. Algunas selecciones son vacas y algunas no. El cdigo est escrito para manejar todos estos casos. El siguiente ejemplo cambia dentro de todas las secciones seleccionadas y las imprime.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org Sub MultipleTextSelectionExample Dim oSelections As Object, oSel As Object, oText As Object Dim lSelCount As Long, lWhichSelection As Long ' The current selection in the current controller. 'If there is no current controller, it returns NULL. oSelections = ThisComponent.getCurrentSelection() If Not IsNull(oSelections) Then oText = ThisComponent.Text lSelCount = oSelections.getCount() For lWhichSelection = 0 To lSelCount - 1 oSel = oSelections.getByIndex(lWhichSelection) MsgBox oSel.getString() Next End If End Sub

See Also: http://api.openoffice.org/common/ref/com/sun/star/text/XTextRange.html

6.3.3 Selected Text, Which End Is Which


Selecciones son esencialmente rangos de texto con un inicio y un final. Como las selecciones tienen ambas un inicio y un final, que lado de la seleccin es cul se determina por el mtodo de seleccin. El objeto de texto provee mtodos para comparar las posiciones de inicio y final de los rangos de texto. El mtodo short compareRegionStarts (XTextRange R1, XTextRange R2) regresar 1 si R1 inicia antes de R2 , 0 si R1 inicia en la misma posicin que R2 y -1 si R1 inicia despus de R2. El mtodo short compareRegionEnds (XTextRange R1, XTextRange R2) retorna 1, si R1 finaliza antes de R2 , 0, si R1 finaliza en la misma posicin que R2 y -1, si R1 finaliza detrs de R2. Yo uso los siguientes dos mtodos para encontrar la posicin ms a la izquierda o ms a la derecha del cursor del texto seleccionado.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'oSelection is a text selection or cursor range

51

'oText is the text object Function GetLeftMostCursor(oSel As Object, oText As Object) As Object Dim oRange As Object, oCursor As Object If oText.compareRegionStarts(oSel.getEnd(), oSel) >= 0 Then oRange = oSel.getEnd() Else oRange = oSel.getStart() End If oCursor = oText.CreateTextCursorByRange(oRange) oCursor.goRight(0, False) GetLeftMostCursor = oCursor End Function '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'oSelection is a text selection or cursor range 'oText is the text object Function GetRightMostCursor(oSel As Object, oText As Object) As Object Dim oRange As Object, oCursor As Object If oText.compareRegionStarts(oSel.getEnd(), oSel) >= 0 Then oRange = oSel.getStart() Else oRange = oSel.getEnd() End If oCursor = oText.CreateTextCursorByRange(oRange) oCursor.goLeft(0, False) GetRightMostCursor = oCursor End Function

See Also: http://api.openoffice.org/common/ref/com/sun/star/text/XTextCursor.html http://api.openoffice.org/common/ref/com/sun/star/text/XSimpleText.html http://api.openoffice.org/common/ref/com/sun/star/text/XTextRangeCompare.html

6.3.4 Sistema Macro de texto seleccionado


Me tom mucho tiempo entender como interactuar sobre el texto seleccionado usando los cursores, por eso tuve que escribir muchas macros que hacen cosas que considero equivocadas. Ahora uso sistemas de alto nivel para hacerlas. La idea es que si no hay texto seleccionado, entonces pregunta a la macro si se debe ejecutar contra todo el documento. Si la pregunta es si, entonces el cursor es creado al inicio y al final del documento, y luego la macro es ejecutada. Si hay texto seleccionado, entonces cada seleccin es traida, un cursor es obtenido al inicio y final de la seleccin, y la macro es ejecutada para cada una de estas selecciones.

52

El sistema rechazado

Ultimamente rechac el siguiente sistema porque es muy largo y dificil de manejar y repetir cada vez que deseo interactuar contra el texto. Sin embargo es aceptable. Puede ser que prefiera este sistema y escoja usarlo.
Sub IterateOverSelectedTextFramework Dim oSelections As Object, oSel As Object, oText As Object Dim lSelCount As Long, lWhichSelection As Long Dim oLCursor As Object, oRCursor As Object oText = ThisComponent.Text If Not IsAnythingSelected(ThisComponent) Then Dim i% i% = MsgBox("No text selected!" + Chr(13) + _ "Call worker for the ENTIRE document?", _ 1 OR 32 OR 256, "Warning") If i% <> 1 Then Exit Sub oLCursor = oText.createTextCursor() oLCursor.gotoStart(False) oRCursor = oText.createTextCursor() oRCursor.gotoEnd(False) CallYourWorkerMacroHere(oLCursor, oRCursor, oText) Else oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() For lWhichSelection = 0 To lSelCount - 1 oSel = oSelections.getByIndex(lWhichSelection) 'If I want to know if NO text is selected, I could 'do the following: 'oLCursor = oText.CreateTextCursorByRange(oSel) 'If oLCursor.isCollapsed() Then ... oLCursor = GetLeftMostCursor(oSel, oText) oRCursor = GetRightMostCursor(oSel, oText) CallYourWorkerMacroHere(oLCursor, oRCursor, oText) Next End If End Sub

El sistema aceptable

Opt por crear el siguiente sistema. Devuelve un arreglo bidimensional de los cursores de inicio y final sobre las cuales interactuar. Esto permite usar un mnimo cdigo base para interactuar sobre el texto seleccionado o sobre el documento entero.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'sPrompt : how to ask if should iterate over the entire text 'oCursors() : Has the return cursors 'Returns true if should iterate and false if should not Function CreateSelectedTextIterator(oDoc As Object, sPrompt As String, oCursors()) As Boolean

53

Dim oSelections As Object, oSel As Object, oText As Object Dim lSelCount As Long, lWhichSelection As Long Dim oLCursor As Object, oRCursor As Object CreateSelectedTextIterator = True oText = oDoc.Text If Not IsAnythingSelected(ThisComponent) Then Dim i% i% = MsgBox("No text selected!" + Chr(13) + sPrompt, _ 1 OR 32 OR 256, "Warning") If i% = 1 Then oLCursor = oText.createTextCursor() oLCursor.gotoStart(False) oRCursor = oText.createTextCursor() oRCursor.gotoEnd(False) oCursors = DimArray(0, 1) oCursors(0, 0) = oLCursor oCursors(0, 1) = oRCursor Else oCursors = DimArray() CreateSelectedTextIterator = False End If Else oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() oCursors = DimArray(lSelCount - 1, 1) For lWhichSelection = 0 To lSelCount - 1 oSel = oSelections.getByIndex(lWhichSelection) 'If I want to know if NO text is selected, I could 'do the following: 'oLCursor = oText.CreateTextCursorByRange(oSel) 'If oLCursor.isCollapsed() Then ... oLCursor = GetLeftMostCursor(oSel, oText) oRCursor = GetRightMostCursor(oSel, oText) oCursors(lWhichSelection, 0) = oLCursor oCursors(lWhichSelection, 1) = oRCursor Next End If End Function

El trabajo principal

Este es un ejemplo que llama a la rutina del trabajo principal.


Sub PrintExample Dim oCursors(), i% If Not CreateSelectedTextIterator(ThisComponent, _ "Print characters for the entire document?", oCursors()) Then Exit Sub For i% = LBOUND(oCursors()) To UBOUND(oCursors()) PrintEachCharacterWorker(oCursors(i%, 0), oCursors(i%, 1), ThisComponent.Text) Next i% End Sub

54

6.3.5 Desplegando caracteres, un ejemplo simple.


Este simple ejemplo puede ser usado con el sistema anterior.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org Sub PrintEachCharacterWorker(oLCursor As Object, oRCursor As Object, oText As Object) If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub oLCursor.goRight(0, False) Do While oLCursor.goRight(1, True) AND oText.compareRegionEnds(oLCursor, oRCursor) >= 0 Print "Character = '" & oLCursor.getString() & "'" Rem This will cause the currently selected text to become Rem no longer selected oLCursor.goRight(0, False) Loop End Sub

6.3.6 Remover espacios y lneas vacos, un gran ejemplo.


Este grupo de macros remueve todos los espacios en blanco con un espacio sencillo. Es fcil de modificar para borrar diferentes tipos de espacios en blanco. Los diferentes tipos de espacios en blanco estn ordenados por importancia de manera que puede tener un espacio regular seguido de un prrafo nuevo, el nuevo prrafo se mantiene y el espacio es removido. Esto causar que los espacios iniciales y finales de las lneas son removidos.
Qu es un espacio en blanco?

Para resolver este problema, mi primera tarea es determinar cuales caracteres son espacios en blanco. Puede trivialmente cambiar la definicin de espacio en blanco para ignorar ciertos caracteres.
'Usually, this is done with an array lookup which would probably be 'faster, but I do not know how to use static initializers in basic. Function IsWhiteSpace(iChar As Integer) As Boolean Select Case iChar Case 9, 10, 13, 32, 160 IsWhiteSpace = True Case Else IsWhiteSpace = False End Select End Function

Rangos de caracteres para borrar

Luego, necesito definir que remover y que debo dejar. Opt por hacer esto con la siguiente rutina.
'-1 means delete the previous character ' 0 means ignore this character

55

' 1 means delete this character ' Rank from highest to lowest is: 0, 13, 10, 9, 160, 32 Function RankChar(iPrevChar, iCurChar) As Integer If Not IsWhiteSpace(iCurChar) Then 'The current char is not white space, ignore it RankChar = 0 ElseIf iPrevChar = 0 Then 'Start of a line and current char is white space RankChar = 1 ' so delete the current character. ElseIf Not IsWhiteSpace(iPrevChar) Then 'Current char is white space but previous is not RankChar = 0 ' so ignore the current charcter. ElseIf iPrevChar = 13 Then 'Previous char is highest ranked white space RankChar = 1 ' so delete the current character. ElseIf iCurChar = 13 Then 'Current character is highest ranked white space RankChar = -1 ' so delete the previous character. ElseIf iPrevChar = 10 Then 'No new Pars so see if the previous char is new line RankChar = 1 ' so delete the current character. ElseIf iCurChar = 10 Then 'No new Pars so see if the current char is new line RankChar = -1 ' so delete the previous character. ElseIf iPrevChar = 9 Then 'No new Lines so see if the previous char is tab RankChar = 1 ' so delete the current character. ElseIf iCurChar = 9 Then 'No new Lines so see if the current char is a tab RankChar = -1 ' so delete the previous character. ElseIf iPrevChar = 160 Then 'No Tabs so check previous char for a hard space RankChar = 1 ' so delete the current character. ElseIf iCurChar = 160 Then 'No Tabs so check current char for a hard space RankChar = -1 ' so delete the previous character. ElseIf iPrevChar = 32 Then 'No hard spaces so check previous for a space RankChar = 1 ' so delete the current character. ElseIf iCurChar = 32 Then 'No hard spaces so check current for a space RankChar = -1 ' so delete the previous character. Else 'Should probably not get here RankChar = 0 ' so simply ignore it! End If End Function

El interativo seleccionador de texto

Esto es el formato estandar para decidir si debe hacerlo sobre todo el documento o sobre una porcin.
'Remove all runs of empty space! 'If text is selected, then it will only be removed from the selected region. Sub RemoveEmptySpace Dim oCursors(), i% If Not CreateSelectedTextIterator(ThisComponent, _ "ALL empty space will be removed from the ENTIRE document?", oCursors()) Then Exit Sub For i% = LBOUND(oCursors()) To UBOUND(oCursors()) RemoveEmptySpaceWorker (oCursors(i%, 0), oCursors(i%, 1), ThisComponent.Text) Next i% End Sub

56

La macro principal

Esto es donde el trabajo real sucede.


Sub RemoveEmptySpaceWorker(oLCursor As Object, oRCursor As Object, oText As Object) Dim sParText As String, i As Integer If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub Dim iLastChar As Integer, iThisChar As Integer, iRank As Integer iLastChar = 0 iThisChar = 0 oLCursor.goRight(0, False) Do While oLCursor.goRight(1, True) iThisChar = Asc(oLCursor.getString()) i = oText.compareRegionEnds(oLCursor, oRCursor) 'If at the last character! 'Then always remove white space If i = 0 Then If IsWhiteSpace(iThisChar) Then oLCursor.setString("") Exit Do End If 'If went past the end then get out If i < 0 Then Exit Do iRank = RankChar(iLastChar, iThisChar) If iRank = 1 Then 'I am about to delete this character. 'I do not change iLastChar because it did not change! 'Print "Deleting Current with " + iLastChar + " and " + iThisChar oLCursor.setString("") ElseIf iRank = -1 Then 'This will deselect the selected character and then select one 'more to the left. oLCursor.goLeft(2, True) 'Print "Deleting to the left with " + iLastChar + " and " + iThisChar oLCursor.setString("") oLCursor.goRight(1, False) iLastChar = iThisChar Else oLCursor.goRight(0, False) iLastChar = iThisChar End If Loop End Sub

6.3.7 Removiendo prrafos vacos, slo otro ejemplo.


Es mejor poner un AutoFormato para remover prrafos en blanco, y luego aplicarlo al documento en cuestin. Haga click en Herramientass=>AutoCorreccin/AutoFormato... y luego seleccionar la cejilla Opciones. Una de las opciones es Remover prrafos en blanco. Asegrese que est marcado. Ahora, puede auto formatear el documento y todos los 57

prrafos en blanco sern removidos. Si desea remover prrafos vacos de una seleccin, entonces necesitar ejecutar esta macro. Si el texto est seleccionado, entonces los prrafos vacos son removidos dentro del texto seleccionado. Si no hay texto seleccionado, se remover del documento entero. Esta primera macro iteracciona sobre el texto seleccionado. Si no hay texto seleccionado, crea un cursor al inicio y al final del documento. La primera cosa que ve esta macro es como atravesar por los prrafos basados en texto. La macro para remover espacios es ms segura porque esta no necesita extraer una cadena para trabajar.
Sub RemoveEmptyParsWorker(oLCursor As Object, oRCursor As Object, oText As Object) Dim sParText As String, i As Integer If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub oLCursor.goRight(0, False) Do While oLCursor.gotoNextParagraph(TRUE) AND oText.compareRegionEnds(oLCursor, oRCursor) > 0 'Yes, I know, limited to 64K here 'If we have one paragraph that is over 64K 'Then I am in trouble! sParText = oLCursor.getString() i = Len(sParText) 'We do not have short circuit logical. Drat! Do While i > 0 If (Mid(sParText,i,1) = Chr(10)) OR (Mid(sParText,i,1) = Chr(13)) Then i=i-1 Else i = -1 End If Loop If i = 0 Then oLCursor.setString("") Else oLCursor.goLeft(0,FALSE) End If loop End Sub

6.4 Reemplazando espacios seleccionados usando cadenas.


En general, no se debera remover espacios extra al leer el texto seleccionado y volvindo a escribir los nuevos valores de nuevo. Una razn es porque las cadenas estn limitadas a 64K de tamao, y la otra es que es posible perder informacin de formateo. Dej estos ejemplos porque trabajan con problemas que fueron escritos antes de que aprendiera cmo hacer lo mismo con cursores., y porque demuestran tecnicas de insertado de caracteres especiales. La primera macro reemplaza todos los nuevos prrafos y nuevas lneas con caracteres de espacios. Este ejemplo tambin demuestra cmo insertar caracteres de control (nuevos prrafos, cambios de lnea, etc.) dentro del texto.
Sub SelectedNewLinesToSpaces

58

Dim lSelCount&, oSelections As Object Dim iWhichSelection As Integer, lIndex As Long Dim s$, bSomethingChanged As Boolean oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() For iWhichSelection = 0 To lSelCount - 1 bSomethingChanged = False Rem What if the string is bigger than 64K? Oops s = oSelections.getByIndex(iWhichSelection).getString() lIndex = 1 Do While lIndex < Len(s) Select Case Asc(Mid(s, lIndex, 1)) Case 13 'We found a new paragraph marker. 'The next character will be a 10! If lIndex < Len(s) And Asc(Mid(s, lIndex+1, 1)) = 10 Then Mid(s, lIndex, 2, " ") Else Mid(s, lIndex, 1, " ") End If lIndex = lIndex + 1 bSomethingChanged = True Case 10 'New line unless the previous charcter is a 13 'Remove this entire case statement to ignore only new lines! If lIndex > 1 And Asc(Mid(s, lIndex-1, 1)) <> 13 Then 'This really is a new line and NOT a new paragraph. Mid(s, lIndex, 1, " ") lIndex = lIndex + 1 bSomethingChanged = True Else 'Nope, this one really was a new paragraph! lIndex = lIndex + 1 End If Case Else 'Do nothing if we do not match something else lIndex = lIndex + 1 End Select Loop If bSomethingChanged Then oSelections.getByIndex(iWhichSelection).setString(s) End If Next End Sub

Tambin se debe preguntar cmo convertir nuevos prrafos en nuevas lneas. Usar cursores es claramente una mejor idea, pero no s como hacerlo. Pienso que este ejemplo es an instructivo, por eso lo dej. Primero borr el texto seleccionado y despus empezar a agregar el texto de nuevo.
Sub SelectedNewParagraphsToNewLines

59

Dim lSelCount&, oSelections As Object, oSelection As Object Dim iWhichSelection As Integer, lIndex As Long Dim oText As Object, oCursor As Object Dim s$, lLastCR As Long, lLastNL As Long oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() oText=ThisComponent.Text For iWhichSelection = 0 To lSelCount - 1 oSelection = oSelections.getByIndex(iWhichSelection) oCursor=oText.createTextCursorByRange(oSelection) s = oSelection.getString() 'Delete the selected text! oCursor.setString("") lIndex = 1 Do While lIndex <= Len(s) Select Case Asc(Mid(s, lIndex, 1) Case 13 oText.insertControlCharacter(oCursor, _ com.sun.star.text.ControlCharacter.LINE_BREAK, False) 'I wish I had short circuit booleans! 'Skip the next LF if there is one. I think there 'always will be but I can not verify this If (lIndex < Len(s)) Then If Asc(Mid(s, lIndex+1, 1)) = 10 Then lIndex = lIndex + 1 End If Case 10 oText.insertControlCharacter(oCursor, _ com.sun.star.text.ControlCharacter.LINE_BREAK, False) Case Else oCursor.setString(Mid(s, lIndex, 1)) oCursor.GoRight(1, False) End Select lIndex = lIndex + 1 Loop Next End Sub

6.4.1 Comparacin de cursores y ejemplos de cadenas


Aqui hay algunas macros que escrib usando mtodos de cursores y siguindolos, de la misma manera que antes hice mis sistemas.!
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'The purpose of this macro is to make it easier to use the Text<-->Table 'method which wants trailing and leading white space removed. 'It also wants new paragraphs and NOT new lines! Sub CRToNLMain Dim oCursors(), i%, sPrompt$ sPrompt$ = "Convert New Paragraphs to New Lines for the ENTIRE

60

document?" If Not CreateSelectedTextIterator(ThisComponent, sPrompt$, oCursors()) Then Exit Sub For i% = LBOUND(oCursors()) To UBOUND(oCursors()) CRToNLWorker(oCursors(i%, 0), oCursors(i%, 1), ThisComponent.Text) Next i% End Sub Sub CRToNLWorker(oLCursor As Object, oRCursor As Object, oText As Object) If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub oLCursor.goRight(0, False) Do While oLCursor.gotoNextParagraph(False) AND oText.compareRegionEnds (oLCursor, oRCursor) >= 0 oLCursor.goLeft(1, True) oLCursor.setString("") oLCursor.goRight(0, False) oText.insertControlCharacter(oLCursor,_ com.sun.star.text.ControlCharacter.LINE_BREAK, True) Loop End Sub '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'The real purpose of this macro is to make it easier to use the Text<->Table 'method which wants trailing and leading white space removed. 'It also wants new paragraphs and NOT new lines! Sub SpaceToTabsInWordsMain Dim oCursors(), i%, sPrompt$ sPrompt$ = "Convert Spaces to TABS for the ENTIRE document?" If Not CreateSelectedTextIterator(ThisComponent, sPrompt$, oCursors()) Then Exit Sub For i% = LBOUND(oCursors()) To UBOUND(oCursors()) SpaceToTabsInWordsWorker(oCursors(i%, 0), oCursors(i%, 1), ThisComponent.Text) Next i% End Sub Sub SpaceToTabsInWordsWorker(oLCursor As Object, oRCursor As Object, oText As Object) Dim iCurrentState As Integer, iChar As Integer, bChanged As Boolean Const StartLineState = 0 Const InWordState = 1 Const BetweenWordState = 2 If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub oLCursor.goRight(0, False) iCurrentState = StartLineState bChanged = False Do While oLCursor.goRight(1, True) AND oText.compareRegionEnds (oLCursor, oRCursor) >= 0 iChar = Asc(oLCursor.getString()) If iCurrentState = StartLineState Then If IsWhiteSpace(iChar) Then oLCursor.setString("") Else iCurrentState = InWordState End If ElseIf iCurrentState = InWordState Then

61

bChanged = True Select Case iChar Case 9 Rem It is already a tab, ignore it iCurrentState = BetweenWordState Case 32, 160 Rem Convert the space to a tab oLCursor.setString(Chr(9)) oLCursor.goRight(1, False) iCurrentState = BetweenWordState Case 10 Rem Remove the new line and insert a new paragraph oText.insertControlCharacter(oLCursor,_ com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, True) oLCursor.goRight(1, False) iCurrentState = StartLineState Case 13 iCurrentState = StartLineState Case Else oLCursor.gotoEndOfWord(True) End Select ElseIf iCurrentState = BetweenWordState Then Select Case iChar Case 9, 32, 160 Rem We already added a tab, this is extra stuff! oLCursor.setString("") Case 10 Rem Remove the new line and insert a new paragraph Rem and be sure to delete the leading TAB that we already Rem added in and that should come out! oText.insertControlCharacter(oLCursor,_ com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, True) oLCursor.goLeft(0, False) Rem and over the TAB for deletion oLCursor.goLeft(1, True) oLCursor.setString("") oLCursor.goRight(1, False) iCurrentState = StartLineState Case 13 Rem first, backup over the CR, then select the TAB and delete it oLCursor.goLeft(0, False) oLCursor.goLeft(1, False) oLCursor.goLeft(1, True) oLCursor.setString("") Rem finally, move back over the CR that we will ignore oLCursor.goRight(1, True) iCurrentState = StartLineState Case Else iCurrentState = InWordState oLCursor.gotoEndOfWord(False) End Select End If oLCursor.goRight(0, False) Loop If bChanged Then Rem To get here, we went one character too far right oLCursor.goLeft(1, False) oLCursor.goLeft(1, True)

62

If Asc(oLCursor.getString()) = 9 Then oLCursor.setString("") End If End Sub '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org Sub TabsToSpacesMain Dim oCursors(), i%, sPrompt$ sPrompt$ = "Convert TABS to Spaces for the ENTIRE document?" If Not CreateSelectedTextIterator(ThisComponent, sPrompt$, oCursors()) Then Exit Sub For i% = LBOUND(oCursors()) To UBOUND(oCursors()) TabsToSpacesWorker(oCursors(i%, 0), oCursors(i%, 1), ThisComponent.Text) Next i% End Sub Sub TabsToSpacesWorker(oLCursor As Object, oRCursor As Object, oText As Object) If IsNull(oLCursor) Or IsNull(oRCursor) Or IsNull(oText) Then Exit Sub If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then Exit Sub oLCursor.goRight(0, False) Do While oLCursor.goRight(1, True) AND oText.compareRegionEnds (oLCursor, oRCursor) >= 0 If Asc(oLCursor.getString()) = 9 Then oLCursor.setString(" ") 'Change a tab into 4 spaces End If oLCursor.goRight(0, False) Loop End Sub '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'sPrompt : how to ask if should iterate over the entire text 'oCursors() : Has the return cursors 'Returns true if should iterate and false if should not Function CreateSelectedTextIterator(oDoc As Object, sPrompt As String, oCursors()) As Boolean Dim oSelections As Object, oSel As Object, oText As Object Dim lSelCount As Long, lWhichSelection As Long Dim oLCursor As Object, oRCursor As Object CreateSelectedTextIterator = True oText = oDoc.Text If Not IsAnythingSelected(ThisComponent) Then Dim i% i% = MsgBox("No text selected!" + Chr(13) + sPrompt, _ 1 OR 32 OR 256, "Warning") If i% = 1 Then oLCursor = oText.createTextCursor() oLCursor.gotoStart(False) oRCursor = oText.createTextCursor() oRCursor.gotoEnd(False) oCursors = DimArray(0, 1) oCursors(0, 0) = oLCursor oCursors(0, 1) = oRCursor Else oCursors = DimArray() CreateSelectedTextIterator = False End If

63

Else oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() oCursors = DimArray(lSelCount - 1, 1) For lWhichSelection = 0 To lSelCount - 1 oSel = oSelections.getByIndex(lWhichSelection) 'If I want to know if NO text is selected, I could 'do the following: 'oLCursor = oText.CreateTextCursorByRange(oSel) 'If oLCursor.isCollapsed() Then ... oLCursor = GetLeftMostCursor(oSel, oText) oRCursor = GetRightMostCursor(oSel, oText) oCursors(lWhichSelection, 0) = oLCursor oCursors(lWhichSelection, 1) = oRCursor Next End If End Function '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'oDoc is a writer object Function IsAnythingSelected(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. 'If there is no current controller, it returns NULL. oSelections = oDoc.getCurrentSelection() If IsNull(oSelections) Then Exit Function If oSelections.getCount() = 0 Then Exit Function If oSelections.getCount() > 1 Then IsAnythingSelected = True Else oSel = oSelections.getByIndex(0) oCursor = oDoc.Text.CreateTextCursorByRange(oSel) If Not oCursor.IsCollapsed() Then IsAnythingSelected = True End If End Function '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'oSelection is a text selection or cursor range 'oText is the text object Function GetLeftMostCursor(oSel As Object, oText As Object) As Object Dim oRange As Object, oCursor As Object If oText.compareRegionStarts(oSel.getEnd(), oSel) >= 0 Then oRange = oSel.getEnd() Else oRange = oSel.getStart() End If oCursor = oText.CreateTextCursorByRange(oRange) oCursor.goRight(0, False) GetLeftMostCursor = oCursor End Function '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org

64

'oSelection is a text selection or cursor range 'oText is the text object Function GetRightMostCursor(oSel As Object, oText As Object) As Object Dim oRange As Object, oCursor As Object If oText.compareRegionStarts(oSel.getEnd(), oSel) >= 0 Then oRange = oSel.getStart() Else oRange = oSel.getEnd() End If oCursor = oText.CreateTextCursorByRange(oRange) oCursor.goLeft(0, False) GetRightMostCursor = oCursor End Function '****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'oSelection is a text selection or cursor range 'oText is the text object Function IsWhiteSpace(iChar As Integer) As Boolean Select Case iChar Case 9, 10, 13, 32, 160 IsWhiteSpace = True Case Else IsWhiteSpace = False End Select End Function

'****************************************************************** 'Here starts the OLD macros! 'Author: Andrew Pitonyak Sub ConvertSelectedNewParagraphToNewLine Dim lSelCount&, oSelections As Object, oSelection As Object Dim iWhichSelection As Integer, lIndex As Long Dim oText As Object, oCursor As Object Dim s$, lLastCR As Long, lLastNL As Long 'There may be multiple selections present! oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() oText=ThisComponent.Text For iWhichSelection = 0 To lSelCount - 1 oSelection = oSelections.getByIndex(iWhichSelection) oCursor=oText.createTextCursorByRange(oSelection) s = oSelection.getString() oCursor.setString("") lLastCR = -1 lLastNL = -1 lIndex = 1 Do While lIndex <= Len(s) Select Case Asc(Mid(s, lIndex, 1) Case 13 oText.insertControlCharacter(oCursor,_ com.sun.star.text.ControlCharacter.LINE_BREAK, False) 'Boy I wish I had short circuit booleans! 'Skip the next LF if there is one. I think that there

65

'always will be but I can not verify this If (lIndex < Len(s)) Then If Asc(Mid(s, lIndex+1, 1)) = 10 Then lIndex = lIndex + 1 End If Case 10 oText.insertControlCharacter(oCursor,_ com.sun.star.text.ControlCharacter.LINE_BREAK, False) Case Else oCursor.setString(Mid(s, lIndex, 1)) oCursor.GoRight(1, False) End Select lIndex = lIndex + 1 Loop Next End Sub

'I decided to write this as a finite state machine 'Finite state machines are a wonderful thing :-) Sub ConvertSelectedSpaceToTabsBetweenWords Dim lSelCount&, oSelections As Object, oSelection As Object Dim iWhichSelection As Integer, lIndex As Long Dim oText As Object, oCursor As Object Dim s$, lLastCR As Long, lLastNL As Long Rem What states are supported Dim iCurrentState As Integer Const StartLineState = 0 Const InWordState = 1 Const BetweenWordState = 2 Rem Transition Points Dim iWhatFound As Integer Const FoundWhiteSpace = 0 Const FoundNewLine = 1 Const FoundOther = 2 Const ActionIgnoreChr = 0 Const ActionDeleteChr = 1 Const ActionInsertTab = 2 Rem Define the state transitions Dim iNextState(0 To 2, 0 To 2, 0 To 1) As Integer iNextState(StartLineState, FoundWhiteSpace, 0) = StartLineState iNextState(StartLineState, FoundNewLine, 0) = StartLineState iNextState(StartLineState, FoundOther, 0) = InWordState iNextState(InWordState, FoundWhiteSpace, 0) = BetweenWordState iNextState(InWordState, FoundNewLine, 0) = StartLineState iNextState(InWordState, FoundOther, 0) = InWordState iNextState(BetweenWordState, FoundWhiteSpace, 0)= BetweenWordState iNextState(BetweenWordState, FoundNewLine, 0) = StartLineState iNextState(BetweenWordState, FoundOther, 0) = InWordState Rem Define the state actions iNextState(StartLineState, FoundWhiteSpace, 1) = ActionDeleteChr iNextState(StartLineState, FoundNewLine, 1) = ActionIgnoreChr iNextState(StartLineState, FoundOther, 1) = ActionIgnoreChr iNextState(InWordState, FoundWhiteSpace, 1) = ActionDeleteChr iNextState(InWordState, FoundNewLine, 1) = ActionIgnoreChr

66

iNextState(InWordState, FoundOther, 1)

= ActionIgnoreChr

iNextState(BetweenWordState, FoundWhiteSpace, 1)= ActionDeleteChr iNextState(BetweenWordState, FoundNewLine, 1) = ActionIgnoreChr iNextState(BetweenWordState, FoundOther, 1) = ActionInsertTab 'There may be multiple selections present! oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() oText=ThisComponent.Text For iWhichSelection = 0 To lSelCount - 1 oSelection = oSelections.getByIndex(iWhichSelection) oCursor=oText.createTextCursorByRange(oSelection) s = oSelection.getString() oCursor.setString("") lLastCR = -1 lLastNL = -1 lIndex = 1 iCurrentState = StartLineState Do While lIndex <= Len(s) Select Case Asc(Mid(s, lIndex, 1)) Case 9, 32, 160 iWhatFound = FoundWhiteSpace Case 10 iWhatFound = FoundNewLine lLastNL = lIndex Case 13 iWhatFound = FoundNewLine lLastCR = lIndex Case Else iWhatFound = FoundOther End Select Select Case iNextState(iCurrentState, iWhatFound, 1) Case ActionDeleteChr 'By choosing to not insert, it is deleted! Case ActionIgnoreChr 'This really means that I must add the character Back! If lLastCR = lIndex Then 'Inserting a control character seems to move the 'cursor around oText.insertControlCharacter(oCursor,_ com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) ' oText.insertControlCharacter(oCursor,_ ' com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH, False) 'oCursor.goRight(1, False) 'Print "Inserted a CR" ElseIf lLastNL = lIndex Then If lLastCR + 1 <> lIndex Then oText.insertControlCharacter(oCursor,_ com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) 'com.sun.star.text.ControlCharacter.LINE_BREAK, False) 'oCursor.goRight(1, False) 'Print "Inserted a NL" End If 'Ignore this one

67

Else oCursor.setString(Mid(s, lIndex, 1)) oCursor.GoRight(1, False) 'Print "Inserted Something" End If Case ActionInsertTab oCursor.setString(Chr$(9) + Mid(s, lIndex, 1)) oCursor.GoRight(2, False) 'Print "Inserted a tab" End Select lIndex = lIndex + 1 'MsgBox "index = " + lIndex + Chr(13) + s iCurrentState = iNextState(iCurrentState, iWhatFound, 0) Loop Next End Sub

Sub ConvertAllTabsToSpace DIM oCursor As Object, oText As Object Dim nSpace%, nTab%, nPar%, nRet%, nTot% Dim justStarting As Boolean oText=ThisComponent.Text 'Get the Text component oCursor=oText.createTextCursor() 'Create a cursor in the text oCursor.gotoStart(FALSE) 'Goto the start but do NOT select the text as you go Do While oCursor.GoRight(1, True) 'Move right one chracter and select it If Asc(oCursor.getString()) = 9 Then oCursor.setString(" ") 'Change a tab into 4 spaces End If oCursor.goRight(0,FALSE) 'Deselect text! Loop End Sub Sub ConvertSelectedTabsToSpaces Dim lSelCount&, oSelections As Object Dim iWhichSelection As Integer, lIndex As Long Dim s$, bSomethingChanged As Boolean 'There may be multiple selections present! 'There will probably be one more than expected because 'it will count the current cursor location as one piece 'of selected text, just so you know! oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() 'Print "total selected = " + lSelCount For iWhichSelection = 0 To lSelCount - 1 bSomethingChanged = False s = oSelections.getByIndex(iWhichSelection).getString() 'Print "Text group " + iWhichSelection + " is of length " + Len(s) lIndex = 1 Do While lIndex < Len(s) 'Print "ascii at " + lIndex + " = " + Asc(Mid(s, lIndex, 1)) If Asc(Mid(s, lIndex, 1)) = 9 Then s = ReplaceInString(s, lIndex, 1, " ")

68

bSomethingChanged = True lIndex = lIndex + 3 End If lIndex = lIndex + 1 'Print ":" + lIndex + "(" + s + ")" Loop If bSomethingChanged Then oSelections.getByIndex(iWhichSelection).setString(s) End If Next End Sub Function ReplaceInString(s$, index&, num&, replaces$) As String If index <= 1 Then 'Place this in front of the string 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 End Function

6.5 Ponindo atributos de texto


Cuando esta macro es ejecutada, afecta los prrafos que contiene el cursor. La fuente y tamao son puestos. El atributo de posicin de caracteres controla itlicas, peso del caracter controla negritas, el control de subrayado, controla el tipo de subrayado. Encuentre los valores vlidos en: http://api.openoffice.org/common/ref/com/sun/star/style/CharacterProperties.html http://api.openoffice.org/common/ref/com/sun/star/awt/FontWeight.html http://api.openoffice.org/common/ref/com/sun/star/awt/FontSlant.html http://api.openoffice.org/common/ref/com/sun/star/awt/FontUnderline.html
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org Sub SetTextAttributes Dim document As Object Dim Cursor Dim oText As Object Dim mySelection As Object Dim Font As String document=ThisComponent oText = document.Text Cursor = document.currentcontroller.getViewCursor()

69

mySelection = oText.createTextCursorByRange(Cursor.getStart()) mySelection.gotoStartOfParagraph(false) mySelection.gotoEndOfParagraph(true) mySelection.CharFontName="Courier New" mySelection.Charheight="10" 'Time to set Italic or NOT italic as the case with 'NONE, OBLIQUE, ITALIC, DONTKNOW, REVERSE_OBLIQUE, REVERSE_ITALIC mySelection.CharPosture = com.sun.star.awt.FontSlant.ITALIC 'So you want BOLD text? 'DONTKNOW, THIN, ULTRALIGHT, LIGHT, SEMILIGHT, 'NORMAL, SEMIBOLD, BOLD, ULTRABOLD, BLACK 'These are really only constants where THIN is 50, NORMAL is 100 ' BOLD is 150, and BLACK is 200. mySelection.CharWeight = com.sun.star.awt.FontWeight.BOLD 'If underlining is your thing 'NONE, SINGLE, DOUBLE, DOTTED, DONTKNOW, DASH, LONGDASH, 'DASHDOT, DASHDOTDOT, SMALLWAVE, WAVE, DOUBLEWAVE, BOLD, 'BOLDDOTTED, BOLDDASH, BOLDLONGDASH, BOLDDASHDOT, 'BOLDDASHDOTDOT, BOLDWAVE mySelection.CharUnderline = com.sun.star.awt.FontUnderline.SINGLE 'I have not experimented with this enough to know what the true 'implications of this really is, but I do know that it seems to set 'the character locale to German. Dim aLanguage As New com.sun.star.lang.Locale aLanguage.Country = "de" aLanguage.Language = "de" mySelection.CharLocale = aLanguage

6.6 End Sub Insertar texto


'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org Sub InsertSimpleText Dim oDocument As Object Dim oText As Object Dim oViewCursor As Object Dim oTextCursor As Object oDocument = ThisComponent oText = oDocument.Text oViewCursor = oDocument.CurrentController.getViewCursor() oTextCursor = oText.createTextCursorByRange(oViewCursor.getStart()) ' Place the text to insert here oText.insertString(oTextCursor, "", FALSE) End Sub

70

6.7 Insertar fecha formateada dentro de un documento de texto


Esto insertar el texto Today is <fecha> donde la fecha es formateada como DD. MMM AAAA. Esto crear el formato de fecha si no existe. Para ms informacin sobre formatos vlidos, vea el contenido de la ayuda en el tpico formato de nmero; formatos.
'****************************************************************** 'Author: Andrew Pitonyak 'email: andrew@pitonyak.org 'uses: FindCreateNumberFormatStyle Sub InsertDateField Dim oDocument As Object Dim oText As Object Dim oViewCursor As Object Dim oTextCursor As Object Dim oDateTime As Object oDocument = ThisComponent If oDocument.SupportsService("com.sun.star.text.TextDocument") Then oText = oDocument.Text oViewCursor = oDocument.CurrentController.getViewCursor() oTextCursor = oText.createTextCursorByRange(oViewCursor.getStart()) oText.insertString(oTextCursor, "Today is ", FALSE) ' Create the DateTime type. ODateTime = oDocument.createInstance("com.sun.star.text.TextField.DateTime") oDateTime.IsFixed = TRUE oDateTime.NumberFormat = FindCreateNumberFormatStyle(_ "DD. MMMM YYYY", oDocument) oText.insertTextContent(oTextCursor,oDateTime,FALSE) oText.insertString(oTextCursor," ",FALSE) Else MsgBox "Sorry, this macro requires a TextDocument" End If End Sub

6.8 Insertar una nueva pgina 6.8.1 La solucin


En mi investigacin sobre cmo insertar una pgina nueva en un documento, tropec con el siguiente vnculo: http://api.openoffice.org/common/ref/com/sun/star/style/ParagraphProperties.html el cual menciona dos propiedades. El estado PageNumberOffset: Si una propiedad de salto de pgina es puesta en un prrafo, esta propiedad contiene el nuevo valor para el nmero de pgina. El estado de la propiedad PageDescName: Si esta propiedad es activada, crear un salto de pgina despus del prrafo al que pertenece y asigna el valor del nombre del estilo que la nueva pgina usa. Razon que si activo PageDescName, entonces puedo crear una nueva pgina y ponerle un nmero de pgina. Lo que no se dijo es que PageDescName es el 71

nombre del nuevo estilo de pgina que se usa despus del salto de pgina. Si no usa un estilo de pgina existente, entonces fallar!
Sub ExampleNewPage Dim oSelections As Object, oSel As Object, oText As Object Dim lSelCount As Long, lWhichSelection As Long Dim oLCursor As Object, oRCursor As Object oText = ThisComponent.Text oSelections = ThisComponent.getCurrentSelection() lSelCount = oSelections.getCount() For lWhichSelection = 0 To lSelCount - 1 oSel = oSelections.getByIndex(lWhichSelection) oLCursor = oText.CreateTextCursorByRange(oSel) oLCursor.gotoStartOfParagraph(false) oLCursor.gotoEndOfParagraph(true) Rem Preserve the existing page style! oLCursor.PageDescName = oLCursor.PageStyleName oLCursor.PageNumberOffset = 7 Next End Sub

72

7 Ejemplo de inversin
Estuve llevando mis inversiones, bien modestas, en una hoja de clculo por algn tiempo. Pero decid que es tiempo de cambiar.

7.1 Pgina resumen


Tengo un resumen con un rengln para cada inversin. Mi pensamiento inicial fue que deseaba la siguiente informacin: Columna Dueo NASDAQ Descripcin A quien pertenece esta cuenta? A mi, a mi esposa, etc. Deseo automatizar la determinacin del valor actual. Para hacer esto, requiero del smbolo NASDAQ symbol. Escribir una macro para hacer esto. Cundo fue la ltima vez que actualic automticamente el valor. Valor actual en el NASDAQ. Nmero de acciones que tengo. Esto es tomado de la hoja de detalles. El valor actual de la inversin. Este es el precio*acciones Mis valores actuales que uso incluyen Capital Comercial, Fondos, y Banco. Actualmente tengo valores como Capital medio para dar un poco ms de informacin acerca de la inversin. Cuando hice esta columna, estaba pensando en cosas como Roth, IRA, inversin, 401K, cheques, etc. Fecha en que abr la cuenta. El nombre que identifica la cuenta. Normalmente le pongo el nombre usado por la institucin a que pertenece, algo como Largo plazo, excenta de impuesto. Ese es el nombre de la compaa a que pertenece, algo como Vanguard, Thrivent, o T. Rowe Price. Mi nmero de cuenta Que podr ser el dueo de la cuenta en caso de que el dueo muera.

Fecha Valor Acciones Vala Tipo Sub Tipo Que Apertura Nombre

Compaa Cuenta Beneficiario

Nombre de la hoja El nombre de la hoja que contiene los detalles de la cuenta.

7.2 Hoja de detalles


Asumo que si cada hoja de detalle se ve igual, esto har que sea fcil realizar operaciones automticas en la hoja. No s mucho de inversiones o finanzas por eso no prometo cuan tiles son mis elecciones. Yo decid las siguientes columnas:

73

Columna Vala Acciones $ agreg # agregu # Igualaciones # Divididas # Honorarios Precio/Accin Fecha $ Gastado

Descripcin Valor actual de la inversin. Esto es Precio * Acciones Nmero de acciones que tengo. Cunto gast en esta transaccin. Acciones compradas por mi contribucin. Acciones compradas por un programa de igualaciones como un 401K match. Acciones agregadas como dividendos. Acciones removidas por honorarios de algn orden. Monto pagado por cada accin. Fecha de la transaccin. Monto acumulado que gast en esta inversin.

Rdito o producto Cuando abro una cuenta bancaria, normalmente est asociada un una tasa de inters. Busco como determinar cmo se ha comportado mi cuenta para poder calcular el promedio de rditos o productos. Comentario Agrego comentarios como $2.50 por honorarios de mantenimiento

7.3 Chequear duplicados en una columna


Para prevenir dos inversiones usando el mismo nombre de hoja, necesito una macro para buscar en la columna nombre de la hoja para prevenir entradas duplicadas. Unos pocos utilitarios de macros se requerien para hacer esto.
'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

7.3.1 Direccin imprimible de una celda


Problemas de seguimiento son mejor reportados en un formato diario sencillo. Internamente, las columnas son numeradas de 0 a 255. Las columnas son reportadas desde 'A' a 'IV'. Por efectos matemticos, el problema es convertir de la base 10 a la base 26, donde 0 significa A 74

y 25 significa Z.
' Columns are numbered 0 to 255, and shows from 'A' to 'IV' ' How do you convert Base 10 numbers to Base 26? Function ColumnNumberToString(the_column As Long) As String Dim s$ Do s$ = Chr(65 + the_column MOD 26) + s$ 'If I don't use Int, then it seems to round 'the result rather than truncating. the_column = Int(the_column / 26) Loop Until the_column = 0 ColumnNumberToString = s$ End Function

Para imprimir la direccin completa de una celda, un poquito ms de trabajo se requiere. El nombre de la hoja se obtiene fcil. El nombre de la columna es descrito abajo. Las filas son representadas internamente iniciando en 0 y externamente iniciando en 1.
'Return a normal looking cell address as 'Sheetname'.ColumnRow. 'Rows start at 0 but are displayed as 1 Function PrintableCellAddress(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

7.3.2 Conteo de entradas no vacas en una columna


'oSheet Spreadsheet containing the column 'lCol Column to check 'l_min Ignore rows before this 'l_max Ignore columns after this 'Return the number of non-blank cells in the column 'I used the variant type in the parameter to avoid a bug in version 1.0.2 'That fails to properly detect Optional parameters with non-variant types. Function NonBlankCellsInColumn (oSheet As Object, lCol&, _ Optional l_min As Variant, Optional l_max As Variant) As Long Dim oCells As Object, oCell As Object, oColumn As Object Dim oAddr As Object, oRanges As Object Dim n&, lMin&, lMax& n=0 lMin = 0 lMax = 2147483647 If Not IsMissing(l_min) Then lMin = l_min If Not IsMissing(l_max) Then lMax = l_max oColumn = oSheet.Columns(lCol)

75

oRanges = ThisComponent.createInstance("com.sun.star.sheet.SheetCellRanges") oRanges.insertByName("", oColumn) oCells = oRanges.Cells.createEnumeration Do While oCells.hasMoreElements oCell = oCells.nextElement oAddr = oCell.CellAddress If oAddr.Row > lMax Then Exit Do If oAddr.Row >= lMin And Len(oCell.String) > 0 Then n=n+1 Loop NonBlankCellsInColumn = n End Function

7.3.3 Arreglo ordenado


No estoy muy convencido de su eficiencia, porque el nmero de elementos en mis arreglos es pequeo. Por eso, us el ordenamiento de burbuja modificado.
'sArray holds the sorted array 'oSheet Spreadsheet containing the column 'lCol Column to check 'l_min Ignore rows before this 'l_max Ignore columns after this Sub BuildSortedArray (sArray() As String, oSheet As Object, lCol&, _ Optional l_min As Variant, Optional l_max As Variant) Dim oCells As Object, oCell As Object, oColumn As Object Dim oAddr As Object, oRanges As Object Dim n&, i&, j&, lMin&, lMax& n = NonBlankCellsInColumn (oSheet, lCol&,l_min,l_max) If n = 0 Then ReDim sArray() As String Else ReDim sArray(n-1) As String lMin = 0 lMax = 2147483647 If Not IsMissing(l_min) Then lMin = l_min If Not IsMissing(l_max) Then lMax = l_max oColumn = oSheet.Columns(lCol) oRanges = ThisComponent.createInstance("com.sun.star.sheet.SheetCellRanges") oRanges.insertByName("", oColumn) oCells = oRanges.Cells.createEnumeration i=0 Do While oCells.hasMoreElements oCell = oCells.nextElement oAddr = oCell.CellAddress If oAddr.Row > lMax Then Exit Do If oAddr.Row >= lMin And Len(oCell.String) > 0 Then sArray(i) = oCell.String

76

i=i+1 End If Loop Dim bSomethingChanged As Boolean Dim sTemp$ For i = LBound(sArray()) To UBound(sArray()) - 2 bSomethingChanged = False For j = n-1 To i+1 Step -1 If sArray(j) < sArray(j-1) Then sTemp$ = sArray(j) sArray(j) = sArray(j-1) sArray(j-1) = sTemp$ bSomethingChanged = True End If Next If Not bSomethingChanged Then Exit For Next End If End Sub

7.3.4 Encontrar el duplicado


Con un arreglo ordenado, es fcil encontrar una entrada duplicada! Busco la primera y regreso el valor.
Function FirstDuplicate(sArray() As String) As String Dim i& FirstDuplicate = "" For i = LBound(sArray()) To UBound(sArray()) - 1 If sArray(i) = sArray(i+1) Then FirstDuplicate = sArray(i) Exit For End If Next End Function

77

8 Lenguaje
8.1 Comentarios
Es siempre una buena prctica comentar libremente su cdigo. Lo que es claro hoy, puede no serlo maana. La comilla sencilla y REM, ambos indican que un comentario va a iniciar. Todo el texto posteriosr ser ignorado.
REM This is a comment REM And this is another comment ' And yet another comment ' I could do this all day long Dim i As IntegerRem i is used as in index variable in loops Print i REM This will print the value of i

8.2 Variables 8.2.1 Nombres


Los nombres de variables estn limitados a 255 caracteres, pueden iniciar con cualquier caracter del alfabeto estndar y pueden contener nmeros. El underscore (subrayado) y los espacios tambin son carcteres vlidos. No hay distincin entre maysculas y minsculas. Los nombres de variables con espacios deben estar encerrados entre parntesis cuadrados [].

8.2.2 Declaracin
Es considerado una buena prctica declarar las variables antes de usarlas. La instruccin Option Explicit fuerza a hacer esto. Esta lnea debe existir en su cdigo antes de cualquier otra. Si no usa Option Explicit, entonces es posible que un nombre de variable mal escrito regrese para asustarlo con errores. Para declarar variables use Dim. La sintaxis de Dim es la siguiente: [ReDim]Dim Nombre1 [(inicio To final)] [As Tipo][, Nombre2 [(inicio To final)] [As Tipo] [,...]] Esto permite declarar un nmero de variables al mismo tiempo. Nombre es cualquier variable o arreglo variable. Las valores inicio and final pueden estar dentro del rango -32768 a 32767. Esto define un nmero de elementos (inclusive) mientras Nombre1(inicio) y Nombre1(final) sean valores vlidos. Si se usa ReDim, entonces los valores inicio y final pueden ser expresiones numricas. Los valores vlidos para tipo incluyen Bool, Currency, Date, Double, Integer, Long, Object, Single, String, y Variant. Las varibles Object4 pueden ser seguidas por un set subsecuente. Uso esto cuando necesito un objeto que retorne valores. El tipo por defecto es Single si tipo no es especificado. A menos que se usen los comandos DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, o DefVar. Estos comandos le permiten especificar el tipo de datos basados en la primera letra del nombre de una variable.
4 Estas variables se usan para definir objetos, como hojas de clculo, cursores, etc. Como en VBA.

79

Los objetos de cadena estn limitados a 64000 carateres. Los objetos Variant pueden contener todos los tipos y se determinan por definicin.

Advertencia El tipo de variable debe ser declarado individualmente para cada


Sub MultipleDeclaration Dim a, b As Integer Dim c As Long, d As String Dim e As Variant, f As Float Print TypeName(a) Rem Empty, Variant by default Print TypeName(b) Rem Integer, Declared Integer Print TypeName(c) Rem Long, Declared Long Print TypeName(d) Rem String, Declared String Print TypeName(e) Rem Empty, Variant as declared Print TypeName(f) Rem Object, Float is unknown type Print TypeName(g) Rem Object, because NOT declared End Sub

variable, o por defecto ser de tipo variant. Dim a, b As Integer declara a como tipo Variant y b como tipo Integer (entero).

8.2.3 Variables globales malas y estticas


Las variables globales usualmente no se usan porque pueden ser modificadas por cualquier rutina y en cualquier momento donde sea, y es dificil saber cuales mtodos modifican cuales variables que est usando. Por eso inicie ponindo el modificador malas despus de Variables Globales mientras enseaba en Ohio State University. Lo us como una herramienta para recordar a mis estudiantes que hay un tiempo y un lugar para las variables globales, y que debe pensar antes de usarlas. Una global puede ser declarada fuera de un procedimiento. Puede usar las palabras claves Public5 y Private para especificar si esta variable es global para todos los mdulos o solamente para este. Si no se especifica Public o Private explicitamente, se asume Private. La sintaxis es la misma que las instrucciones Dim y ReDim. Aunque las variables son pasadas por referencia, a menos que se indique lo contrario, las variables globales aparentemente son pasadas por valor. Esto ha causado ms de un error en mi cdigo. Cada vez que un procedimiento es llamado, las variables locales en el procedimiento son vueltas a crear. Si usted declara una variable Static6, esta retendr su valor. En el ejemplo de abajo, la subrutina Worker cuenta el nmero de veces que ha sido llamada. Recuerde que las variables numricas son iniciadas en cero y las cadenas son iniciadas con una cadena vaca.
Option Explicit Public Author As String REM Global to ALL Modules

5 N.T: Esta palabra clave define una variable pblica. Esta sera la palabra clave que el autor recomienda no usar. 6 N.T: Esta palabra clave declara una variable esttica. Este tipo de variable se mantiene durante todo el tiempo de ejecucin. No se destruye despus de salir de la funcin o subrutina, sin embargo no es global.

80

Private PrivateOne$ Dim PrivateTwo$ Sub PublicPrivateTest Author = "Andrew Pitonyak" PrivateOne = "Hello" Worker() Worker() End Sub

REM Global to THIS Module only REM Global to THIS Module only

Sub Worker() Static Counter As Long REM retains its value between calls Counter = Counter + 1 REM count each time Worker is called Print "Counter = " + Counter Print "Author = " + Author End Sub

8.2.4 Tipos
Abstractamente hablando, OpenOffice.org Basic soporta los tipos numricos, cadenas, booleanos, y objectos variables. Los objetos son usados principalmente usados para referirse a los internos como documentos, tablas, etc. Con un objeto, puede usar sus correspondientes mtodos y propiedades. Los tipos numricos son inicializados en cero y las cadenas con una cadena vaca . Si necesita saber el tipo de una variable en tiempo de ejecucin, la funcin TypeName regresa una representacin de cadena del tipo de variable. Si necesita saber un tipo de variable en tiempo de ejecucin, la funcin VarType regresa un entero que corresponde al tipo de variable. Palabra Clave Boolean Currency Date Double Integer Long Object Single String Variant Booleano Moneda con cuatro decimales Fecha Doble con punto flotante Entero Largo Objeto Sencillo con punto flotante Cadena Puede contener todos los tipos especificados en la definicin 81 Tipo de variable No. tipo variable 11 6 7 5 2 3 9 4 8 12 ! $ DefVar # % & @ DefDate DefDbl DefInt DefLng DefObj Auto Tipo Defxxx DefBool

Palabra Clave Empty Null

Tipo de variable Variable no inicializada No tiene valores vlidos

No. tipo variable 0 1

Auto Tipo

Defxxx

Sub ExampleTypes Dim b As Boolean Dim c As Currency Dim t As Date Dim d As Double Dim i As Integer Dim l As Long Dim o As Object Dim f As Single Dim s As String Dim v As Variant Dim n As Variant Dim x As Variant n = null x=f Print TypeName(b) + " " + VarType(b) Rem Boolean 11 Print TypeName(c) + " " + VarType(c) Rem Currency 6 Print TypeName(t) + " " + VarType(t) Rem Date 7 Print TypeName(d) + " " + VarType(d) Rem Double 5 Print TypeName(i) + " " + VarType(i) Rem Integer 2 Print TypeName(l) + " " + VarType(l) Rem Long 3 Print TypeName(o) + " " + VarType(o) Rem Object 9 Print TypeName(f) + " " + VarType(f) Rem Single 4 Print TypeName(s) + " " + VarType(s) Rem String 8 Print TypeName(v) + " " + VarType(v) Rem Empty 0 Print TypeName(n) + " " + VarType(n) Rem Null 1 Print TypeName(x) + " " + VarType(x) Rem Single 4 End Sub

Variables Booleanas

Las variables booleanas usan los valores Verdadero o Falso, y son internamente representadas por los valores enteros -1 y 0 respectivamente. Si asigna cualquier cosa a una variable booleana, y no puede ser precisamente evaluada como -1, entonces el valor Falso es guardado en la variable. Normalmente se usa de la siguiente manera:
Dim b as Boolean b = True b = False b = (5 = 3) 'Set to False Print b 'Prints 0 b = (5 < 7) 'Set to True Print b 'Prints -1 b=7 'Sets to False

82

Variables enteras

Las variables enteras son nmeros de 16-bits dentro de un rango de -32768 a 32767. Asignar un valor desde un nmero de punto flotante causa que se trunquen los decimales. Poniendo despus del nombre de la variable un caracter % causa que se defina como entero.
Dim Age% Dim Dogs As Integer

Variables Entero largo

Las variables de entero largo son nmeros de 32-bits en un rango de -2,147,483,648 a 2,147,483,647. Asignar un valor desde un nmero de punto flotante causa que se trunquen los decimales. Poniendo despus del nombre de la variable un caracter & causa que se defina como entero largo.
Dim Age& Dim Dogs As Long

Variables de moneda

Las variables de moneda son nmeros de 64-bits con cuatro decimales y cincuenta nmeros no decimales. Su rango va desde -922,337,203,658,477.5808 a +922,337,203, 658,477.5807. Ponindo despus del nombre de la variable un caracter @ causa que se defina como moneda.
Dim Income@ Dim Cost As Currency

Variables de Sencillos

Las variables de Sencillos son nmeros de 32-bits. El nmero ms grande es 3.402823 x 10E38. El nmero ms pequeo es 1.401298 x 10E-45. Poniendo despus del nombre de la variable un caracter ! causa que se defina como de Sencillo.
Dim Weight! Dim Height As Single

Variables de Dobles

Las variables de Dobles Double son nmeros de 64-bits. El valor ms grande para una variable de dobles es 1.79769313486232 x 10E308. El nmero ms pequeo para una variable de Dobles es 4.94065645841247 x 10E-324. Poniendo despus del nombre de la variable un caracter # causa que se defina como de Doble.
Dim Weight# Dim Height As Double

Variables de Cadena

Variables de Cadena usan un byte ASCII para cada caracter y estn limitados a un tamao de 64Kbytes. Poniendo despus del nombre de la variable el caracter $ causa que se defina 83

como de Cadena.
Dim FirstName$ Dim LastName As String

8.2.5 Constantes
OpenOffice.org Basic tambin conoce los valores Verdadero, Falso, y PI. Puede tambin definir sus propias constantes. Cada constante debe ser definida una vez, y slo una vez. Las constantes no se les define un tipo, simplemente se insertan como son digitadas.
Const Gravity = 9.81

8.2.6 Areglos o matrices.


Una matriz permite guardar diferentes valores en una sola variable. Por defecto, el primer item de la matriz est en la direccin 0. Usted puede, sin embargo, especificar los valores iniciales y finales. Aqui hay algunos ejemplos.
Dim a(5) As Integer REM 6 elements from 0 to 5 inclusive Dim b$(5 to 10) As String REM 6 elements from 5 to 10 inclusive Dim c(-5 to 5) As String REM 11 elements from -5 to 5 inclusive Dim d(5 To 10, 20 To 25) As Long

Option Base

Usted puede cambiar el valor inicial de una matriz entre 1 y cero. Esto debe ser hecho antes de cualquier instruccin en el programa. Sintaxis: Option Base { 0 | 1 }
LBound(NombreMatriz[,Dimensin])

Regresa el item ms bajo de un arreglo. El segundo parmetro es opcional, y es la dimensin de la matriz de la cual desea el item ms bajo basado en 1 (no en cero).
LBound(a()) LBound(b()) LBound(c()) LBound(d()) LBound(d(), 1) LBound(d(), 2) REM 0 REM 5 REM -5 REM 5 REM 5 REM 20

UBound(NombreMatriz[,Dimensin])

Regresa el item ms alto de un arreglo. El segundo parmetro es opcional, y es la dimensin de la matriz de la cual desea el item ms alto basado en 1 (no en cero).
LBound(a()) LBound(b()) LBound(c()) LBound(d()) LBound(d(), 1) REM 5 REM 10 REM 5 REM 10 REM 10

84

LBound(d(), 2) REM 25

Est esta matriz definida

Si una matriz es una lista vaca, entonces el item ms bajo ser ms grande que el item ms alto.
Listas de matrices y ReDim

Una matriz de items variables es regresada con el uso del constructor Array. Este es el mtodo ms fcil de regresar una lista de valores.
Dim a() a = Array(0, 1, 2)

Para crear una matriz de dimensiones vacas, use el constructor DimArray. DimArray( 2, 2, 4 ) es lo mismo que DIM a( 2, 2, 4 ). Puede cambiar el tamao de una matriz en tiempo de ejecucin si lo desea.
Dim e() As Integer REM I did not specify the size ReDim e(5) As Integer REM 0 to 5 is valid ReDim e(10) As Integer REM 0 to 10 is valid

La palabra clave Preserve puede ser usada con la instruccin ReDim para preservar el contenido de la matriz cuando es redimensionada.
Sub ReDimExample Dim a(5) As Integer Dim b() Dim c() As Integer a(0) = 0 a(1) = 1 a(2) = 2 a(3) = 3 a(4) = 4 a(5) = 5 Rem a is dimensioned from 0 to 5 where a(i) = i PrintArray("a at start", a()) Rem a is dimensioned from 1 to 3 where a(i) = i ReDim Preserve a(1 To 3) As Integer PrintArray("a after ReDim", a()) Rem Array() returns a variant type Rem b is dimensioned from 0 to 9 where b(i) = i-1 b = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) PrintArray("b at initial assignment", b()) Rem b is dimensioned from 1 to 3 where b(i) = i-1 ReDim Preserve b(1 To 3) PrintArray("b after ReDim", b()) Rem The following is NOT valid because the array is already dimensioned Rem to a different size Rem a = Array(0, 1, 2, 3, 4, 5) Rem c is dimensioned from 0 to 5 where a(i) = i

85

Rem If a "ReDim" had been done on c, then this would NOT work c = Array(0, 1, 2, 3, 4, 5) PrintArray("c, of type Integer after assignment", c()) Rem Ironically, this allowed but c will contain no data! ReDim Preserve c(1 To 3) As Integer PrintArray("c after ReDim", c()) End Sub Sub PrintArray (lead$, a() As Variant) Dim i%, s$ s$ = lead$ + Chr(13) + LBound(a()) + " to " + UBound(a()) + ":" + Chr(13) For i% = LBound(a()) To UBound(a()) s$ = s$ + a(i%) + " " Next MsgBox s$ End Sub

8.2.7 Probando objetos.


Para determinar el tipo de variable, puede usar las funciones booleanas IsArray, IsDate, IsEmpty, IsMissing, IsNull, IsNumeric, IsObject, y IsUnoStruct. La funcin IsArray retorna un valor verdadero si el parmetro es una matriz. La funcin IsDate retorna un verdadero si es posible convertir el objeto en una fecha. Una cadena con un formato apropiado podr retornar un valor verdadero desde la funcin IsDate. El mtodo IsEmpty se usa para probar si un objeto del tipo variante ha sido inicializado. La funcin IsMissing indica si un parmetro opcional est perdido. El mtodo IsNull prueba cuando una variable del tipo variante contiene el valor especial Null, indicndo que la variable no contiene datos. IsNumeric es usado para probar si una cadena contiene nmeros. La funcin IsUnoStruct toma una cadena del nombre de una estructura uno y retorna verdadero o falso si est es un nombre vlido.

8.2.8 Condicionales
Los condicionales generalmente trabajan como se esperan pero no hacen evaluaciones de cortos circuitos. Estos son los condicionales ms comnmente usados Smbolo = < > <= >= <> Is Igual Menor que Mayor que Menor o igual que Mayor o igual que No igual a Son el mismo Objeto 86 Significado

El operador And realiza operaciones lgicas en tipos boleanos y operaciones sobre bits en tipos numricos. El operador OR realiza operaciones lgicas en tipos boleanos y operaciones sobre bits en tipos numricos. El operador XOR realiza operaciones lgicas en tipos boleanos y operaciones sobre bits en tipos numricos. Recuerde que es un Exclusive OR7. El operador NOT realiza operaciones lgicas en tipos boleanos y operaciones sobre bits en tipos numricos. Una simple prueba muestra la precedencia standar que existe entre los roles, es decir que AND tiene ms precedencia que los operadores OR.
Option Explicit Sub ConditionTest Dim msg As String msg = "AND has " msg = msg & IIf(False OR True AND False, "equal", "greater") msg = msg & " precedence than OR" & Chr(13) & "OR does " msg = msg + IIF(True XOR True OR True, "", "not ") msg = msg + "have greater precedence than XOR" + Chr(13) msg = msg & "XOR does " msg = msg + IIF(True OR True XOR True, "", "not ") msg = msg + "have greater precedence than OR" MsgBox msg End Sub

8.3 Funciones y SubProcedimientos


Una funcin es un procedimiento Sub que puede retornar un valor. Esto permite que sea usado como parte de una expresin. Sub y Function inician como sigue: Sintaxis: Sintaxis: Function NombreFuncin [(Var1 [As Tipo][, Var2 [As Tipo][,...]]]) [As Tipo] Sub NombreSub[(Var1 [As Tipo][, Var2 [As Tipo][,...]]])

Las funciones declaran un valor de retorno porque ellas devuelven un valor. Para asignar el valor de retorno, use una instruccin de la siguiente forma NombreFuncin = valor_de_retorno. Aunque puede realizar la asignacin de esta instruccin muchas veces, solamente el ltimo valor asignado ser devuelto. Para dejar inmediatamente el procedimiento use una instruccin Exit.

8.3.1 Parametros opcionales.


Un parmetro puede ser declarado opcional usando la palabra clave Optional. El mtodo IsMissing es usado para determinar si un parmetro ha sido pasado.
Sub testOptionalParameters() Print TestOpt() Rem MMM Print TestOpt(,) Rem MMM Print TestOpt(,,) Rem MMM Print TestOpt(1) Rem 1MM Print TestOpt(1,) Rem 1MM

7 N.T. O exclusivo.

87

Print TestOpt(1,,) Rem 1MM Print TestOpt(1,2) Rem 12M Print TestOpt(1,2,) Rem 12M Print TestOpt(1,2,3) Rem 123 Print TestOpt(1,,3) Rem 1M3 Print TestOpt(,2,3) Rem M23 Print TestOpt(,,3) Rem MM3 Print TestOptI() Rem MMM Print TestOptI(,) Rem 488MM (Error) Print TestOptI(,,) Rem 488488M (Error) Print TestOptI(1) Rem 1MM Print TestOptI(1,) Rem 1MM Print TestOptI(1,,) Rem 1488M (Error) Print TestOptI(1,2) Rem 12M Print TestOptI(1,2,) Rem 12M Print TestOptI(1,2,3)Rem 123 Print TestOptI(1,,3) Rem 14883 (Error) Print TestOptI(,2,3) Rem 48823 (Error) Print TestOptI(,,3) Rem 4884883 (Error) End Sub Function TestOpt(Optional v1 As Variant, Optional v2 As Variant, Optional v3 As Variant) As String Dim s As String s = "" & IIF(IsMissing(v1), "M", Str(v1)) s = s & IIF(IsMissing(v2), "M", Str(v2)) s = s & IIF(IsMissing(v3), "M", Str(v3)) TestOpt = s End Function Function TestOptI(Optional i1 As Integer, Optional i2 As Integer, Optional i3 As Integer) As String Dim s As String s = "" & IIF(IsMissing(i1), "M", Str(i1)) s = s & IIF(IsMissing(i2), "M", Str(i2)) s = s & IIF(IsMissing(i3), "M", Str(i3)) TestOptI = s End Function

Advertencia En la versin 1.0.3.1, IsMissing fallar con Optional si el tipo no es

Variant y el parmetro opcional perdido est representado por dos comas consecutivas. Primero investigu este comportamiento despus de hablar con Christian Anderson [ca@ofs.no]. Esto es un issue 11678 en las issuezillas.

8.3.2 Parmetros por referencia o valor.


Si una variable es pasada por valor, puedo cambiar el parmetro en el procedimiento llamado y el valor original no cambiar. En cambio si es pasado por referencia, si cambio el parmetro tambin cambio el valor original. El comportamiento por defecto es pasar por referencia. Para pasar por valor, use la palabra clave ByVal antes de la declaracin de los parmetros. Si el parmetro es una constante como 4 y lo modifica en el procedimiento este podr o no realmente cambiarse. De acuerdo con Andreas Bregas (ab@openoffice.org) 88

esto es un error por eso abr un issue en issuezilla (http://www.openoffice.org/project/www/issues/show_bug.cgi?id=12272).


Option Explicit Sub LoopForever Dim l As Long l=4 LoopWorker(l) Print "Passed l by value and it is still " + l LoopForeverWorker(l) ' l is now 1 so this will print 1. Print "Passed l by reference and it now is " + l ' This will loop forever because 4 is a constant ' and you can NOT change it. Print "Passing a constant parameter by reference, this will be fun" Print LoopForeverWorker(4) End Sub Sub LoopWorker(ByVal n As Long) Do While n > 1 Print n n=n-1 Loop End Sub Sub LoopForeverWorker(n As Long) Do While n > 1 ' This is fun when n is a constant. Print n n=n-1 Loop End Sub

8.3.3 Recursividad
Sus funciones no pueden ser recursivas. Cuando digo no pueden, realmente quiero decir que no puede porque no obtendr los resultados que espera.
Option Explicit Sub DoFact Print "Recursive = " + RecursiveFactorial(4) Print "Normal Factorial = " + Factorial(4) End Sub Function Factorial(n As Long) As Long Dim answer As Long Dim i As Long i=n answer = 1 Do While i > 1 answer = answer * i

89

i=i-1 Loop Factorial = answer End Function ' This will fail because you can not use recursion Function RecursiveFactorial(n As Long) As Long If n > 2 Then RecursiveFactorial = n * RecursiveFactorial(n-1) Else RecursiveFactorial = 1 End If End Function

8.4 Control de flujo 8.4.1 If ... Then ... Else


El constructor If es usado para ejecutar un bloque de cdigo basado en una expresin. Mientras puede usar GoTo o GoSub para saltar fuera de un bloque If, no podr saltar dentro de un bloque If. Sintaxis: If condicin Then Bloque [ElseIf condicin Then] Bloque [Else] Bloque End If
If x < 0 Then MsgBox "The number is negative" ElseIf x > 0 Then MsgBox "The number is positive" Else MsgBox "The number is zero" End If

8.4.2 IIF
El constructor IIF es usada para devolver una expresin basados en una condicin. Es similar a la sintaxis de ? en C8. Sintaxis: IIf (Condicin, Expresin_si_verdadero, Expresin_si_falso) Es muy similar al siguiente cdigo.
If (Condition) Then object = TrueExpression Else object = FalseExpression End If max_age = IIf(johns_age > bills_age, johns_age, bills_age)

8 N.T. En Visual Fox tambin existe esta misma funcin son una sintaxis igual.

90

8.4.3 Choose
La instruccin choose permite seleccionar desde una lista de valores basados en un ndice. Sintaxis: Choose (ndice, Seleccin1[, Seleccin2, ... [,Seleccin_n]])

Si el ndice es 1, entonces el primer item es regresado. Si el ndice es 2, entonces el segundo item es retornado. Se podr imaginar el resto!

8.4.4 For....Next
Esto repetir un bloque de instrucciones un nmero especfico de veces. Sintaxis:
For contador=inicio To final [Step paso] bloque de instrucciones [Exit For] bloque de instrucciones Next [contador]

El numrico contador es inicialmente asignado al valor inicio. El valor de paso no es dado, entonces el contador es incrementado en uno hasta que pase el valor final. El bloque de instrucciones es ejecutado una vez por cada incremento. El contador es opcional en la instruccin Next, Y automticamente se refiere a la ms reciente instruccin For. Puede dejar prematuramente una instruccin For al usar la instruccin Exit For. Esto har que salga de la instruccin For ms reciente. Ejemplo: El siguiente ejemplo usa dos ciclos anidados para ordenar un arreglo de cadena con diez elementos ( sEntry() ), el cual es primero llenado con varios contenidos:
Sub ForNextExampleSort Dim iEntry(10) As Integer Dim iCount As Integer, iCount2 As Integer, iTemp As Integer Dim bSomethingChanged As Boolean ' Fill the array with the integers between -10 and 10 For iCount = LBound(iEntry()) To Ubound(iEntry()) iEntry(iCount) = Int((20 * Rnd) -10) Next iCount ' Sort the array For iCount = LBound(iEntry()) To Ubound(iEntry()) 'Assume that the array is sorted bSomethingChanged = False For iCount2 = iCount + 1 To Ubound(iEntry()) If iEntry(iCount) > iEntry(iCount2) Then iTemp = iEntry(iCount)

91

iEntry(iCount) = iEntry(iCount2) iEntry(iCount2) = iTemp bSomethingChanged = True End If Next iCount2 'If the array is already sorted then stop looping! If Not bSomethingChanged Then Exit For Next iCount For iCount = 1 To 10 Print iEntry(iCount) Next iCount End Sub

8.4.5 Do ... Loop


El constructor Loop tiene algunas diferentes formas y es usado para continuar ejecutando un bloque de cdigo mientras una condicin sea verdadera. La forma ms comn verifica la condicin antes de que inicie el ciclo y hasta que la condicin sea verdadera ejecutar repetidamente el bloque de cdigo. Si la condicin es falsa, entonces el ciclo nunca ser ejecutado.
Do While condition Block Loop

Una forma similar, pero menos comn verifica la condicin antes que el ciclo inicie y mientras la condicin sea falsa ejecutar repetidamente el bloque de cdigo. Si la condicin se evalue en verdadero inmediatamente, entonces el cilco nunca se ejecutar.
Do Until condition Block Loop

Puede tambin poner la verificacin al final del ciclo en cuyo caso el bloque de cdigo se ejecutar al menos una vez. Para siempre ejecutar el ciclo al menos una vez y luego continuar si la condicin es verdadera, use la siguiente construccin:
Do Block Loop While condition

Para ejecutar el ciclo al menos una vez y luego continuar mientras la condicin sea falsa, use la siguiente construccin:
Do Block Loop Until condition

En un Do Loop, puede forzar a salir inmediatamente del ciclo con la instruccin Exit Do.

8.4.6 Select ... Case


La instruccin Select Case es similar al case y switch de otros lenguajes. Esto imita 92

multiples bloques de Else If en una instruccin If. Una sola expresin de condicin es especificada y comparada contra mltiples valores para verificar como sigue:
Select Case expresin_de_condicin Case caso_expresin1 Bloque_de_instrucciones1 Case caso_expresin2 Bloque_de_instrucciones1 Case Else Bloque_de_instrucciones1 End Select

La expresin_de_condicin es la expresin que ser comparada en cada instruccin Case. No extoy enterado acerca de algn tipo de limitacin de tipos de datos ms que los que sea compatible con los tipos de expresin. El primer bloque de instrucciones en cumplir la condicin ser ejecutado. Si ninguna condicin se cumple, entonces el opcional Case Else se ejecutar.

8.4.7 Expresiones Case


Una expresin case es usualmente una constante de cdigo como Case 4 o Case "Case hello". Mltiples valores pueden ser epecificados al separarlos con comas: Case 3, 5, 7. Si desea verificar un rango de valores, hay una palabra clave To Case 5 To 10. Rangos sin valor inicial pueden ser verificados como Case < 10 o con la palabra clave Is Case Is < 10. La ayuda en lnea incluye un ejemplo que tiene un error. Muestra como verificar un rango de nmeros como Case i > 2 And i < 10. Lo que realmente evala es i > 2 AND i < 10, lo cual es boleano, y entonces lo compara con el parmetro seleccionado (presuntamente i en este ejemplo). Es como decir que i <> (i>2 AND i<10) La forma correcta de hacer esto es algo como IIf(i% > 2 And i% < 10, %i, %i+1).
Select Case i% 'Correct method because it returns %i when it is true 'and %i = %i. It returns %i+1 when it is false and '%i+1 <> %i Case IIf(i% > 2 And i% < 10, %i, %i+1) 'WRONG because %i <> (i% > 2 And i% < 10) Case i% > 2 And i% < 10 'Even better yet because these are integers Case 2 To 10

Todava se puede ver natural escribir algo como Case Is > 2 AND i < 10, y lo que realmente quiere decir es Case Is > (2 AND i < 10) lo cual definitivamente no es lo que se desea.
Sub DemoSelectCase Dim i% i% = Int((15 * Rnd) -2) Select Case i% Case 1 To 5 Print "Number from 1 to 5"

93

Case 6, 7, 8 Print "Number from 6 to 8" Case IIf(i% > 8 And i% < 11, %i, %i+1) Print "Greater than 8" Case Else Print "Out of range 1 to 10" End Select End Sub

8.4.8 While...Wend
No hay nada de especial en el constructor While...Wend, tiene la siguiente forma:
While Condition Cdigo Wend

Tip

Este constructor tiene limitaciones que no existen en el constructor Do While...Loop y no ofrece beneficios particulares. No puede usar el constructor Exit, o puede salir con un GoTo.

8.4.9 GoSub
La instruccin GoSub causa que la ejecucin salte a una etiqueta de subrutina definida en la actual subrutina. No puede saltar fuera de la actual subrutina. Cuando se encuentra la instruccin Return, la ejecucin continuar desde le punto de donde fue originalmente llamada. Si una instruccin Return es encontrada y no se hizo un previo GoSub, ocurre un error. En otras palabras, Return no es un substituto de un Exit Sub o Exit Function. Es generalmente aceptado que el uso de funciones y subrutinas produce un cdigo ms inteligible que el que el uso de GoSub y GoTo.
Option Explicit Sub GoSubExample Dim i As Integer GoSub Line2 GoSub Line1 MsgBox "i = " + i, 0, "GoSub Example" Exit Sub Line1: i=i+1 Return Line2: i=1 Return End Sub

Tip

GoSub y Return son remanentes persistentes de dialectos viejos de BASIC, retenidos solamente por razones de compatibilidad. Su uso no es recomendable porque tiende a producir cdigo ilegible. Subs o Functions son preferibles.

94

8.4.10 GoTo
La instruccin GoTo causa que la ejecucin salte a una etiqueta definida en la actual subrutina. No puede saltar fuera de la actual subrutina. La instruccin GoTo es generalmente considerada que produce cdigo pobremente escrito porque hace ms dificil seguir la lgica9. No recomiendo su uso en general.
Option Explicit Sub GoToExample Dim i As Integer GoTo Line2 Line1: i=i+1 GoTo TheEnd Line2: i=1 GoTo Line1 TheEnd: MsgBox "i = " + i, 0, "GoTo Example" End Sub

8.4.11 On GoTo
Sintaxis: On N GoSub Etiqueta1[, Etiqueta2[, Etiqueta3[,...]]] Sintaxis: On N GoTo Etiqueta1[, Etiqueta2[, Etiqueta3[,...]]] Esto causa que la ejecucin se bifurque a una etiqueta basados en una expresin numrica N. If (N=0) then no ocurre bifurcacin. La expresin numrica N debe estar dentro del rango de 0 y 255. Esto es similar a las instrucciones computed goto, case, y switch, de otros lenguajes. No trate de saltar fuera de la actual subrutina o funcin.
Option Explicit Sub OnGoToExample Dim i As Integer Dim s As String i=1 On i+1 GoSub Sub1, Sub2 s = s & Chr(13) On i GoTo Line1, Line2 REM The exit causes us to exit if we do not continue execution Exit Sub Sub1: s = s & "In Sub 1" : Return Sub2: s = s & "In Sub 2" : Return Line1: s = s & "At Label 1" : GoTo TheEnd Line2:

9 N.T. Se sobreentiende que la lgica del cdigo.

95

s = s & "At Label 2" TheEnd: MsgBox s, 0, "On GoTo Example" End Sub

8.4.12 Exit
La instruccin Exit es usada para salir de un Do Loop, For Next, Function, o un Sub. Tratar de salir (exit) desde alguna parte del cdigo no causar error. Las fomas son las siguientes: Exit DO Continua la instruccin siguiente al Loop. Exit For Continua la instruccin siguiente al Next. Exit Function Inmediatamente saldr de la funcin actual. Exit Sub Inmediatamente saldr de la subrutina actual.
Option Explicit Sub ExitExample Dim a%(100) Dim i% REM Fill the array with 100, 99, 98, ..., 0 For i = LBound(a()) To UBound(a()) a(i) = 100 - i Next i Print SearchIntegerArray(a(), 0 ) Print SearchIntegerArray(a(), 10 ) Print SearchIntegerArray(a(), 100) Print SearchIntegerArray(a(), 200) End Sub Function SearchIntegerArray( list(), num%) As Integer Dim i As Integer SearchIntegerArray = -1 For i = LBound(list) To UBound(list) If list(i) = num Then SearchIntegerArray = i Exit For End If Next i End Function

8.4.13Manejo de errores
Para atrapar los errores en las macros, use la instruccin On Error. On [Local] {Error GoTo Etiqueta | GoTo 0 | Resume Next} La foma On Error GoTo Label, causa que la macro salte a la etiqueta especificada si ocurre un error. Si la forma On Error Resume Next est activada y ocurre un error, la ejecucin continua en la lnea siguiente a la que caus el error. Considero que es una instruccin ignore el error. La instruccin On Error est deshabilitada por medio de el uso de la forma On Error GoTo 0. 96

Una instruccin que inicie con On Error es vlida para el mdulo entero. Si se usa Local, entonces esto define que el manejo de errores es local al contenido de la subrutina o funcin. Si no se usa Local el manejo de errores afecta el mdulo entero.

8.5 Miscelneos
Esta seccin contiene pequeeces y piezas que yo solo s porque las he visto en ejemplos pero no he encontrado ejemplos para aplicar. ********* Muchas instrucciones pueden existir en la misma lnea si estn separadas por dos puntos : . ********* Para una lnea sencilla de instrucciones, la construccin If Then no requiere que se cierre con End If.
Sub SimpleIf If 4 = 4 Then Print "4 = 4" : Print " Hello you"Rem This prints If 3 = 2 Then Print "3 = 2" Rem This does not End Sub

********* Librerias, dialogos, IDE, importar y exportar macros. With objeto ... End With ********* Cmo iniciarlo desde la lnea de comandos? El parmetro para llamar macros se lee as: soffice.exe macro:/Librera mdulo macro Ejemplo: soffice.exe macro:///standard.module1.macro1 Pero note! Si la macro no hace o no abre nada dentro del documento, la macro se implementa y cierra StarOffice de nuevo. ********* Copiar un objeto simplemente copiar la referencia. Copiar una estructura har una nueva copia. Ver EqualUnoObjects para un ejemplo. ********* Los nombres con espacios pueden ser un problema. Puede manejarse de dos maneras
Sub ExampleShell Shell("file:///C|/Andy/My%20Documents/oo/tmp/h.bat",2) Shell("C:\Andy\My%20Documents\oo\tmp\h.bat",2) End Sub

97

****** Poner el fondo de pgina


Sub Main ' First get the Style Families oStyleFamilies= ThisComponent.getStyleFamilies() ' then get the PageStyles oPageStyles= oStyleFamilies.getByName("PageStyles") ' then get YOUR page's style oMyPageStyle= oPageStyles.getByName("Standard") ' then set your background with oMyPageStyle .BackGraphicUrl= _ convertToUrl( <pathToYourGraphic> ) .BackGraphicLocation= _ com.sun.star.style.GraphicLocation.AREA end with End Sub

******* Todo el cdigo para Events est mostrado en la ayuda. ****** La forma usual de cerrar OOo completamente es llamar el mtodo terminate() en el objeto desktop. Esto se ejecutar si no hay abierta una ventana de documentos o una ventana no cerrable y no est registrado el visor de terminacin que objeta contra las llamadas a teminaciones (tal y como lo hace el quickstarter). La interface "XCloseable" se refiere a cerrar documentos sencillos o marcos, y slo trabaja en OOo 1.1, no en Ooo1.0, por eso deber preguntar esto si desea escribir cdigo que corra en OOo1.0 y OOo1.1 (Como se describe en la gua del desarrollador). Buena suerte, Mathias Bauer *******

98

9 Operadores y precedencia
OpenOffice.org Basic soporta los operadores numricos bsicos. -, +, /, *, y ^. Los operadores usan el orden de precedencia standard, pero de todos modos los indicaremos aqui. Los operadores lgicos devuelven 0 para falso (ningn bit activado) y -1 para verdadero (todos los bits activados). Para una descripcin completa, vea la seccin que lista los operadores y funciones. Precedence 0 0 0 0 1 1 1 1 1 1 2 2 2 3 3 3 4 5
Sub TestPrecedence Dim i% Print 1 + 2 OR 1 Print 1 + (2 OR 1) Print 1 + 2 AND 1 Print 1 + 2 * 3 Print 1 + 2 * 3 ^2 Print 1 = 2 OR 4 Print 4 AND 1 = 1 End Sub

Operator AND OR XOR EQV = < > <= >= <> + & * / MOD ^

Description Opera bits en numricos y boleanos lgicos Opera bits en numricos y boleanos lgicos Opera bits en numricos y boleanos lgicos Equvalencia lgica o en bits Lgico Lgico Lgico Lgico Lgico Lgico Resta numrica Suma numrica y concatenacin de caracteres. Concatenacin de caracteres Multiplicacin numrica Divisin numrica Residuo numrico despus de la divisin Exponenciacin numrica

Is (operator) ??No verificado, ver Select Case

REM Prints 3 REM Prints 4 REM Prints 1 REM Prints 7 REM Prints 19 REM Prints 4 REM Prints 4

99

Advertencia Los valores boleanos son guardados internamente como enteros donde

falso = 0 y verdadero = -1. Esto permite usar operaciones numricas con los valores boleanos pero cuidado esto (1 + Verdadero = Falso). Mejor use operadores boleanos.

100

10 Operadores, Instrucciones y Funciones.


10.1 Operador Resumen: Resta dos valores numricos. La precedencia matemtica se explica en la pgina 99. Sintaxis: Resultado = Expresin1 - Expresin2 Parmetros: Resultado : Resultado de la resta. Expresin1, Expresin2 : Cualquier expresin numrica. Ejemplo:
Sub SubtractionExample Print 4 3 Print 1.23e2 23 End Sub '1 '100

10.2 Operador *
Sumario: Multiplica dos valores numricos. La precedencia matemtica se explica en la pgina 99. Sintaxis: Resultado = Expresin1 * Expresin2 Parmetros: Resultado: Resultado de la multiplicacin. Expresin1, Expresin2 : Cualquier expresin numrica. Ejemplo:
Sub MultiplictionExample Print 4 * 3 Print 1.23e2 * 23 End Sub '12 '2829

10.3 Operador +
Sumario: Suma dos valores numricos. Sin embargo trabaja con valores boleanos porque son representados como enteros pero no recomiendo su uso. Experimentalmente, imita el resultado del operador OR pero no recomiendo su uso, porque la conversin puede tener algunos problemas. Las operaciones son hechas en el dominio de los enteros y vueltos a convertir a boleanos. Esto puede acarrear problemas. La precedencia matemtica se explica en la pgina 99. Sintaxis: Resultado = Expresin1 + Expresin2 101

Parmetros: Resultado: Resultado de la suma Expresin1, Expresin2 : Cualquier expresin numrica. Ejemplo:
Sub SubtractionExample Print 4 3 Print 1.23e2 23 End Sub '1 '100

10.4 Operador ^
Sumario: Eleva un numro a una potencia. En la equacin x = y z representa el operador. Si z es un entero, entonces x es el resultado de multiplicar y por el mismo z veces. La precedencia matemtica se explica en la pgina 99. Sintaxis: Resultado = Expresin ^ Exponente Parmetros: Resultado : Resultado de la exponenciacin Expresin: Cualquier expresin numrica Exponent: Cualquier expresin numrica Ejemplo:
Sub ExponentiationExample Print 2 ^ 3 '8 Print 2.2 ^ 2 '4.84 Print 4 ^ 0.5 '2 End Sub

10.5 Operador /
Sumario: Divide dos valores numricos. Tenga cuidado porque una divisin puede que no produzca un entero cuando usted est esperando uno. Es importante el uso de la funcin Int(). La precedencia matemtica se explica en la pgina 99. Sintaxis: Resultado = Expresin1 / Expresin2 Paramtros: Resultado : Resultado de la divisin Expresin1, Expresin2 : Cualquier expresin numrica Ejemplo:
Sub DivisionExample

102

Print 4 /2 Print 11/2 End Sub

'2 '5.5

10.6 Operador AND


Sumario: Realiza AND lgicos en valores boleanos y operacin de bits AND en valores numricos. Una operacin de bits AND en un nmero doble, aparentemente causa una conversin en un tipo entero. Es posible un desbordamiento numrico. La precedencia matemtica se explica en la pgina 99 y la tabla de operaciones es mostrada abajo. x y x AND y VERDAD VERDAD VERDAD ERO ERO ERO VERDAD ERO FALSO FALSO 1 1 0 0 FALSO VERDAD ERO FALSO 1 0 1 0 FALSO FALSO FALSO 1 0 0 0

Sintaxis: Resultado = Expresin1 AND Expresin2 Parmetros: Resultado: Resultado de la operacin. Expresin1, Expresin2 : expresiones numricas o boleanas Ejemplo:
Sub AndExample Print (3 And 1) 'Prints 1 Print (True And True) 'Prints -1 Print (True And False) 'Prints 0 End Sub

10.7 Funcin Abs


Sumario: Retorna el valor absoluto de una expresin numrica. Si el parmetro es una cadena, primero 103

es convertida a nmero, probablemente usando la funcin Val. Si el nmero no es negativo, entonces, es retornado, en otro caso, el negativo del nmero es retornado. Sintaxis: Abs (Nmero) Valor de retorno: Doble Parmetro: Nmero: Cualquier expresin numrica. Ejemplo:
Sub AbsExample Print Abs(3) '3 Print Abs(-4) Print Abs("-123") End Sub '4 '123

10.8 Funcin Array


Sumario: Crea una matriz de una lista de parmetros. Es el mtodo ms rpido para crear una matriz de constantes.

Advertencia Si asigna el valor de una matriz Variant a una matriz no-Variant, no

podr preservar los datos si redimensiona el arreglo. Lo considero un error que pueda asignar matrices Variantes a matrices no-Variantes.

Ver tambin la funcin DimArray. Sintaxis: Array ( lista de argumentos) Valor de retorno: Arreglo Variant conteniendo la lista de argumentos. Parmetros: Lista de argumentos: Lista de valores separados por comas desde las cuales es creada la lista. Ejemplo:
Sub ArrayExample Dim a(5) As Integer Dim b() As Variant Dim c() As Integer Rem Array() returns a variant type Rem b is dimensioned from 0 to 9 where b(i) = i-1 b = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) PrintArray("b at initial assignment", b()) Rem b is dimensioned from 1 to 3 where b(i) = i-1 ReDim Preserve b(1 To 3)

104

PrintArray("b after ReDim", b()) Rem The following is NOT valid because the array is already dimensioned Rem to a different size, but you can ReDim it, go figure! Rem a = Array(0, 1, 2, 3, 4, 5) Rem c is dimensioned from 0 to 5. Rem This concerns me because "Hello" is a String value, but Rem it is allowed as of 1.0.2 c = Array(0, 1, 2, "Hello", 4, 5) PrintArray("c, Variant assigned to an Integer array", c()) Rem Ironically, this allowed but c will contain no data! ReDim Preserve c(1 To 3) As Integer PrintArray("c after ReDim", c()) End Sub Sub PrintArray (lead$, a() As Variant) Dim i%, s$ s$ = lead$ + Chr(13) + LBound(a()) + " to " + UBound(a()) + ":" + Chr(13) For i% = LBound(a()) To UBound(a()) s$ = s$ + a(i%) + " " Next Rem I MsgBox rather than Print because I have an embeded Chr(13) MsgBox s$ End Sub

10.9 Funcin Asc


Sumario: Retorna el valor ASCII (American Standard Code for Information Interchange) del primer caracter de la cadena, el resto es ignorado. Un error en tiempo de ejecucin es reportado si la cadena tiene un tamao de cero. Caracteres 16 bit unicode son permitidos. Esta es esencialmente inversa a la funcin Chr$. Sintaxis: Asc (Texto como cadena) Valor de retorno: entero Parmetro: Texto: Cualquier expresin caracter vlida. Ejemplo:
Sub AscExample Print Asc("ABC") End Sub '65

10.10 Funcin ATN


Sumario: 105

Devuelve el Arcotangente de una expresin numrica dentro del rango -?/2 to ?/2 (radianes). Esta es inversa a la funcin de la tangente (Tan). Para los que no saben mucho de matemtica, esta funcin es trigonomtrica. Sintaxis: ATN(nmero) Valor de retorno: Doble Parametros: Nmero: cualquier expresin numrica Ejemplo:
Sub ExampleATN Dim dLeg1 As Double, dLeg2 As Double dLeg1 = InputBox("Enter the length of the adjacent leg: ","Adjacent") dLeg2 = InputBox("Enter the length of the opposite leg: ","Opposite") MsgBox "The Angle is " + Format(ATN(dLeg2/dLeg1), "##0.0000") _ + " radians" + Chr(13) + "The Angle is " _ + Format(ATN(dLeg2/dLeg1) * 180 / Pi, "##0.0000") + " degrees" End Sub

10.11 Instruccin Beep


Sumario: Genera un beep del sistema (sonido) Sintaxis: Beep Ejemplo:
Sub ExampleBeep Beep Beep End Sub

10.12 Funcin Blue


Sumario: Los colores son representados por enteros largos. Devuelve el componente azul de un cdigo de colores especfico. Ver tambin RGB, Red, y Green. Sintaxis: Blue (Color como entero largo) Valor de retorno: Entero en el rango de 0 a 255. Parmetros:

106

Valor del color: es una expresin de entero largo que representa un color. Ejemplo:
Sub ExampleColor Dim lColor As Long lColor = RGB(255,10,128) MsgBox "The color " & lColor & " consists of:" & Chr(13) &_ "Red = " & Red(lColor) & Chr(13)&_ "Green= " & Green(lColor) & Chr(13)&_ "Blue= " & Blue(lColor) & Chr(13) , 64,"Colors" End Sub

10.13 Palabra clave ByVal


Sumario: Los parmetros de las funciones y subrutinas definidas por el usuario son pasados por referencia. Si la subrutina o la funcin modifica el parmetro, tambin es modificado en el programa que lo llam. Esto puede causar resultados extraos si el parmetro de llamada es una constante o si el que est llamando no lo est esperando. La palabra clave ByVal especifica que el parmetro debe ser pasado por valor y no por referencia. Sintaxis: Sub Nombre(ByVal Parmetro As TipoParmetro) Ejemplo:
Sub ExampleByVal Dim j As Integer j = 10 ModifyParam(j) Print j Rem 9 DoNotModifyParam(j) Print j Rem 9 End Sub Sub ModifyParam(i As Integer) i=i-1 End Sub Sub DoNotModifyParam(ByVal i As Integer) i=i-1 End Sub

10.14 Palabra clave Call


Sumario: Transfiere el control del programa a una subrutina, una funcin o un procedimiento de un DLL. La palabra Call es opcional a menos que llame un DLL en cuyo caso este debe ser definido de primero. Los parmetros pueden estar encerrados en parntesis y deben ser encerrados en parntesis si una funcin es ejecutada como una expresin. Sintaxis: 107

[Call] Nombre [Parmetros] Parmetros: Nombre: Nombre de la subrutina, funcin o DLL a llamar. Parmetros: El tipo y nmero de parmetros depende de la rutina que se est llamando. Ejemplo:
Sub ExampleCall Call CallMe "This text will be displayed" End Sub Sub CallMe(s As String) Print s End Sub

10.15 Funcin CBool


Sumario: Convierte el parmetro a boleano. Si la expresin es un nmero, 0 ser falso y cualquier otro nmero ser verdadero. Si la expresin evala una cadena, entonces true y false (sensible a maysculas) se convierten a Verdadero y Falso respectivamente. Cadenas con cualquier otro valor genera un error en tiempo de ejecucin. Esto es til para forzar a que el resultado sea boleano. Si llamo una funcin y retorna un nmero, como en InStr, puedo escribir If CBool(InStr(s1, s2)) Then en lugar de If InStr(s1, s2) <> 0 Then. Sintaxis: CBool (Expresin) Valor de retorno: Booleano Parmetros: Expresin: Numrico, Booleano, Ejemplo:
Sub ExampleCBool Print CBool(1.334e-2) Print CBool("TRUE") Print CBool(-10 + 2*5) Print CBool("John" <> "Fred") End Sub 'True 'True 'False 'True

10.16 Funcin CByte


Sumario: Convierte una expresin de cadena o numrica en el tipo Byte. Las expresiones de cadena son convertidas a nmeros y los dobles son redondeados. Si la expresin es muy larga o negativa, se genera un error. Sintaxis: 108

Cbyte(expresin) Valor de retorno: Byte Parmetros: Expresin : Una expresin de cadena o numrica. Ejemplo:
Sub ExampleCByte Print Int(CByte(133)) '133 Print Int(CByte("AB")) '0 'Print Int(CByte(-11 + 2*5)) 'Error, out of range Print Int(CByte(1.445532e2)) '145 Print CByte(64.9) 'A Print CByte(65) 'A Print Int(CByte("12")) '12 End Sub

10.17 Funcin CDate


Sumario: Convierte a fecha. Las expresiones numricas conteniendo fechas, empezando desde el 31 de diciembre de 1899 a la izquierda del decimal y la hora a la derecha del decimal. Las expresiones de cadena deben ser formateadas por las funciones convensionales de DateValue y TimeValue. En otras palabras, la el formato de la cadena depende del locale. CDateFromIso no depende de su locale y es ms seguro si desea un cdigo ms global. Sintaxis: CDate (Expresin) Valor de retorno: Date Parmetros: Expresin: Cualquier expresin numrica o de cadena a ser convertida. Ejemplo:
sub ExampleCDate MsgBox cDate(1000.25) REM 09.26.1902 06:00:00 MsgBox cDate(1001.26) REM 09.27.1902 06:14:24 Print DateValue("06/08/2002") MsgBox cDate("06/08/2002 15:12:00") end sub

10.18 Funcin CDateFromIso


Sumario: Retorna el nmero de fecha interno de una cadena conteniendo una fecha en formato ISO.

109

Sintaxis: CDateFromIso(cadena) Valor de retorno: Nmero de fecha interno. Parmetros: Cadena: Una cadena conteniendo una fecha ISO. El ao puede contener dos o cuatro dgitos. Ejemplo:
sub ExampleCDateFromIso MsgBox cDate(37415.70) Print CDateFromIso("20020608") Print CDateFromIso("020608") Print Int(CDateFromIso("20020608")) end sub Rem 08 June 2002 16:48:00 Rem 08 June 2002 Rem 08 June 1902 Rem 37415

10.19 Funcin CDateToIso


Sumario: Retorna la fecha en formato ISO de una serie de nmeros generados con DateSerial o DateValue. Sintaxis: CDateToIso(Nmero) Valor de retorno: Cadena Parmetros: Nmero: Entero que contiene la serie de nmero de fecha. Ejemplo:
Sub ExampleCDateToIso MsgBox "" & CDateToIso(Now) ,64,"ISO Date" End Sub

10.20 Funcin CDbl


Sumario: Convierte cualquier expresin numrica o de cadena en el tipo double. Las cadenas deben ser formateadas en el estilo locale. En USA, 12.34 funcionar, pero podra fallar en otros lugares. Sintaxis: CDbl (Expresin) Valor de retorno: Double

110

Parmetros: Expresin: Cualquier expresin de cadena o numrica a ser convertida. Ejemplo:


Sub ExampleCDbl Msgbox CDbl(1234.5678) Msgbox CDbl("1234.5678") End Sub

10.21 Instruccin ChDir


Sumario: Cambia el directorio actual o la unidad. Si slo quiere cambiar la unidad actual, digite la letra de la unidad, seguida de dos puntos. ?? Cmo trabajar esto en mi computadora <sigh>! ?? Cmo trabajar en Linux o en Mac. Sintaxis: ChDir Texto As String Parmetro: Texto: Cualquier expresin de cadena que especifica una ruta de directorio o unidad. Ejemplo:
Sub ExampleChDir Dim sDir as String sDir = CurDir ChDir( "C:\temp" ) msgbox CurDir ChDir( sDir ) msgbox CurDir End Sub

10.22 Instruccin ChDrive


Sumario: Cambia la unidad actual. La letra de la unidad debe ser escrita como una letra mayscula. Puede usar la instruccin OnError para capturar los errores. Esto se ve muy pequeo en mi computadora ?? Sintaxis: ChDrive Texto As String Parmetros: Texto: Expresin de cadena que contenga una letra de unidad. Se acepta notacin URL. Ejemplo:
Sub ExampleCHDrive On Local Error Goto NoDrive ChDrive "Z" REM Only possible if a drive 'Z' exists. Print "Completed"

111

Exit Sub NoDrive: Print "Sorry, the drive does not exist" Resume Next End Sub

10.23 Funcin Choose


Sumario: Retorna un valor seleccionado de una lista de argumentos. Este es un mtodo rpido para seleccionar un valor de una lista. Si el indice est fuera de los lmites (menor a 1 o mayor que n), entonces es retornado un nulo. Sintaxis: Choose (Index, Seleccin_1[, Seleccin_2, ... [,Seleccin_n]]) Valor de retorno: El tipo depender del que contenga Seleccin_i. Parmetros: Index: Una expresin numrica que especifique el valor de retorno. Selection_i: Un valor a retornar. Ejemplo: En este ejemplo, la variable o no tiene un tipo de valor dado de manera que toma el tipo de Seleccin_i. Seleccin_1 es del tipo cadena y Seleccin_2 es del tipo Double. Si define que o tenga un tipo de datos, entonces el valor de retorno ser convertido a ese tipo de datos.
Sub ExampleChoose Dim sReturn As String Dim sText As String Dim i As Integer Dim o sText = InputBox ("Enter a number (1-3):","Example") i = Int(sText) o = Choose(i, "One", 2.2, "Three") If IsNull(o) Then Print "Sorry, '" + sText + "' is not valid" Else Print "Obtained '" + o + "' of type " + TypeName(o) End If end Sub

10.24 Funcin Chr


Sumario: Retorna el caracter correspondiente al cdigo de caracter especfico (ASCII o Unicode) Esto es usado para crear secuencias especiales de cadenas, como secuencias de control para 112

impresoras, tabuladores, nuevas lneas, retornos de carro, etc. Esto tambin provee un mtodo para insertar comillas dobles dentro de una cadena. Esto es escrito como Chr$(). Ver tambin la Funcin Asc Sintaxis: Chr(Expresin As Integer) Valor de retorno: Cadena Parmetros: Expresin: Variables numricas que representan un valor ASCII de 8 bits vlido (0-255) o un valor unicode de 16 bits. Ejemplo:
Ejemplo: sub ExampleChr REM Show "Line 1" and "Line 2" on separate lines. MsgBox "Line 1" + Chr$(13) + "Line 2" End Sub

10.25 Funcin CInt


Sumario: Convierte cualquier expresion numrica o de cadena en un tipo Integer (entero). La cadena debe ser formateada en base al tipo local. En EEUU, trabajar 12.34. Ver tambin: Fix Sintaxis: CInt(Expresin) Valor de retorno: Entero (Integer) Parmetros: Expresin : Cualquier cadena o expresin numrica a ser convertida. Ejemplo:
Sub ExampleCInt Msgbox CInt(1234.5678) Msgbox CInt("1234.5678") End Sub

10.26 Funcin CLng


Sumario: Convierte cualquier expresin numrica o de cadena en un tipo Largo (Long). Las cadenas deben ser formateadas en base al tipo local. En EEUU, trabajar 12.34. Sintaxis: 113

CLong(Expresin) Valor de retorno: Entero Largo (Long) Parmetros: Expresin : Cualquier cadena o expresin numrica a ser convertida. Ejemplo:
Sub ExampleCLng Msgbox CLng(1234.5678) Msgbox CLng("1234.5678") End Sub

10.27 Instruccin Close


Sumario: Cierra archivos abiertos previamente con la instruccin Open. Multiples archivos pueden ser cerrados simultneamente. Ver tambin, EOF, Kill, y FreeFile Sintaxis: Close NumroArchivo As Integer[, NmeroArchivo2 As Integer[,...]] Parmetros:
NmeroArchivo : Expresin entera que especifica un archivo abierto anteriormente.

Ejemplo:
Sub ExampleCloseFile Dim iNum1 As Integer, iNum2 As Integer Dim sLine As String, sMsg As String 'Next available file number! iNum1 = FreeFile Open "c:\data1.txt" For Output As #iNum1 iNum2 = FreeFile Open "c:\data2.txt" For Output As #iNum2 Print #iNum1, "Text in file one for number " + iNum1 Print #iNum2, "Text in file two for number " + iNum2 Close #iNum1, #iNum2 Open "c:\data1.txt" For Input As #iNum1 iNum2 = FreeFile Open "c:\data2.txt" For Input As #iNum2 sMsg = "" Do While not EOF(iNum1) Line Input #iNum1, sLine If sLine <> "" Then sMsg = sMsg+"File: "+iNum1+":"+sLine+Chr(13) Loop Close #iNum1 Do While not EOF(iNum2) Line Input #iNum2, sLine If sLine <> "" Then sMsg = sMsg+"File: "+iNum2+":"+sLine+Chr(13)

114

Loop Close #iNum2 Msgbox sMsg End Sub

10.28 Instruccin Const


Sumario: Las Constantes mejora la lectura de los programas al asignar nombres a las contantes y tambin provee un solo punto de definicin. Las constantes pueden incluir la definicin de un tipo de datos pero no es requerido. Una constante es definida una vez y no puede ser modificada. Sintaxis: Const Texto [As tipo] = Expresin[, Texto2 [As tipo] = Expresin2[, ...]] Parmetros: Texto: Cualquier nombre de constante que siga los estndares de nombres de variables. Ejemplo:
Sub ExampleConst Const iVar As String = 1964 Const sVar = "Program", dVar As Double = 1.00 Msgbox iVar & " " & sVar & " " & dVar End Sub

10.29 Funcin ConvertFromURL


Sumario: Convierte un URL de archivo en un nombre de archivo de sistema. Sintaxis: ConvertFromURL(NombreArchivo) Valor de retorno: Cadena (String) Parmetros: NombreArchivo: Nombre del archivo como un URL Ejemplo:
Sub ExampleUrl Dim sUrl As String, sName As String sName = "c:\temp\file.txt" sUrl = ConvertToURL(sName) MsgBox "Original File:" + sName + Chr(13) + "URL: " + sURL + Chr(13) + _ "And Back:" + ConvertFromURL(sUrl) End Sub

115

10.30 Funcin ConvertToURL


Sumario: Convierte un archivo de un URL a un nombre de archivo del sistema. Sintaxis: ConvertToURL(NombreArchivo) Valor de retorno: Cadena (String) Parmetros: NombreArchivo: Nombre del archivo como un nombre del sistema. Ejemplo:
Sub ExampleUrl Dim sUrl As String, sName As String sName = "c:\temp\file.txt" sUrl = ConvertToURL(sName) MsgBox "Original File:" + sName + Chr(13) + _ "URL: " + sURL + Chr(13) + _ "And Back:" + ConvertFromURL(sUrl) End Sub

10.31 Funcin Cos


Sumario: El coseno de una expresin numrica con un valor de retorno en el rango de 1 y -1. Para las mentes no matemticas, esta es una funcin trigonomtrica. Sintaxis: Cos(Nmero) Valor de retorno: Doble (Double) Parmetros: Nmero: Ejemplo:
Sub ExampleCos Dim dLeg1 As Double, dLeg2 As Double, dHyp As Double Dim dAngle As Double dLeg1 = InputBox("Enter the length of the adjacent leg: ","Adjacent") dLeg2 = InputBox("Enter the length of the opposite leg: ","Opposite") dHyp = Sqr(dLeg1 * dLeg1 + dLeg2 * dLeg2) dAngle = Atn(dLeg2 / dLeg1) MsgBox "Adjacent Leg = " + dLeg1 + Chr(13) + _ "Opposite Leg = " + dLeg2 + Chr(13) + _ "Hypotenuse = " + Format(dHyp, "##0.0000") + Chr(13) + _ "Angle = "+Format(dAngle*180/Pi, "##0.0000")+" degrees"+Chr(13)+_

116

"Cos = " + Format(dLeg1 / dHyp, "##0.0000") + Chr(13) + _ "Cos = " + Format(Cos(dAngle), "##0.0000") End Sub

10.32 Funcin CreateUnoDialog


Sumario: Crea un objeto Basic Uno que representa un dialogo de control Uno durante el tiempo de ejecucin de Basic. Los dilogos estn definidos en las libreras de dilogos. Para desplegar un dialogo, un dilogo vivo debe ser creado en la librera. Sintaxis: CreateUnoDialog( oDlgDesc ) Valor de retorno: Objeto: Dilogo a ejecutar! Parmetros: oDlgDesc : Descripcin del dialogo previamente definido en la librera. Ejemplo: ?? Warning, I have not made this work at all! Work on this!
Sub ExampleCreateDialog Dim oDlgDesc As Object, oDlgControl As Object DialogLibraries.LoadLibrary("Standard") ' Get dialog description from the dialog library oDlgDesc = DialogLibraries.Standard Dim oNames(), i% oNames = DialogLibraries.Standard.getElementNames() i = lBound( oNames() ) while( i <= uBound( oNames() ) ) MsgBox "How about " + oNames(i) i=i+1 wend oDlgDesc = DialogLibraries.Standard.Dialog1 ' generate "live" dialog oDlgControl = CreateUnoDialog( oDlgDesc ) ' display "live" dialog oDlgControl.execute End Sub

10.33 Funcin CreateUnoService


Sumario: Instancia un servicio Uno con el ProcessServiceManager (Administrador de servicios de procesos). Sintaxis: 117

oService = CreateUnoService( Nombre del servicio Uno ) Valor de retorno: ?? Parmetros: ?? Ejemplo:
oIntrospection = CreateUnoService( "com.sun.star.beans.Introspection" )

10.34 Funcin CreateUnoStruct


Sumario: Crea una instancia de un tipo de estructura Uno. Es mejor usar el siguiente constructor.!
Dim oStruct as new com.sun.star.beans.Property

Sintaxis: oStruct = CreateUnoStruct( Nombre del tipo Uno ) Valor de retorno: Parmetros: Ejemplo:
oStruct = CreateUnoStruct("com.sun.star.beans.Property") '*********************************** '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() 'You could have done it this way after it was defined! 'mPrinter(0) = CreateUnoStruct("com.sun.star.beans.PropertyValue")

10.35 Funcin CSng


Sumario: Convierte una expresin numrica o de cadena en un tipo sencillo (Single). Las cadenas deben ser formateadas en base al tipo local. En EEUU, trabajar 12.34. Sintaxis: CSng(Expresin) Valor de retorno: Entero Sencillo (Single)

118

Parmetros: Expresin : Cualquier cadena o expresin numrica a ser convertida. Ejemplo:


Sub ExampleCLng Msgbox CSng(1234.5678) Msgbox CSng("1234.5678") End Sub

10.36 Funcin CStr


Sumario: Converte cualquier expresin en una cadena. Esto se usa para convertir un nmero en una cadena. Tipo entrada Booleano Fecha (Date) Null Vaco (Empty) Cualquier nmero Valor de salida True o False Cadena con la fecha y la hora. Error en tiempo de ejecucin. Cadena vaca El nmero como una cadena. Los ceros a la derecha del decimal son cortados.

Sintaxis: CStr (Expresin) Valor de retorno: Cadena (String) Parmetros: Expresin: Cualquier cadena vlida o expresin numrica a ser convertida. Ejemplo:
Sub ExampleCSTR Dim sVar As String Msgbox CDbl(1234.5678) Msgbox CInt(1234.5678) Msgbox CLng(1234.5678) Msgbox CSng(1234.5678) sVar = CStr(1234.5678) MsgBox sVar end sub

10.37 Funcin CurDir


Sumario:

119

retorna la cadena representando la ruta actual de la unidad especificada. Si el parmetro no es dado o de tamao cero, entonces la ruta de la unidad actual es retornado. Sintaxis: CurDir [(Texto As String)] Valor de retorno: Cadena (String) Parmetros: Texto: Cadena no sensible a maysculas especificando una unidad para retornar la ruta actual. Debe ser un solo caracter. ?? Chequear esto en linux. Ejemplo:
Sub ExampleCurDir MsgBox CurDir("c") MsgBox CurDir("p") MsgBox CurDir() end sub

10.38 Funcin Date


Sumario: Retorna o cambia el sistema actual. El formato de fecha depende del local. Sintaxis: Fecha Date = Texto As String Valor de retorno: Cadena (String) Parmetros: Texto: Nueva fecha del sistema como se define en su configuracin local. Ejemplo:
Sub ExampleDate MsgBox "The date is " & Date End Sub

10.39 Funcin DateSerial


Sumario: Convierte un ao, mes, y da en un objeto Fecha (Date). La representacin interna es un doble (Double) donde 0 es Diciembre 30,1899. Ver este doble como el nmero de das desde esta fecha base. Los nmeros negativos son antes y los positivos despus. Ver tambin DateValue, Date, y Day.

120

Advertencia Los aos de dos dgitos son consderados como 19xx. Esto no es
consistente con la funcin DateValue. Sintaxis: DateSerial (ao, mes, da) Valor de retorno: Fecha Parmetros: Ao: valor entero de ao. Valores entre 0 y 99 son representados como los aos 1900 a 1999. todos los dems aos debern contener cuatro dgitos. Mes: Entero indicando el mes. Los valores vlidos van de 1 a 12. Da: Entero indicando el da. Los valores vlidos van de 1 a 28, 29, 30 o 31 (Depende del mes). Ejemplo:
Sub ExampleDateSerial Dim lDate as Long, sDate as String, lNumDays As Long lDate = DateSerial(2002, 6, 8) sDate = DateSerial(2002, 6, 8) MsgBox lDate REM returns 37415 MsgBox sDate REM returns 06/08/2002 lDate = DateSerial(02, 6, 8) sDate = DateSerial(02, 6, 8) MsgBox lDate REM returns 890 MsgBox sDate REM returns 06/08/1902 end sub

10.40 Funcin DateValue


Sumario: Convierte una cadena de fecha en un valor nmerico que puede ser usado para determinar el nmero de das entre dos fechas. Ver tambin DateSerial, Date, y Day

Advertencia Los aos de dos dgitos son considerados 20xx. Esto no es consistente
con la funcin DateSerial. Sintaxis: DateValue [(fecha)] Valor de retorno: Largo Parmetros: Fecha: Cadena representando la fecha. Ejemplo: 121

Sub ExampleDateValue Dim s(), i%, sMsg$, l1&, l2& Rem These all map to June 8, 2002. s = Array("06.08.2002", "6.08.02", "6.08.2002", "June 08, 2002", _ "Jun 08 02", "Jun 08, 2002", "Jun 08, 02", "06/08/2002") Rem If you use these values, it will generate an error Rem which contradicts the included help Rem s = Array("6.08, 2002", "06.08, 2002", "06,08.02", "6,08.2002", "Jun/08/02") sMsg = "" For i = LBound(s()) To UBound(s()) sMsg = sMsg + DateValue(s(i)) + "<=" + s(i) + Chr(13) Next MsgBox sMsg Print "I was married " + (DateValue(Date) - DateValue("6/8/2002")) + " days ago" end sub

10.41 Funcin Day


Sumario: Retorna el da del mes basado en un nmero de serie de datos (serial date number) generado con DateSerial o DateValue. Sintaxis: Day (Nmero) Valor de retorno: Entero Parmetros: Nmero: Nmero Serial date retornado por DateSerial Ejemplo:
Sub ExampleDay Print Day(DateValue("6/8/2002") Rem 8 Print Day(DateSerial(02,06,08)) Rem 8 end sub

10.42 Instruccin Declare


Sumario: Usado para declarar y definir una subrutina en un DLL DLL (Dynamic Link Library) para ser ejecutada desde OpenOffice.org Basic. La palabra clave ByVal debe ser usada si los parmetros son pasados por valor en lugar de por referencia. Ver tambin: FreeLibrary Sintaxis: Declare {Sub | Function} Name Lib "Libname" [Alias "Aliasname"] [Parameter] [As Typ] Parameter/Element: Name: Un nombre diferente que el definido en el DLL, usado para llamar la subrutina desde 122

Basic. Aliasname: Nombre de la subrutina tal y como est definida en la DLL. Libname: Archivo o nombre de sistema de la DLL. Esta librera es automticamente cargada la primera vez que la funcin es usada. Argumentlist: Lista de parmetros representando los argumentos que son pasados al procedimiento cuando este es llamado. El tipo y nmero de parmetros depende del procedimiento que se est ejecutando. Type: Define el tipo de datos de el valor retornado por el procedimiento Funcin. Esto puede ser excluido si un caracter de tipo de declaracin es ingresado despues del nombre. Ejemplo:
Declare Sub MyMessageBeep Lib "user32.dll" Alias "MessageBeep" ( long ) Sub ExampleDeclare Dim lValue As Long lValue = 5000 MyMessageBeep( lValue ) FreeLibrary("user32.dll" ) End Sub

10.43 Instruccin DefBool


Sumario: Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con b, por ejemplo, sean automticamente del tipo boleanos. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefBool Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
REM Prefix definition for variable types: DefBool b DefDate t DefDbL d DefInt i DefLng l DefObj o DefVar v DefBool b-d,q Sub ExampleDefBool cOK = 2.003 zOK = 2.003 Print cOK Rem True

123

Print zOK End Sub

Rem 2.003

10.44 Instruccin DefDate


Summary Define el tipo de variable por defecto, de acuerdo a un rango de letras, si no es declarado el tipo mediante un caracter de definicin o una palabra clave. Permite que todas las variables que inician con una t, por ejemplo, sean automaticamente del tipo fecha. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefDate Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
ver ejemplo DefBool

10.45 Instruccin DefDbl


Sumario: Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con d, por ejemplo, sean automticamente del tipo Doble. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefDbl Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
ver ejemplo DefBool

10.46 Instruccin DefInt


Sumario: Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con i, por ejemplo, sean automticamente del tipo Entero. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: 124

DefInt Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
Ver ejemplo DefBool

10.47DefLng Statement
Sumario: Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con l, por ejemplo, sean automticamente del tipo Largo. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefLng Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
Ver ejemplo DefBool

10.48 Instruccin DefObj


Sumario: Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con o, por ejemplo, sean automticamente del tipo Objeto. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefObj Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
Ver ejemplo DefBool

10.49 Instruccin DefVar


Sumario: 125

Define el tipo por defecto de las variables, de acuerdo a un rango de letras, si no se define un caracter de tipo de declaracin o palabra clave. Puede permitir que todas las variables que inician con v, por ejemplo, sean automticamente del tipo Variante. Ver tambin: DefBool, DefDate, DefDbL, DefInt, DefLng, DefObj, y DefVar. Sintaxis: DefVar Rango1[, Rango2[,...]] Parmetros: Rango: Letras especificando el rango de variables a las que se les va a definir el tipo de datos por defecto. Ejemplo:
Ver ejemplo DefBool

10.50 Instruccin Dim


Sumario: Declara variables. El tipo de cada variable es declarado separadamente y el tipo por defecto es Variante. La siguiente instruccin define a, b, y c del tipo Variante y d del tipo Fecha.
Dim a, b, c, d As Date

Los tipos de variables tambin pueden ser definidos mediante el uso de un caracter al final. Esto es mencionado en la seccin de tipos de variables. Dim es usada para declarar variables locales dentro de las subrutinas. Las variables globales fuera de las Subrutinas son declaradas con las instrucciones PUBLIC o PRIVATE. A menos que la instruccin Option Explicit est presente, las variables que no sean matriz pueden ser usadas sin declaracin y su tipo por defecto ser variante. Son soportadas matrices sencillas y multi-dimensionales. Ver tambin: Public, Private, ReDim Sintaxis: [ReDim]Dim Nombre_1 [(inicio To fin)] [As Tipo][, Nombre_2 [(inicio To fin)] [As Tipo] [,...]] Parmetros/Palabras clave: Name_i: Nombre de la variable o de la matriz. Inicio, fin: Constante entero desde -32768 a 32767 del rango de la matriz o arreglo. A nivle de procedimiento, ReDim permite expresiones numricas de manera que puede ser reiniciado en tiempo de ejecucin. Tipo: Palabra clave usada para declarar el tipo de datos de una variable. Los tipos soportados son Boolean (Boleano), Currency (Moneda), Date (Fecha), Double (Doble), Integer (Entero), Long (Largo), Object (Objeto), Single (Sencillo), String (Cadena), o Variant (Variante). Ejemplo:
Sub ExampleDim

126

Dim s1 As String, i1 As Integer, i2% Dim a1(5) As String Rem 0 to 6 Dim a2(3, -1 To 1) As String Rem (0 to 3, -1 to 1) Const sDim as String = " Dimension:" For i1 = LBound(a2(), 1) To UBound(a2(), 1) For i2 = LBound(a2(), 2) To UBound(a2(), 2) a2(i1, i2) = Str(i1) & ":" & Str(i2) Next Next For i1 = LBound(a2(), 1) To UBound(a2(), 1) For i2 = LBound(a2(), 2) To UBound(a2(), 2) Print a2(i1, i2) Next Next End Sub

10.51 Funcin DimArray


Sumario: Crea una matriz del tipo Variante. Esto trabaja igual que Dim(Lista de argumentos). Si no hay argumentos, una matriz vaca es creada. Si hay parmetros, una dimensin es creada por cada parmetro. Ver tambin: Array Sintaxis: DimArray ( Lista de argumentos) Valor de retorno: Matriz Variant Parmetros: Lista de argumentos: De manera opcional son enteros separados por comas. Ejemplo: DimArray( 2, 2, 4 ) es lo mismo que DIM a( 2, 2, 4 )

10.52 Funcin Dir


Sumario: Retorna el nombre de un archivo, directorio, o todos los archivos y directorios de una unidad o directorio que concuerde con la ruta de busqueda especificada. Un posible uso es verificar que exista un archivo o directorio, o listar los archivos y directorios de un directorio especifico. Si no concuerda ningn archivo o directorio, se retorna una cadena de tamao cero. Llamar repetidamente la funcin Dir hasta que una cadena de tamao cero sea retornada para iterate a traves de todos los valores retornados. Los atributos de Volumen y Directorio tienen significado exclusivamente si pide uno de estos 127

y es la nica cosa que obtiene. No puedo determinar cual tiene ms precedencia, porque la versin 1.0.3, el atributo del volumen no hace nada. Los atributos son un subconjunto de estos disponibles en GetAttr. Ver tambin: GetAttr Sintaxis: Dir [(Texto As String[, Atributo As Integer])] Valor de retorno: Cadena Parmetros: Texto: Cadena que especifica la ruta de bsqueda, directorio o archivo. Notacin URL es aceptada. Atributo: Entero para los atributos de los archivos. La funcin Dir retornar solo los archivos o directorios que concuerden con los atributos especificos. Sume los atributos para combinarlos. Atributo 0 2 4 8 16 Ejemplo:
Sub ExampleDir REM Displays all files and directories Dim sFile as String, sPath As String Dim sDir as String, sValue as String Dim iFIle as Integer sFile= "Files: " sDir="Directories:" iFile = 0 sPath = CurDir Rem 0 : Normal files. Rem 2 : Hidden files. Rem 4 : System files. Rem 8 : Returns the name of the volume Rem 16 : Returns the name of the directory only. Rem This example will ONLY return directories because the 16 is included! Rem Remove the 16 and you will receive the files sValue = Dir$(sPath, 0 + 2 + 4 + 16) Do If sValue <> "." and sValue <> ".." Then

Descripcin Archivo normal. Archivo oculto. Archivo de sistema. Retorna el nombre del volumen (Exclusivo). Retorna directorios (Exclusivo).

128

If (GetAttr( sPath + getPathSeparator() + sValue) AND 16) > 0 Then REM here the directories sDir = sDir & chr(13) & sValue Else REM here the files If iFile Mod 3 = 0 Then sFile = sFile + Chr(13) iFile = iFile + 1 sFile = sFile + sValue &"; " End If End If sValue = Dir$ Loop Until sValue = "" MsgBox sDir,0,sPath MsgBox "" & iFile & " " & sFile,0,sPath End Sub

Tip

El mtodo getPathSeparator() es incluido sin embargo no aparece en la lista de ayuda. No ha encontrado aun donde est definido, pero es usado en las herramientas distribuidas y en la ayuda. refieren al directorio actual y al directorio padre respectivamente. Si escribe cdigo que barra un directorio, probablemente no desee seguirlos o caer en un ciclo infinito. aun cuando la ayuda en lnea parezca indicar que si lo hace.

Advertencia Algunos sistemas operativos incluyen los directorios . y .. que se

Advertencia Cuando obtenga una lista de directorios, los archivos no sern retornados, 10.53 Instruccin Do...Loop
Sumario: Construye una repeticin de instrucciones. Ver tambin: Control Loop Pgina 92. Sintaxis: Do [{While | Until} Condicin = True] Block de instrucciones [Exit Do] Block de instrucciones Loop Sintaxis: Do Block de instrucciones [Exit Do] Block de instrucciones

129

Loop [{While | Until} condicin = True]

10.54 Instruccin End


Sumario: Marca el final de un procedimiento o bloque. Ver tambin: Exit Sintaxis: Forma End Funcin Por s mismo termina la ejecucin del programa. Puede estar en cualquier parte. Es opcional. Marca el final de una funcin. Marca el final de un bloque If...Then...Else. Marca el final de un bloque Select Case. Marca el final de una subrutina.

End Function End If End Select End Sub Ejemplo:

Sub ExampleEnd Dim s As String s = InputBox ("Enter an integer :","White Space Checker") If IsWhiteSpace(Val(s)) Then Print "ASCII " + s + " is white space" Else Print "ASCII " + s + " is not white space" End If End Print "I will never get here" End Sub Function IsWhiteSpace(iChar As Integer) As Boolean Select Case iChar Case 9, 10, 13, 32, 160 IsWhiteSpace = True Case Else IsWhiteSpace = False End Select End Function

10.55 Funcin Environ


Sumario: Retorna el valor de una variable de ambiente. Las variables de ambiente dependen del sistema operativo. En una Macintosh esta funcin retorna una cadena vaca. Sintaxis: 130

Environ (Ambiente As String) Valor de retorno: Cadena Parmetros: Ambiente: Variable de ambiente, de la cual se quiere extraer el valor que contiene. Ejemplo:
Sub ExampleEnviron MsgBox "Path = " & Environ("PATH") End Sub

10.56 Funcin EOF


Sumario: Use EOF para evitar tratar de leer ms all del final del archivo. Cuando el final del archivo es encontrado, EOF retorna Verdadero (-1). Ver tambin Open, Close, Kill, y FreeFile Sintaxis: EOF (ValorEntero As Integer) Valor de retorno: Boleano Parmetros: ValorEntero: Expresin Entera que evala el nmero correspondiente de un archivo abierto. Ejemplo:
Rem Este ejemplo est modificado de la ayuda en lnea. Rem El ejemplo de la ayuda en lnea no funciona. Sub ExampleEof Dim iNumber As Integer Dim aFile As String Dim sMsg as String, sLine As String aFile = "c:\DeleteMe.txt" iNumber = Freefile Open aFile For Output As #iNumber Print #iNumber, "First line of text" Print #iNumber, "Another line of text" Close #iNumber iNumber = Freefile Open aFile For Input As iNumber While Not Eof(iNumber) Line Input #iNumber, sLine If sLine <>"" Then sMsg = sMsg & sLine & chr(13) End If Wend Close #iNumber

131

Msgbox sMsg End Sub

10.57 Funcin EqualUnoObjects


Sumario: Verifica si dos objetos Uno representan la misma instancia del objeto Uno. Sintaxis: EqualUnoObjects( oObj1, oObj2 ) Valor de retorno: Boleano Ejemplo:
Sub ExampleEqualUnoObjects Dim oIntrospection, oIntro2, Struct2 Rem Copy of objects -> same instance oIntrospection = CreateUnoService( "com.sun.star.beans.Introspection" ) oIntro2 = oIntrospection print EqualUnoObjects( oIntrospection, oIntro2 ) Rem Copy of structs as value -> new instance Dim Struct1 as new com.sun.star.beans.Property Struct2 = Struct1 print EqualUnoObjects( Struct1, Struct2 ) End Sub

10.58 Operador EQV


Sumario: Calcula la equivalencia lgica de doe expresiones. En una comparacin de bit-a-bit, el operador EQV activa el bit correspondiente en el resultado solamente si un bit es activado en ambas expresiones o en ninguna expresin. La precedencia matemtica usada est mostrada en la pgina 99 y la tabla de operaciones es mostrada a continuacin: x y x EQV y VERDAD VERDAD VERDAD ERO ERO ERO VERDAD ERO FALSO FALSO 1 FALSO VERDAD ERO FALSO 1 FALSO FALSO VERDAD ERO 1

132

x 1 0 0

y 0 1 0

x EQV y 0 0 1

Sintaxis: Resultado = Expresin1 EQV Expresin2 Parmetros: Resultado: Variable numrica que contiene el resultado de la comparacin. Expresin1, expresin2 : Expresiones a comparar. Ejemplo:
Sub ExampleEQV Dim vA as Variant, vB as Variant, vC as Variant, vD as Variant Dim vOut as Variant vA = 10: vB = 8: vC = 6: vD = Null vOut = vA > vB EQV vB > vC REM returns -1 Print vOut vOut = vB > vA EQV vB > vC REM returns -1 Print vOut vOut = vA > vB EQV vB > vD REM returns 0 Print vOut vOut = (vB > vD EQV vB > vA) REM returns -1 Print vOut vOut = vB EQV vA REM returns -1 End Sub

10.59 Funcin Erl


Sumario: Retorna el nmero de lnea en la que ha ocurrido un error durante el tiempo de ejecucin. Ver tambin: Err Sintaxis: Erl Valor de retorno: Entero Ejemplo:
Sub ExampleErl On Error GoTo ErrorHandler Dim iVar as Integer iVar = 0 iVar = 4 / iVar

133

Exit Sub ErrorHandler: Rem Error 11 : Division by Zero Rem In line: 8 Rem .... MsgBox "Error " & err & ": " & error$ + chr(13) + _ "In line : " + Erl + chr(13) + Now , 16 ,"An error occured" End Sub

10.60 Funcin Err


Sumario: Retorna el nmero de error del ltimo error. Ver tambin: Erl Sintaxis: Err Valor de retorno: Entero Ejemplo:
Sub ExampleErr On Error GoTo ErrorHandler Dim iVar as Integer iVar = 0 iVar = 4 / iVar Exit Sub ErrorHandler: Rem Error 11 : Division by Zero Rem In line: 8 Rem .... MsgBox "Error " & err & ": " & error$ + chr(13) + _ "In line : " + Erl + chr(13) + Now , 16 ,"An error occured" End Sub

10.61 Funcin Error


Sumario: Simula la ocurrencia de un error durante la ejecucin de un programa. Sintaxis: Error NumeroError As Integer Parmetros: NumeroError: Expresin Entera que especifica el nmero de error a ser simulado. La instruccin Error simula la ocurrencia de un error durante la ejecucin de un programa. Un error interceptado por una rutina de manejo de errores no ser reportada, a menos que sea tomada una accin correctiva o no. La instruccin Error es usada para reportar un error 134

cuando no hay rutina de manejo de errores, y detener la ejecucin del programa. Ejemplo: ?? This does NOT work! Sintaxis: Error NumeroError As Integer Valor de retorno: Entero Parmetros: Ejemplo:

10.62 Funcin Error


Sumario: Retorna el mensaje de error correspondiente a un cdigo de error dado. Sintaxis: Error (Expresin) Valor de retorno: Cadena Parmetros: Expresin: Entero opcional conteniendo el mensaje de error para un nmero de error. Si este no est presente, el mensaje de error ms reciente es regresado. Ejemplo:
Sub ExampleError On Error GoTo ErrorHandler Dim iVar as Integer iVar = 0 iVar = 4 / iVar Exit Sub ErrorHandler: Rem Error 11 : Division by Zero Rem In line: 8 Rem .... MsgBox "Error " & err & ": " & error$ + chr(13) + _ "In line : " + Erl + chr(13) + Now , 16 ,"An error occured" End Sub

10.63 Instruccin Exit


Sumario: La instruccin Exit es usada para dejar una estructura Do...Loop, For...Next, Funcin o 135

Subroutina. En otras palabras, puedo inmediatamente salir de cualquiera de estas estructuras. Si estoy dentro de una subrutina y determino que los argumentos estn mal, puedo dejar inmediatamente la subrutina. Ver tambin: End Sintaxis: Forma Exit Do Exit For Function Sale del Do...Loop ms cercano. Sale del For...Next ms cercano.

Exit Function Sale de una funcin y continua la ejecucin siguiente a la llamada a la funcin. Exit Sub Ejemplo:
Sub ExampleExit Dim sReturn As String Dim sListArray(10) as String Dim siStep as Single Rem Build array ("B", "C", ..., "L") For siStep = 0 To 10 REM Fill array with test data sListArray(siStep) = chr(siStep + 66) Next siStep sReturn = LinSearch(sListArray(), "M") Print sReturn Exit Sub Rem This really is a useless statement! End Sub REM Returns the index of the entry or (LBound(sList()) - 1) if not found Function LinSearch( sList(), sItem As String ) as integer Dim iCount As Integer REM LinSearch searches a TextArray:sList() for a TextEntry: For iCount=LBound(sList()) To UBound(sList()) If sList(iCount) = sItem Then LinSearch = iCount Exit Function Rem Probably a good use of Exit here! End If Next LinSearch = LBound(sList()) - 1 End Function

Sale de la subrutina y continua la ejecucin siguiente a la llamada a la subrutina.

10.64 Funcin Exp


Sumario: Retorna la base del logaritmo natural (e = 2.718282) elevado a una potencia. Ver tambin: Log 136

Sintaxis: Exp (Nmero) Valor de retorno: Doble Parmetros: Nmero: Cualquier expresin numrica. Ejemplo:
Sub ExampleExp Dim d as Double, e As Double e = Exp(1) Print "e = " & e Print "ln(e) = " & Log(e) Print "2*3 = " & Exp(Log(2.0) + Log(3.0)) Print "2^3 = " & Exp(Log(2.0) * 3.0) end sub

10.65 Funcin FileAttr


Sumario: El primer propsito de la funcin FileAttr es determinar el modo de acceso de un archivo abierto con la instruccin Open. Ponindo el segundo parmetro en 1, recupera este valor. Valor 1 2 4 8 32 Descricin del modo de acceso INPUT (Archivo abierto para entrada) OUTPUT (Archivo abierto para salida) RANDOM (Archvo abierto para acceso aleatorio) APPEND (Archivo abierto para aadir) BINARY (Archivo abierto en modo binario)

El segundo propsito de la funcin FileAttr es determinar el atributo de un archivo MS-DOS que ha sido abierto con la instruccin Open. Este valor depende del sistema operativo. Ponindo el segundo parametro en 2, recupera este valor.

Advertencia El atributo de archivos depende del sistema operativo. Si el sistema

operativo es una versin 32-bit, no es posible usar la funcin FileAttr para determinar al atributo del archivo MS-Dos file de manera que es regresado un cero.

Ver tambin: Open Sintaxis: FileAttr (NumeroArchivo As Integer, Atributo As Integer) 137

Valor de retorno: Entero Parmetros: NumeroArchivo: Nmero usado en la instruccin Open. Atributo: Entero indicando que informacin retornar. 1 recupera el modo de acceso y 2 recupera el nmero de acceso del archivo. Ejemplo:
Sub ExampleFileAttr Dim iNumber As Integer iNumber = Freefile Open "file:///c|/data.txt" For Output As #iNumber Print #iNumber, "Random Text" MsgBox AccessModes(FileAttr(#iNumber, 1 )),0,"Access mode" MsgBox FileAttr(#iNumber, 2 ),0,"File attribute" Close #iNumber End Sub Function AccessModes(x As Integer) As String Dim s As String s = "" If (x AND 1) <> 0 Then s = "INPUT" If (x AND 2) <> 0 Then s = "OUTPUT" If (x AND 4) <> 0 Then s = s & " RANDOM" If (x AND 8) <> 0 Then s = s & " APPEND" If (x AND 32) <> 0 Then s = s & " BINARY" AccessModes = s End Function

10.66 Instruccin FileCopy


Sumario: Copia un archivo. No puede copiar un archivo que est abierto. Sintaxis: FileCopy TextoDesde As String, TextoA As String Parmetros: TextoDesde: Cadena especificando el nombre del archivo origen. TextoA: Cadena especificando el nombre de archivo destino. Ejemplo:
Sub ExampleFilecopy Filecopy "c:\Data.txt", "c:\Temp\Data.sav" End Sub

10.67 Funcin FileDateTime


Sumario: 138

Retorna una cadena cona la fecha y hora en que un archivo ha sido creado o modificado por ltima vez, retornado en un formato que depende del sistema."MM/DD/YYYY HH:MM:SS" en mi computadora. Considere el uso de la funcin DateValue function con esta cadena. Sintaxis: FileDateTime(Texto As String) Valor de retorno: Cadena Parmetros: Texto: Especificacin del archivo (no se permiten comodines). Notacin URL es permitida. Ejemplo:
Sub ExampleFileDateTime Rem 04/23/2003 19:30:03 MsgBox FileDateTime("file://localhost/C|/macro.txt") End Sub

10.68 Funcin FileExists


Sumario: Determina si un archivo o directorio existe. Sintaxis: FileExists(NombreArchivo As String | NombreDirectorio As String) Valor de retorno: Boleano Parmetros: NombreArchivo | NombreDirectorio: Archivo o directorio especificado (No se permiten comodines). Ejemplo:
Sub ExampleFileExists MsgBox FileExists("C:\autoexec.bat") MsgBox FileExists("file://localhost/c|/macro.txt") MsgBox FileExists("file:///d|/private") End Sub

10.69 Funcin FileLen


Sumario: Determina el tamao de un archivo. Si el archivo est actualmente abierto, el tamao antes de que fue abierto ser retornado. Para determinar el largo del archivo de un archivo abierto, en su lugar use la funcin Lof. Sintaxis: FileExists(NombreArchivo As String) 139

Valor de retorno: Largo. Parmetros: NombreArchivo: Especificacin del archivo (No se permiten comodines). Ejemplo:
Sub ExampleFileExists MsgBox FileLen("C:\autoexec.bat") MsgBox FileLen("file://localhost/c|/macro.txt") End Sub

10.70 Funcin FindObject


Sumario: ?? No tengo idea10 Sintaxis: Valor de retorno: Parmetros: Ejemplo:

10.71 Funcin FindPropertyObject


Sumario: ?? No tengo idea11 Sintaxis:
10 El siguiente texto est tomado de la ayuda en lnea: Permite que los objetos sean referenciados en tiempo de ejecucin como un parmetro de cadena de caracteres por medio del nombre del objeto. Sintaxis: FindObject(NombreObjeto As String) Parmetro: NombreObjeto: Cadena que especifica el nombre del objeto que debe ser referenciado en tiempo de ejecucin. Ejemplo: Dim ObjVar as Object Dim ObjProp as Object ObjName As String = "MyObj" ObjVar = FindObject( ObjName As String ) PropName As String = "Prop1" ObjProp = FindPropertyObject( ObjVar, PropName As String ) ObjProp.Command = 5 11 La ayuda en lnea de este tpico es igual a la anterior.

140

Valor de retorno: Parmetros: Ejemplo:

10.72 Funcin Fix


Sumario: Retorna la porcin entera de una expresin numrica removiendo la fraccin. Ver tambin: CInt Sintaxis: Fix(Expresin) Valor de retorno: Doble Parmetros: Expresin: Nmero del cual se retornar la parte entera. Ejemplo:
sub ExampleFix Print Fix(3.14159) REM returns 3. Print Fix(0) REM eturns 0. Print Fix(-3.14159) REM returns -3. End Sub

10.73For...Next Statement
Sumario: Construye una repeticin de instrucciones con un contador que se autoincrementa. Ver tambin: For....Next en la pgina 91. Sintaxis: For contador=inicio To end [Step paso] block de instrucciones [Exit For] block de instrucciones Next [contador]

141

10.74 Funcin Format


Sumario: Convierte un nmero en una cadena formateada de acuerdo al formado de cadena opcional. Formatos mltiples pueden ser incluidos en una sola cadena de formato. Cada formato individual est separado por un ;. El primer formato es usado para los nmeros positivos, el segundo para los negativos y el tercero para el cero. Si slo un cdigo de formato est presente, se aplica para todos los nmeros. Cdigo 0 Descripcin Si un nmero tiene un dgito en la posicin del cero en el cdigo del formato, el dgito es desplegado; de lo contrario aparecer un cero. Esto significa que los cero al inicio y al final son despegados, los digitos al inicio no sern truncados y los decimales al final sern redondeados. Esto trabaja como el 0, pero los ceros al inicio y al final no son desplegados. El punto decimal determina el nmero de posiciones decimales a la derecha y a la izquierda del separador decimal. Multiplica el nmero por 100 e inserta el signo porcentual (%) en donde aparezca en el cdigo del formato. Si el cdigo de formato contiene al menos una posicin para digitos a la derecha del simbolo, el nmero ser formateado en notacin cientfica. La letra E o e es insertada entre el nmero y el exponente. El nmero de posiciones para los dgitos a la derecha del smbolo determina el nmero de dgitos en el exponente. Si el exponente es negativo, un signo de menos es desplegado directamente antes del exponente. Si el exponente es positivo, un signo de ms solamente ser desplegado antes con E+ o e+. La coma es un indicador para el separador de miles. Separa los miles de los cientos en un nmero de al menos cuatro dgitos. El delimitador de miles es desplegado si el formato contiene el delimitador rodeado de los indicadores de dgitos (0 o #). Ms (+), menos (-), dlar ($), espacio, o parntesis entradas directamente en el formato son desplegadas como caracteres literales.

# . %

EE+ ee+

- + $ ( ) space

142

Cdigo

Descripcin El backslash despliega el siguiente caracter en el formato del codigo. En otras palabras, previene que el siguiente caracter se lea como un caracter especial. El backslash no es desplegado, a menos que introduzca un doble backslash (\\) en el cdigo de formato. Los caracteres que pueden ser precedidos por un backslash en el cdigo de formato para que sean desplegados como caracteres literales son los caracteres de formato de fecha-hora (a, c, d, h, m, n, p, q, s, t, w, y, /, :), caracteres de formateo de nmeros (#, 0, %, E, e, coma, punto) y caracteres de formatero de cadenas (@, &, <, >, !). Puede encerrar los caracteres en comillas dobles. Los nmeros se despliegan tal y como se introducen. Un signo de dlar es colocado al frente del nmero; los nmeros negativos son encerrados en parntesis. Se despliegan dos decimales. (Actualmente, esto es especifico de la localizacin) Al menos un digito es desplegado al frente del separador decimal. Se despliegan dos decimales. Despliega los nmeros con el separador de miles especfico de la localizacin. Se despliegan dos decimales. Despliego los nmeros en notacin cientfica. Se despliegan dos decimales.

Nmeros en general Moneda Fijo Standard Cientfico

Advertencia No se hace ninguna conversin si el parmetro no es un nmero (como


cuando es una cadena) y una cadena vaca es devuelta.

Advertencia La versin 1.0.3.1, Format(123.555, .##) produce .12356 lo que

considero un problema. Cambiando el formato a #.## resuelve el problema. Use siempre un # o 0 adelante segn sea lo apropiado. La notacin cientfica actualmente est mala (quebrada) Moneda es colocando el signo de dlar a la derecha. Actualmente no es posible realizar caracteres especiales de escape.

Sintaxis: Format (Nmero [, Formato As String]) Valor de retorno: Cadena 143

Parmetros: Nmero: Expresin numrica a ser convertida a una cadena formateada. Formato: El formato deseado. Si es omitido, la funcin Format trabajar como la funcin Str. Ejemplo:
Sub ExampleFormat MsgBox Format(6328.2, "##,##0.00") REM = 6,328.20 MsgBox Format(123456789.5555, "##,##0.00") REM = 123,456,789.56 MsgBox Format(0.555, ".##") Rem .56 MsgBox Format(123.555, "#.##") Rem 123.56 MsgBox Format(0.555, "0.##") Rem 0.56 MsgBox Format(0.1255555, "%#.##") Rem %12.56 MsgBox Format(123.45678, "##E-####") Rem 12E1 MsgBox Format(.0012345678, "0.0E-####") Rem 1.2E3 (broken) MsgBox Format(123.45678, "#.e-###") Rem 1e2 MsgBox Format(.0012345678, "#.e-###") Rem 1e3 (broken) MsgBox Format(123.456789, "#.## is ###") Rem 123.45 is 679 (strange) MsgBox Format(8123.456789, "General Number")Rem 8123.456789 MsgBox Format(8123.456789, "Fixed") Rem 8123.46 MsgBox Format(8123.456789, "Currency") Rem 8,123.46$ (broken) MsgBox Format(8123.456789, "Standard") Rem 8,123.46 MsgBox Format(8123.456789, "Scientific") Rem 8.12E03 MsgBox Format(0.00123456789, "Scientific") Rem 1.23E03 (broken) End Sub

10.75 Funcin FreeFile


Sumario: Retorna el siguiente nmero de archivo disponible para abrir un archivo. Esto asegura que nunca use un nmero de archivo que est actualmente en uso. Ver tambin Open, EOF, Kill, y Close. Sintaxis: FreeFile Valor de retorno: Entero Ejemplo: Ver el ejemplo para Close.

10.76FreeLibrary Function
Sumario: Libera una DLL que ha sido cargada por una instruccin Declare. La DLL ser automaticamente recargada si una de sus funciones es llamada. Solamente las DLLs cargadas durante el tiempo de ejecucin de Basic pueden ser liberadas. Ver tambin: Declare 144

Sintaxis: FreeLibrary (NombreLib As String) Parmetros: NombreLib: Nombre de la DLL. Ejemplo:


Declare Sub MyMessageBeep Lib "user32.dll" Alias "MessageBeep" ( long ) Sub ExampleDeclare Dim lValue As Long lValue = 5000 MyMessageBeep( lValue ) FreeLibrary("user32.dll" ) End Sub

10.77 Instruccin Function


Sumario: Define una funcin definida por el usuario, en oposicin a una subrutina. Ver tambin: Sub Sintaxis: Function Nombre[(Variable1 [As Tipo][, Variable2 [As Tipo][,...]]]) [As Tipo] bloque de instrucciones [Exit Function] bloque de instrucciones End Function Valor de retorno: Cualquier tipo que haya sido declarado. Ejemplo:
Function IsWhiteSpace(iChar As Integer) As Boolean Select Case iChar Case 9, 10, 13, 32, 160 IsWhiteSpace = True Case Else IsWhiteSpace = False End Select End Function

10.78 Instruccin Get


Sumario: Lee un registro de un archivo relativo, o una secuencia de bytes de un archivo binario, dentro de una variable. Si el parmetro de posicin es omitido, los datos son leidos de la posicin actual en el archivo. Para los archivos abiertos en modo binario, la posicin es la posicin del 145

byte en el archivo. Ver tambin: PUT Sintaxis: Get [#] NmeroArchivo As Integer, [Posicin], Variable Parmetros: NmeroArchivo: expresin entera que determina el nmero de archivo. Yo uso FreeFile para obtenerlo. Posicin: Para los archivos abiertos en modo aleatorio, este es el nmero de registro a ser leido. Variable: Variable a leer. El objeto Variable puede no ser usado aqui. Ejemplo:
'?? This is broken! Sub ExampleRandomAccess2 Dim iNumber As Integer, aFile As String Dim sText As Variant REM Must be a variant aFile = "c:\data1.txt" iNumber = Freefile Open aFile For Random As #iNumber Len=5 Seek #iNumber,1 REM Position at beginning Put #iNumber,, "1234567890" REM Fill line with text Put #iNumber,, "ABCDEFGHIJ" Put #iNumber,, "abcdefghij" Rem This is how the file looks now! Rem 08 00 0A 00 31 32 33 34 35 36 37 38 39 30 08 00 ....1234567890.. Rem 0A 00 41 42 43 44 45 46 47 48 49 4A 08 00 0A 00 ..ABCDEFGHIJ.... Rem 61 62 63 64 65 66 67 68 69 6A 00 00 00 00 00 00 abcdefghij Rem Seek #iNumber,1 Get #iNumber,,sText Print "on open:" & sText Close #iNumber iNumber = Freefile Open aFile For Random As #iNumber Len=5 Get #iNumber,,sText Print "reopened: " & sText Put #iNumber,,"ZZZZZ" Get #iNumber,1,sText Print "anoter get "& sText Get #iNumber,1,sText Put #iNumber,20,"This is the text in record 20" Print Lof(#iNumber) Close #iNumber End Sub

146

10.79 Funcin GetAttr


Sumario: Retorna un mscara de bits para el tipo de archivo. Los atributos son el tipo usado en la funcin Dir. Atributo 0 1 2 4 8 16 32 Ver tambin: Dir Archivo Normal. Archivo de Slo-Lectura Archivo oculto. Archivo de sistema. Nombre del Volumen. Directorio. Bit de archivado (el archivo cambio desde el ltimo backup) Descripcin

Advertencia No sirve en 1.0.3.1. Pruebe con la versin que usted usa.


Sintaxis: GetAttr (Texto As String) Valor de retorno: Entero Parmetros: Texto: Expresin de cadena que contiene una especificacin nica de archivo. Es vlida la notacin URL. Ejemplo:
Sub ExampleGetAttr Rem Should say " Read-Only Hidden System Archive" Rem says " Read-Only" Print FileAttributeString(GetAttr("C:\IO.SYS")) Rem Should say " Archive" says "Normal" Print FileAttributeString(GetAttr("C:\AUTOEXEC.BAT")) Rem "Directory" Print FileAttributeString(GetAttr("C:\WINDOWS")) End Sub Function FileAttributeString(x As Integer) As String Dim s As String If (x = 0) Then s = "Normal" Else s = ""

147

If (x AND 16) <> 0 Then s = "Directory" If (x AND 1) <> 0 Then s = s & " Read-Only" If (x AND 2) <> 0 Then s = " Hidden" If (x AND 4) <> 0 Then s = s & " System" If (x AND 8) <> 0 Then s = s & " Volume" If (x AND 32) <> 0 Then s = s & " Archive" End If FileAttributeString = s End Function

10.80 Funcin GetProcessServiceManager


Sumario: Obtiene el administrador Uno central. Esto es requerido cuando debe iniciar un servicio usando CreateInstance con argumentos. ?? Encontrar un mejor ejemplo que este! Mostrar un ejemplo que toma un argumento! Sintaxis: oServiceManager = GetProcessServiceManager() Valor de retorno: Ejemplo:
oServiceManager = GetProcessServiceManager() oIntrospection = oServiceManager.createInstance("com.sun.star.beans.Introspection"); this is the same as the following statement: oIntrospection = CreateUnoService("com.sun.star.beans.Introspection")

10.81 Funcin GetSolarVersion


Sumario: Retorna el nmero interno de la versin actual de OpenOffice.org. Puede escribir sus macros de manera que trabajen alrededor de problemas conocidos en las diferentes versiones. Sintaxis: s = GetSolarVersion() Valor de retorno: Cadena Ejemplo:
Sub ExampleGetSolarVersion Rem as of 1.0.3.1, this is "641" Print GetSolarVersion() End Sub

148

10.82 Funcin GetSystemTicks


Sumario: Retorna los tiempos del sistema provistos por el sistema operativo. El nmero de tiempos de reloj del sistema retornados dentro de ciertos marcos de tiempo, dependen del sistema operativo. Sintaxis: GetSystemTicks() Valor de retorno: Largo Ejemplo: Este ejemplo intentar medir cuantos tiempos de reloj hay por segundo. En Windows XP y la versin 1.0.3.1 de OpenOffice.org, veo 1000 tiempos de reloj por segundo.
Sub ExampleGetSystemTicks Dim lTick As Long, lMillisToWait As Long Dim lSecsToWait As Long, lTicksPerSec As Long lSecsToWait = 60 lMillisToWait = lSecsToWait * 1000 lTick = GetSystemTicks() wait(lMillisToWait) lTick = (GetSystemTicks() - lTick) lTicksPerSec = lTick / lSecsToWait MsgBox "Each second has about " & lTicksPerSec & " Ticks Per Second" End Sub

10.83 Instruccin GlobalScope


Sumario: Los macros de y dilogos estn organizados en librerias. Una librera puede contener mdulos y/o dilogos. En Basic, el contenedor de libreras es llamado BasicLibraries y el contenedor de dialogos es llamado DialogLibraries. De esta forma ambos contenedores de libreras existen en el nivel de aplicacin y de documento, en basic estas son cargadas automticamente pero no en el doumento. Para llamar estos contenedores de libreras globales dentro de un documento, debe usar la palabra clave GlobalScope. Sintaxis: GlobalScope Ejemplo:
' calling Dialog1 in the document library Standard oDlgDesc = DialogLibraries.Standard.Dialog1 ' calling Dialog2 in the application library Library1 oDlgDesc = GlobalScope.DialogLibraries.Library1.Dialog2

149

10.84 Function
Sumario: Sintaxis: Valor de retorno: Parmetros: Ejemplo:

10.85 Function
Sumario: Sintaxis: Valor de retorno: Parmetros: Ejemplo:

10.86 Function
Sumario: Sintaxis: Valor de retorno: Parmetros: Ejemplo:

150

???????

10.87 Function
Sumario: Sintaxis: Valor de retorno: Parmetros: Ejemplo:

10.88 Funcin Green


Sumario: Los colores son representados por un entero largo. Retorna el componente verde del cdigo de colores especfico. Ver tambin RGB, Red, y Blue. Sintaxis: Green(Color As Long) Valor de retorno: Entero en el rango de 0 a 255. Parmetros: Color: Expresin de entero largo representando un color. Ejemplo:
Sub ExampleColor Dim lColor As Long lColor = RGB(255,10,128) MsgBox "The color " & lColor & " consists of:" & Chr(13) &_ "Red = " & Red(lColor) & Chr(13)&_ "Green= " & Green(lColor) & Chr(13)&_ "Blue= " & Blue(lColor) & Chr(13) , 64,"Colors" End Sub

151

10.89 Palabra clave Private


Sumario: La palabra clave Private es usado para declarar una variable fuera de una subrutina como privada. Si una variable es declarada usando la palabra clave Dim, es considerada privada. Ver tambin la descripcin para las descripciones de la sintaxis de Dim. Ver tambin: Dim, Public Sintaxis: Private Nombre_1 [(inicio To fin)] [As VarType][, Nombre_2 [(inicio To fin)] [As VarType] [,...]] Ejemplo:
Private iPriv As Integer Sub ExamplePublic iPriv = 1 Call CalledSub End Sub Sub CalledSub Print iPriv Rem 1 End Sub

10.90 Palabra clave Public


Sumario: La palabra clave Public es usada para declarar una variable fuera de una subrutina como pblica para todos los mdulos. Si una variable es declarada usando la palabra clave Dim, es considerada privada. Vea la descripcin en Dim para la sintaxis. Ver tambin: Dim, Private Sintaxis: Public Nombre_1 [(inicio To fin)] [As VarType][, Nombre_2 [(inicio To fin)] [As VarType] [,...]] Ejemplo:
Public iPub As Integer Sub ExamplePublic iPub = 1 Call CalledSub End Sub Sub CalledSub Print iPub Rem 1 End Sub

152

10.91 Funcin Red


Sumario: Los colores son representados por un entero largo. Retorna el componente rojo del cdigo de colores especfico. Ver tambin RGB, Green, y Blue. Sintaxis: Red(Color As Long) Valor de retorno: Entero en el rango de 0 a 255. Parmetros: Color: Expresin de entero largo representando un color. Ejemplo:
Sub ExampleColor Dim lColor As Long lColor = RGB(255,10,128) MsgBox "The color " & lColor & " consists of:" & Chr(13) &_ "Red = " & Red(lColor) & Chr(13)&_ "Green= " & Green(lColor) & Chr(13)&_ "Blue= " & Blue(lColor) & Chr(13) , 64,"Colors" End Sub

10.92 Notacin y nombres de archivo URL 10.92.1 Notacin URL


En una computadora con windows, c:\autoexec.bat es un tpico mtodo para referenciar un archivo. Esto tambin puede ser referenciado en notacin URL como file:///c|/autoexec.bat. Una idea general cuando realice conversiones es iniciar el URL con file:///, cambiar : por |, y reemplazar \ con /. Si desea insertar el nombre de una computadora o una direccin IP, insrtelo entre el segundo y tercer caracter / como en file://localhost/c|/autoexec.bat/.

10.92.2 Rutas con espacios y otros caracteres especiales.


Los espacios y caracteres especiales pueden ser cambiados en las URLs como notacin estandar de archivos usando la secuencia de escape standar de URL. Tome el valor ASCII que intenta cambiar, conviertalo en hex, ponga el caracter % antes, y coloquelo donde desea el caracter especial. Considere el cambio por un espacio en la ruta. c:\My% 20Documents\info.sxw y file///c|/My%20Documents/info.sxw.

153

154

11Index
/ 86p., 90, 101, 103p. Abs 106 And 87, 101, 105 Array 85p. Asc 107 ATN 108 AVERAGE 41 Beep 108 Blue 109 Bool 79 BottomLine 42 ByVal 89, 109 Call 110 case 93, 95 Case Else 93 CBool 110 Cbyte 111 CDate 111 CDateFromIso 111p. CDateToIso 112 CDbl 113 Cell CellAddress 38, 74p. CellBackColor 35 getFormula 35 getSpreadSheet 38, 74p. getString 35 getValue 35 IsCellBackgroundTransparent NumberFormat 35, 41 setFormula 35, 41 setString 35, 41 setValue 35 String 29 CellAddress Column 38, 74p. Row 38, 74p. CharacterProperties CharFontName 69 Charheight 69 CharLocale 69 CharPosture 69 FontSlant 69 CharUnderline 69

35

CharWeight 69 FontWeight 69 FontSlant DONTKNOW 69 ITALIC 69 NONE 69 OBLIQUE 69 REVERSE_ITALIC 69 REVERSE_OBLIQUE FontUnderline BOLD 69 BOLDDASH 69 BOLDDASHDOT 69 BOLDDASHDOTDOT BOLDDOTTED 69 BOLDLONGDASH 69 BOLDWAVE 69 DASH 69 DASHDOT 69 DASHDOTDOT 69 DONTKNOW 69 DOTTED 69 DOUBLE 69 DOUBLEWAVE 69 LONGDASH 69 NONE 69 SINGLE 69 SMALLWAVE 69 WAVE 69 FontWeight BLACK 69 BOLD 69 DONTKNOW 69 LIGHT 69 NORMAL 69 SEMIBOLD 69 SEMILIGHT 69 THIN 69 ULTRABOLD 69 ULTRALIGHT 69 ChDir 113 ChDrive 114 Choose 114 Chr 107, 115 Christian Anderson 88 CInt 115 155

69

69

CLong 116 Close 31, 116, 134, 147 Component CurrentController 41 CurrentSelection 41 DatabaseRanges 41 getCurrentController 43 removeByName 42 StatusIndicator 20 Text 1 computed goto 95 Config commitChanges 25 ConfigurationUpdateAccess 25 createInstanceWithArguments PickListSize 25 replaceByName 25 ConfigurationProvider 25 Const 117 Controller ActiveSheet 41 getViewCursor() 69 select 43 StatusIndicator 20 ConvertFromURL 117 ConvertToURL 118 Cos 118 CreateUnoDialog 119 CreateUnoService 25, 120 CreateUnoStruct 120 CSng 121 CStr 121 CurDir 122 Currency 79 CurrentController 20 Cursor getRangeName 29 getStart() 69 goRight 29 gotoEndOfParagraph() 69 gotoStartOfParagraph() 69 Date 79, 122 DateSerial 112, 123 DateValue 111p., 124 Day 124 DBG_methods 8

25

DBG_Properties 8 Declare 125 DefBool 79, 126 DefDate 79, 126 DefDbl 79, 127 DefInt 79, 127 DefLng 79, 127 DefObj 79, 128 DefVar 79, 128 Desktop CurrentComponent 41 LoadComponentFromURL() 27 Dim 79pp., 84p., 129 Dim 79 DimArray 85, 130 DimArray. 85, 106 Dir 130, 150 Do...Loop ms cercano 138 Double 79 Else 90 ElseIf 90 El tipo por defecto es Single 79 End 132p. End Function 132p. End If 133 End Select 133 End Sub 133 Environ 133 EOF 116, 134, 147 EqualUnoObjects 134 EQV 101, 135 Erl 136 Err 136 Error 137 Exit 96 Exit DO 96 Exit For 96 Exit Function 96 Exit Sub 96 Exit. 87 Exit Do 93, 138 Exit For 91, 138 Exit Function 139 Exit Sub 139 Exp 139 False 87 156

Fecha 122 Fibonnaci 33 File CLOSE 31 FileExists 31 LINE INPUT 31 OPEN 31 FileAttr 140 FileCopy 141 FileDateTime 141 FileExists 142 Fix 144 For 91 For...Next 138 Format 146 FreeFile 116, 134, 147 Function 87 Get 149 GetAttr 130, 150 getCurrentComponent 20 getNumberFormats() 32 getPathSeparator() 131 GetProcessServiceManager() 151 GetSolarVersion() 151 GetSystemTicks() 152 GlobalScope 152 GoSub 90, 94 GoTo 31, 90, 94p. Green 154 If 90 If. 90 IIf 87, 90p. Int 31 Integer 79 Is 87, 93 IsArray 86 IsDate 86 IsEmpty 86 IsMissing 32, 86, 88 IsNull 74, 86 IsNumeric 86 IsObject 86 IsUnoStruct 86 Kelecevic, Sasa 27 Kill 116, 134, 147 Las variables enteras son nmeros de 16-bits

dentro de un rango de 83 Las varibles Object4 79 LBound 21, 23, 84p. LEN 20, 31 LineDistance 42 Locale Country 69 Language 69 Long 79 Loop 92 Do 92 Do Until 92 Do While 92 Loop Until 93 Loop While 92 Los objetos de cadena estn limitados a 80 Los objetos Variant 80 Macro Author Andrew Pitonyak AccessModes 141 BuildSortedArray 76 CalcGroupingExample 44 ClearDefinedRange 36 ColumnNumberToString 38, 75 CreateSelectedTextIterator 52 DisplayAllStyles 21 ExampleNewPage 72 FileAttributeString 151 FindCreateNumberFormatStyle 32 FirstDuplicate 77 ForNextExampleSort 91 GetLeftMostCursor 50 GetRightMostCursor 50 GoToExample 95 InsertDateField 71 InsertDateIntoCell 39 InsertSimpleText 69 IsAnythingSelected 48 IsSpreadhsheetDoc 35 IsWhiteSpace 53, 148 IterateOverSelectedTextFramework 51 MultipleTextSelectionExample 49 NonBlankCellsInColumn 75 OnGoToExample 95 PrintableAddressOfCell 38, 74 PrintableCellAddress 75 157

PrintAscii 7 PrintDataInColumn 44 PrintEachCharacterWorker 53 ProtectSpreadsheet 45 RankChar 54 Read_Write_Number_In_File 31 RemoveEmptyParsWorker 56 RemoveFromString 6 ReplaceInString 6 SelectedNewLinesToSpaces 56 SelectedNewParagraphsToNewLines 57 SetTextAttributes 68 testOptionalParameters 88 edA-qa mort-ora-y Fibonnaci 33 Hermann Kienlein CreateTable 29 InsertNextItem 29 Niklas Nebel setting_borders_in_calc 42 OpenOffice GetDocumentType 7 Pavel Jank CallExternalProgram 30 Sasa Kelecvic _no_salvar 27 ActiveSheet 41 Analize 41 CellPos 41 DefineDbRange 42 DeleteDbRange 41p. ExampleGetValue 35 ExampleSetValue 35 FillCells 40 GetAddress 41 open_new 29 open_old_file 29 ProgressBar 20 salvar_y_cerrar 27 SelectedCells 39 SortRange 43 StatusText 20 Tony Bloomfield DisplayMethods 8 Unknown

ChangePickListSize 25 MAX 41 MIN 41 MOD 21, 101 NOT 87 Null 86 NumberFormat 32 addNew 32 DATE 32 FindCreateNumberFormatStyle 39, 71 queryKey 32 Object 79 On Error 97 Local 97 On Error 97 On Error GoTo 0 97 On Error GoTo Label 97 On Error Resume Next 97 ON ERROR 31 On Local Error Goto 0 31 On N GoSub 95 On N GoTo 95 Open 31, 134, 147 Option Explicit 25 Option 25 Optional 32, 88 Option Base 84 Option Explicit 9, 79 OR 87, 101 PageDescName 71 PageDescName es el nombre del nuevo estilo de pgina que se usa despus del salto de pgina. Si no usa un estilo de pgina existente, entonces fallar 71 PageNumberOffset 71 PI 84 PRINT 31 printdbgInfo 3 Private 80p., 155 PropertyValue 25, 43 Name 25, 43 Value 25, 43 Public 80p., 155 Public5 80 Red 156 158

ReDim 79, 129 ReDim Preserve 85p. ReDim 85p. ReDimExample 85 ReDim. 80 Return 94 Select Case 93 Selection Columns 41 getRangeAddress 41 Rows 41 shell 30 Single 79 Sort 43 SortField 43 Field 43 SortAscending 43 SPACE 20 SpreadsheetDocument BottomLine 42 Column Columns 39p. getByIndex 40p. getCount 40p. getName 40, 44 Columns 39, 44 Count 36 CurrentSelection 39p. getByName 35, 43 getCellByPosition 35, 40 getCellRangeByName 43 getCellRangeByPosition 42 getCount 40 getName 38, 74p. getRangeAddress 39 Row EndRow 40p. getCount 40p. Rows 40 StartRow 40p. Rows 40 setString 40 Sheets 35p., 42pp. SpreadsheetDocument 35 SupportsService 35

TableBorder 42 StarDesktop respectivamente Static 81 Static6 80 StatusIndicator start 20 Str 31 String 79 Styles CharacterStyles 21 FrameStyles 21 getByName 21 getElementNames() 21 NumberingStyles 21 PageStyles 21 ParagraphStyles 21 StyleFamilies 21 Sub 87 switch 93, 95 TableBorder 42 Tan 108 TextCursor goRight() 47 gotoEnd() 47 gotoStart() 47 IsCollapsed 47 IsCollapsed() 48p. TextDocument compareRegionEnds() compareRegionStarts() createTextCursorByRange createTextCursorByRange() CurrentController 69 getCurrentSelection getCount() 49 getCurrentSelection() 48p. getByIndex() 49 getCount() 48 getString() 30 getText() 30 insertControlCharacter insertString 69 setString 30 Text 30, 69 TextTable getCellByName 29 159

49 49p. 69 48pp., 69

58

ThisComponent TimeValue 111 To 93 Trim 31 True 87 UBound 21 Variant 79 wait 30 While...Wend 94 WritedbgInfo 3 XOR 87, 101

160

Potrebbero piacerti anche