Saltar al contenido
PROGRAMAR EN VBA MACROS DE EXCEL

Como crear una factura o sale invoice seleccionando articulos en listbox


.

En esta tercera presentación de la macro denominada como crear una factura o sale invoice, voy a mostrar como cargar datos de productos de una base de datos de Excel en un listbox, buscar por marca o producto, seleccionar un ítem en el listbox y pasar los datos a otro listbox con enter.

Es decir una vez cargado el cliente, se procede a ingresar al padrón de artículos para listarlos en listbox, realizado esto se puede seleccionar un producto  y mediante enter pasarlo al listbox de la factura, procediendo a realizar los cálculos correspondientes para determinar el total a pagar por el producto facturado.

Con anterioridad se vió:

Como crear una factura o sale invoice seleccionando cliente de listbox
Como crear una factura o sale invoice guardar cliente nuevo
Como crear una factura o sale invoice seleccionando articulos en listbox
Como crear una factura o sale invoice eliminar articulos del listbox
Como crear una factura o sale invoice y guardar registro
Como crear una factura o sale invoice guardar e imprimir
Como crear una factura o sale invoice y guardar en PDF
Como crear una factura o sale invoice y grabar guardar PDF XLS y enviar por MAIL
Como crear una factura o sale invoice y descontar de Stock o Inventario

Antes de seguir recomiendo leer un excelente libro sobre Excel que te ayudará operar las planillas u hojas de cálculo, haz click acá, si quieres aprender sobre Excel, en inglés, entonces debes hacer click here. Si lo que necesitas es aprender o profundizar sobre la programación de macros con VBA este es unos de los mejores cursos on line que he visto en internet.

  
En este post concretamente se podrá observar como cargar datos de una base de datos a un listbox, como buscar productos a medida que se escribe en textbox, como pasar con enter de un listbox a otro listbox un producto seleccionado, como realizar cálculos, en este caso precio por cantidad y dicho resultado agregarlo en la misma fila del listbox del ítem seleccionado; como realizar una sumatoria de toda una columna de un listbox.

En el ejemplo al seleccionar un articulo en el listbox, automátiamente se cargan en variables públicas los datos necesarios con estos códigos:

cod = ListBox1.List(fila, 1)
art = ListBox1.List(fila, 2)
mar = ListBox1.List(fila, 3)
pv = ListBox1.List(fila, 8)

Esto luego es usado en el Userform3 más específicamente en el evento change del textbox, donde se detecta si la tecla presionada es Enter en ese caso ejecuta la macro y copia los datos de las variables anteriores y los cálculos correspondientes en el listbox de la factura, es  se realiza con esta parte del código, con ello se puede aprender como detectar si la letra presionada es Enter (If KeyCode = 13 Then), pasar datos datos al listbox y dar formato a los valores del listbox en el resto de código que seguidamente se muestran.

If KeyCode = 13 Then
can = Val(UserForm3.TextBox1)
UserForm2.ListBox1.AddItem cod
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 1) = art
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 2) = mar
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 3) = Format(pv, «#,##0.0000;-#.##0,0000»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 4) = Format(can, «#,##0.00;-#.##0,00»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 5) = Format((pv * 0.16), «#,##0.00;-#.##0,00»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 6) = Format(((can * pv) * 1.16), «#,##0.00;-#.##0,00»)
Unload UserForm3

Sugiero descargar desde un link al final de post este ejemplo y los anteriores para poder ver con facilidad su funcionamiento y codificación, del resto y de este post cuya macro permite entre otras cosas pasar datos de un listbox a otro listbox con Enter.

Una explicación más detallada y gráfica de la macro presentada se muestra en el vídeo que se muestra seguidamente, recomiendo observar para una más fácil comprensión de la macro; suscribe a nuestra web desde la parte superior derecha de la página ingresando tu mail y a nuestro canal de You Tube para recibir en tu correo vídeos explicativos sobre macros interesantes, como por ejemplo Como cerrar libro dependiendo de fecha de caducidadbuscar en listbox mientras escribes en textboxComo conectar Excel con Word crear archivo e insertar textoComo crear un autonumerico en Excel y muchos ejemplos más.


if (payload.eventType == ‘subscribe’) {
// Add code to handle subscribe event.
} else if (payload.eventType == ‘unsubscribe’) {
// Add code to handle unsubscribe event.
}
if (window.console) { // for debugging only
window.console.log(‘YT event: ‘, payload);
}
}

Código que se inserta en un módulo
Public cod, art, mar, pv, ctr, creg
Sub muestra1()
UserForm2.Show
End Sub
Código que se inserta en un Formulario

Private Sub CommandButton1_Click()
Unload Me
End Sub

Private Sub ListBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
On Error Resume Next
If KeyAscii = 13 Then
Set a = Sheets(«Articulos»)
filaedit = a.Range(«A» & Rows.Count).End(xlUp).Row + 1
fila = Me.ListBox1.ListIndex
‘a.Cells(filaedit, «A») = ListBox1.List(fila, 0)
‘a.Cells(filaedit, «B») = ListBox1.List(fila, 1)
‘a.Cells(filaedit, «C») = ListBox1.List(fila, 2)
‘a.Cells(filaedit, «D») = ListBox1.List(fila, 3)
‘a.Cells(filaedit, «E») = ListBox1.List(fila, 4)
‘a.Cells(filaedit, «F») = ListBox1.List(fila, 5)
‘a.Cells(filaedit, «G») = ListBox1.List(fila, 6)
‘a.Cells(filaedit, «H») = ListBox1.List(fila, 7)
‘a.Cells(filaedit, «I») = ListBox1.List(fila, 8)
cod = ListBox1.List(fila, 1)
art = ListBox1.List(fila, 2)
mar = ListBox1.List(fila, 3)
pv = ListBox1.List(fila, 8)
End If
Unload UserForm1
UserForm3.Show
End Sub

Private Sub TextBox1_Change()
On Error Resume Next
Set b = Sheets(«Articulos»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox1.Value) = «» Then
Me.ListBox1.Clear
     ‘Me.ListBox1.List() = b.Range(«A2:H» & uf).Value
     ‘Me.ListBox1.RowSource = «Hoja2!A2:H» & uf
     ‘Adiciona un item al listbox reservado para la cabecera
UserForm1.ListBox1.AddItem

For i = 2 To uf
  ‘ strg = b.Cells(i, 4).Value
   ‘If UCase(strg) Like UCase(TextBox2.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 7) = b.Cells(i, 8)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 8) = b.Cells(i, 9)
  ‘ End If
Next i

‘Carga los datos de la cabecera en listbox
For ii = 0 To 9
UserForm1.ListBox1.List(0, ii) = Sheets(«Articulos»).Cells(1, ii + 1)
Next ii
   Exit Sub
End If

b.AutoFilterMode = False
Me.ListBox1.Clear
Me.ListBox1.RowSource = Clear
‘Adiciona un item al listbox reservado para la cabecera
UserForm1.ListBox1.AddItem
For i = 2 To uf
   strg = b.Cells(i, 3).Value
   If UCase(strg) Like UCase(TextBox1.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 7) = b.Cells(i, 8)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 8) = b.Cells(i, 9)
   End If
Next i

‘Carga los datos de la cabecera en listbox
For ii = 0 To 9
UserForm1.ListBox1.List(0, ii) = Sheets(«Articulos»).Cells(1, ii + 1)
Next ii
‘Me.ListBox1.ColumnWidths = «20 pt;70 pt;180 pt;80 pt;60 pt;60 pt;60 pt;60pt»
End Sub
Private Sub TextBox2_Change()
On Error Resume Next
Set b = Sheets(«Articulos»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox2.Value) = «» Then
Me.ListBox1.Clear
     ‘Me.ListBox1.List() = b.Range(«A2:H» & uf).Value
     ‘Me.ListBox1.RowSource = «Hoja2!A2:H» & uf
     ‘Adiciona un item al listbox reservado para la cabecera
UserForm1.ListBox1.AddItem

For i = 2 To uf
  ‘ strg = b.Cells(i, 4).Value
   ‘If UCase(strg) Like UCase(TextBox2.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 7) = b.Cells(i, 8)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 8) = b.Cells(i, 9)
  ‘ End If
Next i

‘Carga los datos de la cabecera en listbox
For ii = 0 To 9
UserForm1.ListBox1.List(0, ii) = Sheets(«Articulos»).Cells(1, ii + 1)
Next ii
   Exit Sub
End If
b.AutoFilterMode = False
Me.ListBox1.Clear
Me.ListBox1.RowSource = Clear

‘Adiciona un item al listbox reservado para la cabecera
UserForm1.ListBox1.AddItem

For i = 2 To uf
   strg = b.Cells(i, 4).Value
   If UCase(strg) Like UCase(TextBox2.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 7) = b.Cells(i, 8)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 8) = b.Cells(i, 9)
   End If
Next i

‘Carga los datos de la cabecera en listbox
For ii = 0 To 9
UserForm1.ListBox1.List(0, ii) = Sheets(«Articulos»).Cells(1, ii + 1)
Next ii
End Sub

Private Sub UserForm_Initialize()
Dim fila As Long
On Error Resume Next
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set b = Sheets(«Articulos»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
uc = b.Cells(1, Columns.Count).End(xlToLeft).Address
wc = Mid(uc, InStr(uc, «$») + 1, InStr(2, uc, «$») – 2)
With Me.ListBox1
    .ColumnCount = 9
    .ColumnWidths = «20 pt;70 pt;180 pt;80 pt;60 pt;60 pt;60 pt;60pt;60pt»
    ‘.RowSource = «Hoja2!A1:» & wc & uf
End With
‘Adiciona un item al listbox reservado para la cabecera
UserForm1.ListBox1.AddItem

For i = 2 To uf
  ‘ strg = b.Cells(i, 4).Value
   ‘If UCase(strg) Like UCase(TextBox2.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 7) = b.Cells(i, 8)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 8) = b.Cells(i, 9)
  ‘ End If
Next i

‘Carga los datos de la cabecera en listbox
For ii = 0 To 9
UserForm1.ListBox1.List(0, ii) = Sheets(«Articulos»).Cells(1, ii + 1)
Next ii

Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
On Error GoTo Fin
If CloseMode <> 1 Then Cancel = True
Fin:

End Sub

Código que se inserta en un formulario

Private Sub CommandButton1_Click()
Unload UserForm2
End Sub

Private Sub CommandButton3_Click()
UserForm1.Show
End Sub

Private Sub Label4_Click()
ActiveWorkbook.FollowHyperlink «https://macrosenexcel.com/p/home.html»
End Sub

Private Sub ListBox2_Click()
On Error Resume Next
ctr = 1
TextBox1 = Empty
TextBox2 = Empty
fila = Me.ListBox2.ListIndex
Me.TextBox1 = ListBox2.List(fila, 2)
Me.TextBox2 = ListBox2.List(fila, 3)
ListBox2.Visible = False
ctr = 0
End Sub

Private Sub TextBox1_AfterUpdate()
creg = ListBox2.ListCount
If creg = 0 Then
ListBox2.Visible = False
RESP = MsgBox(«Presione SI para cargar cliente o NO para cancelar y proseguir la realización del comprobante de venta», vbYesNo, «REQUIERE CARGAR EL CLIENTE NUEVO»)
    If RESP = 6 Then
    uf = Sheets(«Clientes»).Range(«A» & Rows.Count).End(xlUp).Row
    UserForm4.TextBox1 = Application.WorksheetFunction.Max(Sheets(«Clientes»).Range(«A2» & «:A» & uf + 1)) + 1
    UserForm4.TextBox3 = UserForm2.TextBox1
    UserForm4.TextBox2.SetFocus
    UserForm4.Show
    Else
    UserForm2.TextBox2.Locked = False
    UserForm2.TextBox2 = Empty
    UserForm2.TextBox2.SetFocus
    End If
End If
End Sub

Private Sub TextBox1_Change()
If ctr = 1 Then Exit Sub
On Error Resume Next
Set b = Sheets(«Clientes»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox1.Value) = «» Then
   Me.ListBox2.RowSource = «Clientes!A2:D» & uf
   Exit Sub
End If
b.AutoFilterMode = False
Me.ListBox2.Clear
Me.ListBox2.RowSource = Clear
Me.ListBox2.ColumnCount = 4
For i = 2 To uf
   strg = b.Cells(i, 3).Value
   If UCase(strg) Like «*» & UCase(TextBox1.Value) & «*» Then
       Me.ListBox2.AddItem b.Cells(i, 1)
       Me.ListBox2.List(Me.ListBox2.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox2.List(Me.ListBox2.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox2.List(Me.ListBox2.ListCount – 1, 3) = b.Cells(i, 4)
   End If
Next i
Me.ListBox2.ColumnWidths = «15 pt;50 pt;80 pt;80»
ListBox2.Visible = True
End Sub

Private Sub UserForm_Initialize()
Nfac = Application.WorksheetFunction.Max(Sheets(«DbFac»).Range(«A2» & «:A» & uf + 1)) + 1
Label2.Caption = Format(Nfac, «00000000»)
Me.ListBox1.ColumnCount = 7
Me.ListBox1.ColumnWidths = «70 pt;160 pt;60 pt;60 pt;60 pt;60 pt;60 pt»
TextBox3.SetFocus
End Sub

Código que se inserta en un formulario

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim t As Variant, tot As Variant
If UserForm3.TextBox1 = Empty Or UserForm3.TextBox1 = 0 Then Exit Sub
On Error Resume Next
If KeyCode = 13 Then
can = Val(UserForm3.TextBox1)
UserForm2.ListBox1.AddItem cod
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 1) = art
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 2) = mar
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 3) = Format(pv, «#,##0.0000;-#.##0,0000»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 4) = Format(can, «#,##0.00;-#.##0,00»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 5) = Format((pv * 0.16), «#,##0.00;-#.##0,00»)
UserForm2.ListBox1.List(UserForm2.ListBox1.ListCount – 1, 6) = Format(((can * pv) * 1.16), «#,##0.00;-#.##0,00»)
Unload UserForm3

For X = 0 To UserForm2.ListBox1.ListCount – 1
t = CDec(UserForm2.ListBox1.List(X, 6))
tot = tot + t
t = 0
Next X

‘Alinea los números de la columna del listbox a la derecha
‘For j = 3 To 6
‘For X = 0 To UserForm2.ListBox1.ListCount – 1
‘UserForm2.ListBox1.List(X, j) = Space(10 – 2 * Len(Trim(Format(UserForm2.ListBox1.List(X, j), «#,##0.00;-#.##0,00»)))) & UserForm2.ListBox1.List(X, j)
‘Next X
‘Next j

UserForm2.Label16.Caption = «Total  » & Format(tot, «#,##0.00;-#.##0,00»)
UserForm2.Label14.Caption = «Subtotal  » & Format((tot / 1.16), «#,##0.00;-#.##0,00»)
UserForm2.Label15.Caption = «IVA  » & Format(((tot / 1.16) * 0.16), «#,##0.00;-#.##0,00»)
End If
End Sub

Código que se inserta en un formulario


Private Sub CommandButton1_Click()
If UserForm4.TextBox1 = Empty Or UserForm4.TextBox2 = Empty Or UserForm4.TextBox3 = Empty Or UserForm4.TextBox4 = Empty Then Exit Sub
Set a = Sheets(«Clientes»)
uf = a.Range(«A» & Rows.Count).End(xlUp).Row + 1
a.Cells(uf, «A») = Val(UserForm4.TextBox1)
a.Cells(uf, «B») = UserForm4.TextBox2
a.Cells(uf, «C») = UserForm4.TextBox3
a.Cells(uf, «D») = UserForm4.TextBox4
UserForm2.TextBox1 = UserForm4.TextBox3
UserForm2.TextBox2 = UserForm4.TextBox4
MsgBox («Los datos se gaurdarón con éxito»), vbInformation, «AVISO»
Unload UserForm4
End Sub

Private Sub CommandButton2_Click()
Unload UserForm4
End Sub

Si te fue de utilidad puedes INVITARME UN CAFÉ y de esta manera ayudar a seguir manteniendo la página, CLICK para descargar en ejemplo en forma gratuita.


.

If this post was helpful INVITE ME A COFFEE and so help keep up the page, CLICK to download free example.

Si te gustó por favor compártelo con tus amigos
If you liked please share it with your friends