Saltar al contenido
PROGRAMAR EN VBA MACROS DE EXCEL

Como pasar con enter datos seleccionados en listbox multiselect a hoja Excel


.

Un suscriptor pregunta como pasar varios datos seleccionados en un listbox multiselect cuando se presione enter, eso es lo que muestra este ejemplo que se presenta en el presente pos, quizás sea de utilidad lo que se enseñó anteriormente que es como pasar datos de un listbox a otro listbox con enter, como pasar datos de un listbox a otro listbox con doble click, como mostrar en un listbox una suma, cuenta y promedio.

El ejemplo que se puede descargar desde el link del final permite seleccionar varios ítemes de un listbox multiselect, luego al presionar enter se pasan todos los datos seleccionados en el listbox a la hoja de excel.

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.

  
Un listbox multiselect a diferencia de un listbox que no es multiselect, permite seleccionar varios ítemes a la vez, es por ello que para pasar todos los datos a la hoja de Excel con Enter, se debe apelar a un bucle que recorra todas las filas del listbox determinando si está seleccionada en ese caso y solo en ese caso se pasan los datos requeridos a la hoja de Excel, para ello en este ejemplo el código que se aplica es el siguiente:

Private Sub ListBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
On Error Resume Next
If KeyAscii = 13 Then
For x = 0 To Me.ListBox1.ListCount – 1
If Me.ListBox1.Selected(x) = True Then
Set a = Sheets(«Hoja1»)
filaedit = a.Range(«A» & Rows.Count).End(xlUp).Row + 1
fila = Me.ListBox1.ListIndex
a.Cells(filaedit, «A») = ListBox1.List(x, 0)
a.Cells(filaedit, «B») = ListBox1.List(x, 1)
a.Cells(filaedit, «C») = ListBox1.List(x, 2)
a.Cells(filaedit, «D») = ListBox1.List(x, 3)
a.Cells(filaedit, «E») = ListBox1.List(x, 4)
a.Cells(filaedit, «F») = ListBox1.List(x, 5)
a.Cells(filaedit, «G») = ListBox1.List(x, 6)
a.Cells(filaedit, «H») = ListBox1.List(x, 7)
filaedit = filaedit + 1
End If
Next x
End If
End Sub

Si se observa el código, con KeyAscci=13 se detecta si se ha presionado enter, ya 13 es en código que se Asigna en Código Ascci a la tecla Enter, en caso que se haya presionado enter se procede a realizar un bucle desde la primera a la última fila del listbox, en ese recorrido determina si la fila está seleccionada, en caso positivo traslada los datos del listbox a Excel.

Para determinar si una linea o fila del listbox está seleccionada, se utiliza el siguiente código:

If Me.ListBox1.Selected(x) = True Then
….
End If

El código anterior es lo que permite filtrar todas las filas seleccionadas del listbox, es por ello que solo permite pasar a la hoja de Excel los datos seleccionados.

El vídeo que sigue muestra una explicación más detallada y gráfica de la macro presentada, 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 formulario que crea un listado de todas las hojas para poder luego seleccionarlasbuscar en listbox mientras escribes en textboxordenar hojas libro excel por su nombreconectar Excel con Access 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
Sub muestra()
UserForm1.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
For x = 0 To Me.ListBox1.ListCount – 1
If Me.ListBox1.Selected(x) = True Then
Set a = Sheets(«Hoja1»)
filaedit = a.Range(«A» & Rows.Count).End(xlUp).Row + 1
fila = Me.ListBox1.ListIndex
a.Cells(filaedit, «A») = ListBox1.List(x, 0)
a.Cells(filaedit, «B») = ListBox1.List(x, 1)
a.Cells(filaedit, «C») = ListBox1.List(x, 2)
a.Cells(filaedit, «D») = ListBox1.List(x, 3)
a.Cells(filaedit, «E») = ListBox1.List(x, 4)
a.Cells(filaedit, «F») = ListBox1.List(x, 5)
a.Cells(filaedit, «G») = ListBox1.List(x, 6)
a.Cells(filaedit, «H») = ListBox1.List(x, 7)
filaedit = filaedit + 1
End If
Next x
End If
End Sub

Private Sub CommandButton2_Click()
Dim conta As Integer
On Error Resume Next
conta = 0
For x = 0 To Me.ListBox1.ListCount – 1
    If Me.ListBox1.Selected(x) = True Then
    conta = conta + 1
    End If
Next x
If conta = 0 Then
MsgBox «Debe seleccionar un item para copiar en hoja de Excel», vbInformation, «AVISO»
Exit Sub
End If
conta = 0
Set a = Sheets(«Hoja1»)
filaedit = a.Range(«A» & Rows.Count).End(xlUp).Row + 1
For x = 0 To Me.ListBox1.ListCount – 1
    If Me.ListBox1.Selected(x) = True Then
    conta = conta + 1
    End If
Next x
If conta <> 0 Then
For x = 0 To Me.ListBox1.ListCount – 1
          If Me.ListBox1.Selected(x) = True Then
            ‘fila = Me.ListBox1.ListIndex.SelectedItem
            a.Cells(filaedit, «A») = ListBox1.List(x, 0)
            a.Cells(filaedit, «B») = ListBox1.List(x, 1)
            a.Cells(filaedit, «C») = ListBox1.List(x, 2)
            a.Cells(filaedit, «D») = ListBox1.List(x, 3)
            a.Cells(filaedit, «E») = ListBox1.List(x, 4)
            a.Cells(filaedit, «F») = ListBox1.List(x, 5)
            a.Cells(filaedit, «G») = ListBox1.List(x, 6)
            a.Cells(filaedit, «H») = ListBox1.List(x, 7)
            Me.ListBox1.Selected(x) = False
            filaedit = filaedit + 1
          End If
Next x
End If
End Sub
Private Sub ListBox1_Change()
TextBox3 = Clear
For x = 0 To Me.ListBox1.ListCount – 1
    If Me.ListBox1.Selected(x) = True Then
    tot = tot + CDec(UserForm1.ListBox1.List(x, 7))
    End If
Next x
TextBox3.Text = Format(tot, «Currency»)
TextBox3.TextAlign = fmTextAlignRight
End Sub

Private Sub TextBox1_Change()
On Error Resume Next
TextBox3 = Clear
Set b = Sheets(«Hoja2»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox1.Value) = «» Then
     ‘Me.ListBox1.List() = b.Range(«A2:H» & uf).Value
     Me.ListBox1.RowSource = «Hoja2!A2:H» & uf
   Exit Sub
End If
b.AutoFilterMode = False
Me.ListBox1 = Clear
Me.ListBox1.RowSource = Clear
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)
   End If
Next i
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
TextBox3 = Clear
Set b = Sheets(«Hoja2»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox2.Value) = «» Then
     ‘Me.ListBox1.List() = b.Range(«A2:H» & uf).Value
     Me.ListBox1.RowSource = «Hoja2!A2:H» & uf
   Exit Sub
End If
b.AutoFilterMode = False
Me.ListBox1 = Clear
Me.ListBox1.RowSource = Clear
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)
   End If
Next i
Me.ListBox1.ColumnWidths = «20 pt;70 pt;180 pt;80 pt;60 pt;60 pt;60 pt;60pt»
End Sub

Private Sub UserForm_Initialize()
Dim fila As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set b = Sheets(«Hoja2»)
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 = 8
    .ColumnWidths = «20 pt;70 pt;180 pt;80 pt;60 pt;60 pt;60 pt;60pt»
    .RowSource = «Hoja2!A2:» & wc & uf
End With
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

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