jueves, 23 de enero de 2014

Macro para la Creación de una Boleta

CREACION DE REGISTRO DE BOLETAS

Antes de comenzar la explicación de la macro propiamente tal, les explicaré un poco en qué consistió todo el proceso previo a la utilización de esta.
Lo primero que realicé fue crear una base de datos con la información de ciertos productos de una empresa en particular. La empresa que utilicé para ejemplificar mi modelo fue la empresa Samsung y sus productos telefónicos Android, específicamente los Galaxy (que se entienda que este modelo es aplicable para cualquier empresa, solo que a modo de ejemplo yo utilicé Samsung). 




Segundo, luego de tener todos los datos de los teléfonos Android y sus valores, realicé un formulario en el cual podía escoger, a través de una lista desplegable, el modelo Galaxy que yo deseaba comprar. Luego de asignar el modelo, puedo escoger la cantidad que deseo comprar. Principalmente el formulario tiene como fin realizar una cotización del producto que deseas comprar, por lo que luego de escoger el modelo y cantidad de teléfonos,  el formulario me entregará el monto total de la compra con los descuentos asociados de acuerdo al tipo de pago. Finalmente, luego de este proceso, el formulario tiene un botón (el cual está asociado a la macro que explicaremos posteriormente) que se utilizará para crear la boleta de la compra.




Aquí comienza la explicación de la macro. Lo que consiste principalmente esta macro es que, luego de realizar la cotización, ésta creará una boleta, la cual será guardada en forma de PDF para su posterior  impresión y además permitirá crear un registro en una hoja llamada “HISTORIA”  todos los registros de las boletas emitidas.


EXPLICACION DE LA MACRO (VISUAL BASIC)

Lo primero que hice en la macro fue crear el formato tipo de una boleta (cotización), el cual contiene el nombre del cliente, su rut, dirección, el producto que compra, la cantidad y el valor total de la compra, además de la fecha en la cual la realizó.



Sub CrearBoleta()

' Creamos el modelo tipo de la boleta

    Worksheets("Boleta").Activate
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "Nombre Cliente:"
    Range("B3").Select
    ActiveCell.FormulaR1C1 = "Rut:"
    Range("B4").Select
    ActiveCell.FormulaR1C1 = "Dirección"
    Range("B6").Select
    ActiveCell.FormulaR1C1 = "Producto:"
    Range("B7").Select
    ActiveCell.FormulaR1C1 = "Cantidad:"
    Range("B8").Select
    ActiveCell.FormulaR1C1 = "Total a Pagar:"
    Range("B10").Select
    ActiveCell.FormulaR1C1 = "Gracias por su compra"
    Range("B11").Select
    ActiveCell.FormulaR1C1 = _
    "SAMSUNG DIGITall everyone's invited"
    Rows("1:1").Select
    Selection.Insert Shift:=xlDown
    Range("C1").Select
    ActiveCell.FormulaR1C1 = "COTIZACION"
   
    Range("B1:E1").Select
    Selection.Font.Bold = True
    Selection.Font.Size = 12
    Selection.Font.Size = 14
   
    Range("E2").Select
    ActiveCell.FormulaR1C1 = "Fecha:"
    Cells.Select
    Cells.EntireColumn.AutoFit
    Range("A1:F13").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Rows("14:14").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.EntireRow.Hidden = True
    Columns("G:G").Select
    Range("G2").Activate
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.EntireColumn.Hidden = True
    Selection.End(xlToLeft).Select
    Selection.End(xlToLeft).Select
    Selection.End(xlToLeft).Select
    Range("B12:E12").Select
    Range("E12").Activate
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge
    Range("B11:E11").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge
    Columns("B:B").Select
    Range("B2").Activate
    Columns("B:B").EntireColumn.AutoFit
    Columns("E:E").ColumnWidth = 11.43
    Range("C3").Select
    ActiveWindow.SmallScroll Down:=-12
    Range("B1:E1").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge
    Range("C3").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    Selection.Borders(xlEdgeTop).LineStyle = xlNone
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("C4").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("C5").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("C7").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    Selection.Borders(xlEdgeTop).LineStyle = xlNone
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("C8").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("C9").Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    Range("B3:B9").Select
    With Selection
        .HorizontalAlignment = xlRight
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Range("B12:E12").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.349986266670736
        .PatternTintAndShade = 0
    End With


Luego hacer el formato tipo de la boleta le voy a asignar los datos que irán en ella. Además le daré formato moneda a lo que es el monto total de la compra.

'Seleccionamos los datos que van a ir en la boleta y le damos formato

    ActiveSheet.Select
   
    Range("C7").Select
    ActiveCell.FormulaR1C1 = "=COTIZACION!R3C4"
    Range("C8").Select
    ActiveCell.FormulaR1C1 = "=COTIZACION!R7C2"
    Range("C9").Select
    ActiveCell.FormulaR1C1 = "=COTIZACION!R23C2"
    Range("C10").Select

    Range("C9").Select
    Selection.NumberFormat = "$ #,##0.00"
    Selection.NumberFormat = "$ #,##0.0"
    Selection.NumberFormat = "$ #,##0"


Luego de tener lista la boleta con los datos y el formato , voy a crear variables (Dim) que me permitirán llevar a cabo diferentes tareas. En el caso de la variable x=nombre, y=rut y z=dirección las aplicaré como un ImputBox, el cual me permitirá el llenado de esos datos para hacer más personalizada la boleta. Además creé las variables ID, producto, cantidad y total y les asigné un rango de valor. Finalmente le asigno la fecha de creación de la boleta.

'Dim -> Declaro variables
'Realizo un InputBox

Dim x As String 'nombre
Dim y As String 'rut
Dim z As String 'dirección
Dim ID As Double
Dim Producto As String
Dim Cantidad As Double
Dim Total As Double

x = InputBox("Indique su nombre", "Registro de datos")
ActiveSheet.Range("c3").Value = x

y = InputBox("Indique su rut", "Registro de datos")
ActiveSheet.Range("c4").Value = y

z = InputBox("Indique su dirección", "Registro de datos")
ActiveSheet.Range("c5").Value = z

Producto = Range("C7").Value
Precio = Val(Range("C8").Value)
Total = Val(Range("C9").Value)

'Le asigno a la boleta la fecha de hoy

    Range("F2").Select
    ActiveCell.FormulaR1C1 = "=TODAY()"


   
       
Luego de tener lista la hoja con la boleta cotización, creo una hoja llamada "HISTORIA" la cual es una tabla que contiene los mismos encabezados que la boleta en la que se van a ir almacenando toda la información de las cotizaciones emitidas (boletas).

‘Creo la hoja HISTORIA en la que se almacenarán los datos
   
    Worksheets("HISTORIA").Activate
    ActiveSheet.Range("B2").Activate
   
    Do While Not IsEmpty(ActiveCell)
    ActiveCell.Offset(1, 0).Activate
   
    Loop
    ID = Val(Range("J1").Value)
   
    With ActiveCell
    .Value = ID
    .Offset(0, 1).Value = x
    .Offset(0, 2).Value = y
    .Offset(0, 3).Value = z
    .Offset(0, 4).Value = Producto
    .Offset(0, 5).Value = Precio
    .Offset(0, 6).Value = Total
   
    End With



Finalmente, cada vez que se lleve a cabo una nueva cotización, activamos la hoja BOLETA para guardarla como PDF y así tener un conteo de todas las boletas impresas. Esta boleta quedará guardada en la carpeta que se le asignó, sin embargo, a modo de hacerlo más estándar para cada computador, no le asignaremos ninguna carpeta, para que así el archivo se guarde por defecto en "Mis Documentos".

‘Guardo la boleta como PDF

    Worksheets("BOLETA").Activate
    Range("A1:F13").Select
   
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "BOLETA - " & ID & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False

    Selection.Clear
ActiveSheet.Select
      
End Sub

"C:\Users\Pacita\Desktop\BOLETAS\BOLETA - " & ID & ".pdf" _ 
‘ Este seria el código para guardarlo en una carpeta determinada.





Descargar Archivo

No hay comentarios:

Publicar un comentario