Duda al validar usuario y contraseña en excel vba

Tengo un problema la macro solo funciona bien para el administrador y para la cuenta usuario me muestra el msgbox

Private Sub CommandButton1_Click()
'
    Set h1 = Sheets("USUARIOS")
    '
    If N_Usuario = -1 And N_Clave = "" Then Exit Sub
    '
    existe = False
    For i = 3 To h1.Range("A" & Rows.Count).End(xlUp).Row
        If N_Usuario = h1.Cells(i, "C") And N_Clave = h1.Cells(i, "D") Then
            existe = True
            Exit For
        End If
    Next
    '
    If existe Then
        Unload Me
        FrmInicio.Show
    Else
        MsgBox "EL USUARIO Y LA CLAVE INGRESADA SON INCORRECTOS", vbInformation + vbCritical
        N_Usuario = Empty
        N_Clave = Empty
        N_Usuario.SetFocus
    End If
End Sub
'
Private Sub UserForm_Activate()
    Set hx = Sheets("USUARIOS")
    '
    For i = 3 To hx.Range("A" & Rows.Count).End(xlUp).Row
        N_Usuario.AddItem hx.Cells(i, "C")
    Next i
End Sub

'

'

2 Respuestas

Respuesta
1

En el ejemplo del usuario, estás comparando un texto contra un número, por eso no lo encuentra.

Realicé unos ajustes a tu código:

Private Sub CommandButton1_Click()
'
    Set h1 = Sheets("USUARIOS")
    '
    If N_Usuario.ListIndex = -1 Then
        MsgBox "Falta el usuario"
        Exit Sub
    End If
    If N_Clave = "" Then
        MsgBox "Falta la clave"
        Exit Sub
    End If
    '
    existe = False
    For i = 3 To h1.Range("A" & Rows.Count).End(xlUp).Row
        If IsNumeric(N_Clave) Then w_clave = Val(N_Clave) Else w_clave = N_Clave
        If N_Usuario = h1.Cells(i, "C") And w_clave = h1.Cells(i, "D") Then
            existe = True
            Exit For
        End If
    Next
    '
    If existe Then
        Unload Me
        FrmInicio.Show
    Else
        MsgBox "EL USUARIO Y LA CLAVE INGRESADA SON INCORRECTOS", vbInformation + vbCritical
        N_Usuario = Empty
        N_Clave = Empty
        N_Usuario.SetFocus
    End If
End Sub

N_Usuario.ListIndex = -1, se refiere a que no has seleccionado un dato de la lista del combo.


Sal u dos

Respuesta
1

Es cuestión de formatos. Te va pasar eso con cualquier "password" numérico. Cambia esta línea del siguiente modo:

 If N_usuario = h1.Cells(i, "C") And N_Clave = h1.Cells(i, "D").Text Then

Saludos

Abraham Valencia

PD: Sugiero siempre declarar las variables también.

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas