Páginas

lunes, 4 de mayo de 2020

VBA: Funcion para formatear un JSON String para la linea de comandos.

Function escapeQuotes(quotedString As String) As String
    'agrega un escape a las comillas para que sea aceptado por la linea de comandos
    'convierte {"key":"value"} en "{\"key\":\"value\"}"
   
    escQuotes = Replace(quotedString, Chr(34), "\" & Chr(34))
    escapeQuotes = Chr(34) & escQuotes & Chr(34)
   
End Function

jueves, 30 de abril de 2020

VBA: Lista de Funciones Predeterminadas

https://www.excelfunctions.net/vba-functions.html


Built-In VBA Functions


VBA provides a large number of built-in functions that can be used in your code. The most popular built-in VBA functions are listed below. Select a function name to go to a full description of the function with examples of use.

VBA Message Functions
InputBoxDisplays a dialog box prompting the user for input.
MsgBoxDisplays a modal message box.
VBA Text Functions
FormatApplies a format to an expression and returns the result as a string.
InStrReturns the position of a substring within a string.
InStrRevReturns the position of a substring within a string, searching from right to left.
LeftReturns a substring from the start of a supplied string.
LenReturns the length of a supplied string.
LCaseConverts a supplied string to lower case text.
LTrimRemoves leading spaces from a supplied string.
MidReturns a substring from the middle of a supplied string.
ReplaceReplaces a substring within a supplied text string.
RightReturns a substring from the end of a supplied string.
RTrimRemoves trailing spaces from a supplied string.
SpaceCreates a string consisting of a specified number of spaces.
StrCompCompares two strings and returns an integer representing the result of the comparison.
StrConvConverts a string into a specified format.
StringCreates a string consisting of a number of repeated characters.
StrReverseReverses a supplied string.
TrimRemoves leading and trailing spaces from a supplied string.
UCaseConverts a supplied string to upper case text.
VBA Information Functions
IsArrayTests if a supplied variable is an array.
IsDateTests if a supplied expression is a date.
IsEmptyTests if a supplied variant is Empty.
IsErrorTests if a supplied expression represents an error.
IsMissingTests if an optional argument to a procedure is missing.
IsNullTests if a supplied expression is Null.
IsNumericTests if a supplied expression is numeric.
IsObjectTests if a supplied variable represents an object variable.
VBA Error Handling Functions
CVErrProduces an Error data type for a supplied error code.
ErrorReturns the error message corresponding to a supplied error code.
VBA Program Flow Functions
ChooseSelects a value from a list of arguments.
IIfEvaluates an expression and returns one of two values, depending on whether the expression evaluates to True or False.
SwitchEvaluates a list of Boolean expressions and returns a value associated with the first true expression.
VBA Conversion Functions
AscReturns an integer representing the code for a supplied character.
CBoolConverts an expression to a Boolean data type.
CByteConverts an expression to a Byte data type.
CCurConverts an expression to a Currency data type.
CDateConverts an expression to a Date data type.
CDblConverts an expression to a Double data type.
CDecConverts an expression to a Decimal data type.
ChrReturns the character corresponding to a supplied character code.
CIntConverts an expression to an Integer data type.
CLngConverts an expression to a Long data type.
CSngConverts an expression to a Single data type.
CStrConverts an expression to a String data type.
CVarConverts an expression to a Variant data type.
FormatCurrencyApplies a currency format to an expression and returns the result as a string.
FormatDateTimeApplies a date/time format to an expression and returns the result as a string.
FormatNumberApplies a number format to an expression and returns the result as a string.
FormatPercentApplies a percentage format to an expression and returns the result as a string.
HexConverts a numeric value to hexadecimal notation and returns the result as a string.
OctConverts a numeric value to octal notation and returns the result as a string.
StrConverts a numeric value to a string.
ValConverts a string to a numeric value.
VBA Date & Time Functions
DateReturns the current date.
DateAddAdds a time interval to a date and/or time.
DateDiffReturns the number of intervals between two dates and/or times.
DatePartReturns a part (day, month, year, etc.) of a supplied date/time.
DateSerialReturns a Date from a supplied year, month and day number.
DateValueReturns a Date from a String representation of a date/time.
DayReturns the day number (from 1 to 31) of a supplied date.
HourReturns the hour component of a supplied time.
MinuteReturns the minute component of a supplied time.
MonthReturns the month number (from 1 to 12) of a supplied date.
MonthNameReturns the month name for a supplied month number (from 1 to 12).
NowReturns the current date and time.
SecondReturns the second component of a supplied time.
TimeReturns the current time.
TimerReturns the number of seconds that have elapsed since midnight.
TimeSerialReturns a Time from a supplied hour, minute and second.
TimeValueReturns a Time from a String representation of a date/time.
WeekdayReturns an integer (from 1 to 7), representing the weekday of a supplied date.
WeekdayNameReturns the weekday name for a supplied integer (from 1 to 7).
YearReturns the year of a supplied date.
VBA Math & Trig Functions
AbsReturns the absolute value of a number.
AtnCalculates the arctangent of a supplied number.
CosCalculates the cosine of a supplied angle.
ExpCalculates the value of ex for a supplied value of x.
FixTruncates a number to an integer (rounding negative numbers towards zero).
IntReturns the integer portion of a number (rounding negative numbers away from zero).
LogCalculates the natural logarithm of a supplied number.
RndGenerates a random number between 0 and 1.
RoundRounds a number to a specified number of decimal places.
SgnReturns an integer representing the arithmetic sign of a number.
SinCalculates the sine of a supplied angle.
TanCalculates the tangent of a supplied angle.
SqrReturns the square root of a number.
VBA Financial Functions
DDBCalculates the depreciation of an asset during a specified period, using the Double Declining Balance Method.
FVCalculates the future value of a loan or investment.
IPmtCalculates the interest part of a payment, during a specific period, for a loan or investment.
IRRCalculates the internal rate of return for a series of periodic cash flows.
MIRRCalculates the modified internal rate of return for a series of periodic cash flows.
NPerCalculates the number of periods for a loan or investment.
NPVCalculates the net present value of an investment.
PmtCalculates the constant periodic payments for a loan or investment.
PPmtCalculates the principal part of a payment, during a specific period, for a loan or investment.
PVCalculates the present value of a loan or investment.
RateCalculates the interest rate per period for a loan or investment.
SLNCalculates the straight line depreciation of an asset for a single period.
SYDCalculates the sum-of-years' digits depreciation for a specified period in the lifetime of an asset.
VBA Array Functions
ArrayCreates an array, containing a supplied set of values.
FilterReturns a subset of a supplied string array, based on supplied criteria.
JoinJoins a number of substrings into a single string.
LBoundReturns the lowest subscript for a dimension of an array.
SplitSplits a Text String into a Number of Substrings.
UBoundReturns the highest subscript for a dimension of an array.
VBA File Management Functions
CurDirReturns the current path, as a string.
DirReturns the first file or directory name that matches a specified pattern and attributes.
FileAttrReturns the mode of a file that has been opened using the Open statement.
FileDateTimeReturns the last modified date and time of a supplied file, directory or folder.
FileLenReturns the length of a supplied file, directory or folder.
GetAttrReturns an integer, representing the attributes of a supplied file, directory or folder.
Related Page
Vlookup in VBAUse the Excel spreadsheet Vlookup function from within VBA

Oulook VBA: Funcion para obtener un mensaje de correo.


Input = Ninguno
Output = Un objeto MailItem (Un mensaje de correo)

El proceso verifica si en la ventana activa se encuentra abierto un mensaje de correo, la funcion devuelve el mensaje para futura manipulación.

Function getMessage()

    If TypeName(Application.ActiveWindow) = "Inspector" Then
        Set getMessage = Application.ActiveWindow.CurrentItem
    Else
        Set getMessage = Nothing
    End If

End Function


Test:


Sub testFunction()

    Set mail = getMessage()
    
    If mail Is Nothing Then
        Debug.Print TypeName(mail)
    Else
        Debug.Print TypeName(mail)
        Debug.Print mail.Subject
        Debug.Print mail.Body
        For Each adjunto In mail.Attachments
            Debug.Print adjunto.fileName
        Next
    End If

End Sub

miércoles, 18 de marzo de 2020

Evolución de casos Coronavirus Ecuador

martes, 24 de septiembre de 2019

Python: Como descargar el reporte de transacciones de la bolsa de valores

En realidad esta funcion sirve para descargar cualquier archivo que permita hacer un get request.
Debo descomponerla en una funcion que solo descargue un archivo, y otra que lo guarde en formato excel.

def dowloadFile(url, savepath):
'''
Inputs:
url: la direccion web donde se encuentra el archivo, y
savepath: la ruta donde guardar el archivo

Output: Un archivo de excel .xls guardado en la direccion especificada en savepath
'''
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'}
        r = requests.get(url, stream=True, headers=headers)
        with open(savepath, 'wb') as f:
            for chunk in r.iter_content(chunk_size = 128):
                f.write(chunk)


if __name__ == "__main__":
    downloadFile("https://www.bolsadequito.com/uploads/estadisticas/boletines/cotizaciones-historicas/acciones.xls", "c:\acciones.xls")

miércoles, 30 de agosto de 2017

VBA Excel: Macro para combinar varios libros de excel en uno solo

Algunas personas me han preguntado como combinar varios libros con el mismo formato en uno solo y en una sola hoja, pero por default Excel no tiene una herramienta para realizarlo, y las soluciones que estan en internet son tan complicadas que hasta requieren que el usuario inserte codigo de VBA.

Les propongo una solucion mas sencilla:



1.Descargar el archivo con el programa en este link.

2.Abrirlo y habilitar las macros:




3.Indicar el numero de fila en donde se encuentran los titulos de columna

4.Seleccionar la carpeta donde se encuentran los archivos a combinar


5. Procesar. La macro creara un archivo combinado en la misma carpeta seleccionada al inicio.


6. Compartir esta publicacion jajaja.

Para los interesados en ver el codigo, no lo he protegido asi que con ALT-F11 pueden chequearlo y sugerir/realizar cambios.


viernes, 11 de agosto de 2017

Get Request con VBA Excel: Extrayendo definiciones desde la pagina web de la RAE

Hay algunas formas de extraer información desde una página web, la mas sencilla es por medio de un GET Request, que consiste en enviar una dirección modificada con los parámetros de la búsqueda.


Que pasa cuando hacemos click en el botón buscar de la pagina de búsquedas de la rae:









En el background el explorador envía una cadena de texto al servidor de la pagina, algo así como:






La parte hasta el signo de interrogación es la base para enviar todas las consultas a la pagina:





"w=" y "m=" son los campos del formulario que contienen los valores a consultar, de donde salen?



"w" es el atributo "name" del campo donde llenamos la palabra a buscar






"m" es el valor de la opción "exacta" en la lista desplegable.




Entonces en esta parte de la cadena de texto (o dirección web) que vamos a enviar el servidor, estamos especificando la palabra buscada y el tipo de definición:


http://dle.rae.es/srv/search?w=macro&m=30



Si quisieras buscar otras palabras, solo hay que actualizar el contenido de "w",  hagan la prueba pegándolas en la barra de direcciones y vean la pagina que se les devuelve:


http://dle.rae.es/srv/search?w=productividad&m=30
http://dle.rae.es/srv/search?w=programar&m=30
http://dle.rae.es/srv/search?w=programa&m=30


De ahí en adelante es cuestión de leer la pagina y extraer los datos como ya se ha hecho en estos posts:




El Codigo esta dividido en una subrutina que abre el explorador y pasa las palabras a una función que extrae su definición:


Sub buscar_definicion()
    Dim ie As InternetExplorer
    Set ie = New InternetExplorer
    ie.Visible = False
    ie.Navigate "
http://dle.rae.es/"
   
   
    While ie.readyState <> READYSTATE_COMPLETE
        'Debug.Print ("Esperando carga de pagina")
    Wend
   
    Dim celda_palabra As Range
    Dim palabra As String
    For Each celda_palabra In Range("A2", "A11")
        palabra = celda_palabra.Value
        Debug.Print (palabra)
        celda_palabra.Offset(0, 1).Value = buscar_palabra(ie, palabra)
    Next
End Sub


Function buscar_palabra(ie As InternetExplorer, palabra As String)
    Dim pagina As HTMLDocument
    ie.Navigate "
http://dle.rae.es/srv/search?w=" & palabra & "&m=30"
   
    While ie.readyState <> 4
        Debug.Print ("Descargando pagina")
    Wend
   
    Set pagina = ie.document
   
    'chequea que exista un elemento <p> para comprobar que la pagina haya cargado
   
    Dim elemento_parrafo As HTMLParaElement
   
    While elemento_parrafo Is Nothing
        Set pagina = ie.document
        Set elemento_parrafo = pagina.getElementsByTagName("p")(0)
    Wend
       
   
    'chequea si el elemento p es definicion o no
    Dim parrafo As HTMLParaElement
   
    Set parrafo = pagina.getElementsByClassName("j")(0)
   
    If parrafo Is Nothing Then
        buscar_palabra = "Definicion no encontrada"
        Exit Function
    End If
   
    Dim parcial As Variant
    Dim texto_final As String
    texto_final = ""
    For Each parcial In parrafo.Children
        texto_final = texto_final & parcial.innerHTML & " "
    Next
      
    Debug.Print (texto_final)
    buscar_palabra = texto_final
   
   
End Function
























miércoles, 30 de noviembre de 2016

Como copiar una carpeta (y subcarpetas) usando la linea de comandos (Windows)


C:\robocopy carpetaOrigen CarpetaDestino /e /mir

El switch "/e" crea los subdirectorios que estan dentro de la carpeta de origen
El switch "/mir" sirve para crear un "espejo" de la carpeta de origen, ideal para un backup. Si lo elimino un archivo en la carpeta de origen, al copiar se eliminara tambien de la carpeta de destino.

martes, 15 de noviembre de 2016

Como agregar tus programas al boton derecho del mouse

Hace unos dias cree un programa en python que tomaba el path a un archivo de
excel, lo leia, extraia algunos datos y creaba un archivo csv con la
informacion.

Para pasar el path al script, tenia que escribir la ruta en la linea de
comandos, lo cual estaba bien para mi, pero si deseaba compartir mi programa
con algun companero tendria que encontrar una forma mas sencilla de utilizarlo.

Y nada mas facil que hacer click con el boton derecho del mouse sobre el archivo que
deseaba procesar. Asi que buscando un poco en internet encontre dos maneras de
agregar mi script al boton derecho:

La forma larga.
Utilizando el programa regedit.exe se puede crear un path hacia la aplicacion
el el registro de Windows.
1. En la linea de comandos buscamos el programa regedit.exe


2. Seleccionamos la carpeta HKEY_CLASSES_ROOT/*/shell
3. En 'shell' con boton derecho agregamos un 'KEY' con New->Key y le ponemos
el nombre con el que queremos que salga en el menu derecho del mouse. En mi
caso la aplicacion se llama "Make CSV"



4. Agregamos otro key dentro de la carpeta recien creada, esta vez con el
nombre de 'command'
5. Hacemos doble click sobre '(Default)' y emerge una ventana dentro de la
cual ingresamos el path hacia el interprete de python y el path hacia el
programa.
En mi caso el valor a ingresar fue: "C:\Python27\python.exe"
"D:\myScripts\csvmaker\main.py" "%1"
El '%1' se utiliza para pasar a python el path del archivo sobre el cual se
hace click derecho.


Y eso es todo, el script esta ahora accesible desde el menu derecho del mouse.


La forma corta. 
Se crea un archivo '.reg' que contenga la siguiente informacion:

Windows Registry Editor Version 5.00
 [HKEY_CLASSES_ROOT\*\Shell\Make CSV\command]
@="\"C:\\Python27\\python.exe\" \"D:\\myScripts\\csvmaker\\main.py\" \"%1\""

Entro los brackets [] va la ruta donde se alojara la aplicacion
Luego de '@=' va la ruta hacia el interprete de Python y el Script, tal como
especificamos arriba, aunque con muchos 'scape characters'

En mi caso guarde el archivo como csvmaker.reg. Al ejecutar este archivo, el
script se agrega automaticamente al menu. Este metodo tiene la gran ventaja de
que hace mas sencillo aun compartir tus aplicaciones con otros usuarios. Basta
con enviarles el archivo '.reg' y sus maquinas quedaran configuradas para
utilizar tus aplicaciones sin
ningun esfuerzo.

martes, 19 de enero de 2016

VBA OUTLOOK: Como guardar los adjuntos en una seleccion de correos

La clave es utilizar la propiedad "Selection" del Objeto explorer:


Sub guardarAdjuntos()

Dim mensaje As MailItem
Dim mensajes As Variant
Dim adjunto As Attachment
Dim carpeta As String

'escribo el nombre de la carpeta
carpeta = "D:\miCarpeta\"

'Va por cada elemento seleccionado
For Each element In Application.ActiveExplorer.Selection
   'verifica que el elemento sea un mensaje de correo
   If TypeName(element) = "MailItem" Then
        Set mensaje = element
        If mensaje.Attachments.Count > 0 Then 'si hay algun adjunto
            For Each adjunto In mensaje.Attachments 'explora cada adjunto en el mensaje
                adjunto.SaveAsFile (carpeta & adjunto.FileName)
            Next
        MsgBox "Adjuntos guardados: " + mensaje.Subject
        End If
   End If
Next
End Sub

viernes, 20 de noviembre de 2015

Python: Funcion para crear un numero de identidad basado en la fecha

 
from datetime import datetime

def create_id(prefix = "test"):
    '''creates id with a prefix chosen by user'''
    thisday = datetime.now()
    return prefix+str(thisday.year)+str(thisday.month)+str(thisday.year)+ str(thisday.hour)+str(thisday.minute)+str(thisday.second)
    
if __name__ == "__main__":
    new_id = create_id("RUBEN")
    print new_id

viernes, 23 de octubre de 2015

Test sobre Valoracion Aduanera en los Estados Unidos

Para mis amigos profesionales del comercio exterior, una vez mas pónganse a prueba!

Cuales de los siguientes Incotermos son utilizados por la aduana de los Estados Unidos como base imponible para el cálculo de los impuestos a la importación?
  • FAS
  • FOB
  • CIP
  • CIF
  • CPT
  • FCA
  • CFR