Problema macro On Error GoTo

De nuevo a todos.

Tengo otro problemilla. Al ejecutar otra macro, se supone que si marca error me mande directamente al mensaje. Pero al momento de ejecutarlo me agrega al listbox el dato del texbox.

Private Sub CommandButton2_Click()
Set i = Sheets("INVENTARIO")
Set b = i.Columns("A").Find(TextBox3.Value, LookAt:=xlWhole)
On Error GoTo msnError
Me.ListBox1.AddItem Me.TextBox3.Value
ListBox1.List(ListBox1.ListCount - 1, 0) = i.Cells(b.Row, "B")
ListBox1.List(ListBox1.ListCount - 1, 1) = i.Cells(b.Row, "D")
ListBox1.List(ListBox1.ListCount - 1, 2) = i.Cells(b.Row, "C")
ListBox1.List(ListBox1.ListCount - 1, 3) = i.Cells(b.Row, "A")
ListBox1.List(ListBox1.ListCount - 1, 4) = ComboBox3.Value
Me.TextBox3.Value = ""
Me.Label11.Caption = ""
Me.Label12.Caption = ""
Me.TextBox3.SetFocus
Exit Sub
msnError:
MsgBox "El registro no existe"
End Sub

Al momento de ejecutar la macro y mandar el mensaje de error se alcanza a registrar el contenido del textbox, cuando se supone que no debe de arrojar nada.

Otra cosa:

¿Cómo se le puede hacer para que al dar la tecla Enter al textbox haga automáticamente esta macro?

1 respuesta

Respuesta
3

No deberías utilizar las instrucciones On Error Goto u On Error Resume Next, no es una buena práctica.

Lo que debes hacer es controlar los posibles errores con programación.


De cualquier forma, te explico lo que está sucediendo.

Cuando ejecutas esta instrucción:

Set b = i.Columns("A").Find(TextBox3.Value, LookAt:=xlWhole)

Si no encuentra, no ocurre ningún error, ya que el objeto b simplemente está vacío.

Como no hay error, en el listbox se agrega el dato del textbox:

Me. ListBox1. AddItem Me. TextBox3.Value

El error ocurre en la siguiente línea

ListBox1. List(ListBox1.ListCount - 1, 0) = i. Cells(b. Row, "B")

Y eso es debido a que estás utilizando b. Row, pero como b está vacío entonces ocurre el error.


La forma de solucionar lo anterior, sin utilizar la instrucción On Error, quedaría así:

Private Sub CommandButton2_Click()
    Set i = Sheets("INVENTARIO")
    Set b = i.Columns("A").Find(TextBox3.Value, LookAt:=xlWhole)
    If Not b Is Nothing Then
        Me.ListBox1.AddItem Me.TextBox3.Value
        ListBox1.List(ListBox1.ListCount - 1, 0) = i.Cells(b.Row, "B")
        ListBox1.List(ListBox1.ListCount - 1, 1) = i.Cells(b.Row, "D")
        ListBox1.List(ListBox1.ListCount - 1, 2) = i.Cells(b.Row, "C")
        ListBox1.List(ListBox1.ListCount - 1, 3) = i.Cells(b.Row, "A")
        ListBox1.List(ListBox1.ListCount - 1, 4) = ComboBox3.Value
        Me.TextBox3.Value = ""
        Me.Label11.Caption = ""
        Me.Label12.Caption = ""
        Me.TextBox3.SetFocus
    Else
        MsgBox "El registro no existe"
    End If
End Sub

Otro detalle que veo en tu macro, en esta línea pones el textbox3 en la columna 0 del listbox:

Me. ListBox1. AddItem Me. TextBox3.Value

Y después agregas el dato de la columna B en la columna 0 del listbox, sobreescribiendo el dato del textbox3:

ListBox1. List(ListBox1.ListCount - 1, 0) = i. Cells(b. Row, "B")

Si quieres los 2 datos en el listbox, debes cambiar la numeración.


Por último, si quieres que se ejecute cuando presionas enter en el textbox3, cuando presionas enter, equivale a salir del textbox, para eso se utiliza el evento Exti:

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Set i = Sheets("INVENTARIO")
    Set b = i.Columns("A").Find(TextBox3.Value, LookAt:=xlWhole)
    If Not b Is Nothing Then
        Me.ListBox1.AddItem Me.TextBox3.Value
        ListBox1.List(ListBox1.ListCount - 1, 0) = i.Cells(b.Row, "B")
        ListBox1.List(ListBox1.ListCount - 1, 1) = i.Cells(b.Row, "D")
        ListBox1.List(ListBox1.ListCount - 1, 2) = i.Cells(b.Row, "C")
        ListBox1.List(ListBox1.ListCount - 1, 3) = i.Cells(b.Row, "A")
        ListBox1.List(ListBox1.ListCount - 1, 4) = ComboBox3.Value
        Me.TextBox3.Value = ""
        Me.Label11.Caption = ""
        Me.Label12.Caption = ""
        Me.TextBox3.SetFocus
    Else
        MsgBox "El registro no existe"
    End If
End Sub

'.[Sal u dos. Dante Amor. No olvides valorar la respuesta. 
'.[Avísame cualquier duda

Gracias entiendo lo que dices.
Es que no se mucho de de programación.
Lo que me dices de sobrescribir lo pongo por que no se otra forma de agregar los datos, ya que si no pongo esa linea

Me.ListBox1.AddItem Me.TextBox3.Value

Me marca error
Unas ultimas dudas.

-Para hacer que se ejecute de cualquiera de las dos formas ya sea el botón o con enter tengo que duplicar la macro, una para el botón y otra para el enter?

-Al ejecutar la macro se sale del textbox por lo que la parte de setfocus ya no me funciona, si la pongo al final me marca error. Se puede hacer que se vuelva a seleccionar el textbox? Es que pienso usar un lector de textos.
Agradezco mucho tu ayuda.

Si no quieres el dato del textbox, entonces no es necesario ponerlo puede ser así:

Me. ListBox1. AddItem

Cuando pones .AddItem, le indicas al listbox que te genere un registro, después lo puedes llenar.

Entonces puede ser así:

Me. ListBox1.AddItem i.Cells(b.Row, "B")
ListBox1. List(ListBox1.ListCount - 1, 1) = i. Cells(b.Row, "D")
ListBox1. List(ListBox1.ListCount - 1, 2) = i. Cells(b.Row, "C")
ListBox1. List(ListBox1.ListCount - 1, 3) = i. Cells(b.Row, "A")
ListBox1. List(ListBox1.ListCount - 1, 4) = ComboBox3.Value

o así:

Me. ListBox1. AddItem 
ListBox1. List(ListBox1.ListCount - 1, 0) = i. Cells(b.Row, "B")
ListBox1. List(ListBox1.ListCount - 1, 1) = i. Cells(b.Row, "D")
ListBox1. List(ListBox1.ListCount - 1, 2) = i. Cells(b.Row, "C")
ListBox1. List(ListBox1.ListCount - 1, 3) = i. Cells(b.Row, "A")
ListBox1. List(ListBox1.ListCount - 1, 4) = ComboBox3.Value

No tienes que duplicar la macro, solamente deja la que quieras.

Si es el evento exit, puede ser así:

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
'Por Dante Amor
    'Para salir del textbox lo tienes que dejar en blanco
    If TextBox3.Value = "" Then
        Cancel = False
        Exit Sub
    End If
    '
    Set i = Sheets("INVENTARIO")
    Set b = i.Columns("A").Find(TextBox3.Value, LookAt:=xlWhole)
    If Not b Is Nothing Then
        Me. ListBox1. AddItem
        ListBox1. List(ListBox1.ListCount - 1, 0) = i. Cells(b.Row, "B")
        ListBox1. List(ListBox1.ListCount - 1, 1) = i. Cells(b.Row, "D")
        ListBox1. List(ListBox1.ListCount - 1, 2) = i. Cells(b.Row, "C")
        ListBox1. List(ListBox1.ListCount - 1, 3) = i. Cells(b.Row, "A")
        ListBox1.List(ListBox1.ListCount - 1, 4) = ComboBox3.Value
        Me.TextBox3.Value = ""
        Me.Label11.Caption = ""
        Me.Label12.Caption = ""
        Me.TextBox3.SetFocus
    Else
        MsgBox "El registro no existe"
    End If
    Cancel = True   'para regresar al textbox se pone True
End Sub

Quedó perfecto.

Ahora entiendo lo de AddItem siempre creí que se tenia que poner el primer dato de la matriz, por eso la sobreeescribía cuando no lo necesitaba, creo que aún sigo muy apegado a las fórmulas.

Gracias por tu ayuda!

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas