Como utilizar validación de datos en VB

He estado buscando la manera de evitar que en una hoja excel se repitan algunos datos al momento de ingresarlos. Estoy usando un formulario para capturar los datos, pero al momento de usar el contar si, no me funciona. Agradeceré mucho su ayuda

El código que estoy usando para guardar el siguiente

Private sub commandbutton1_click ()                  Dim fila as Long                                                        Dim duplicados se boolean                                  Fila= application.worksheet.function.countA(range ("D:D")) +1                                                      duplicados = false                                                  Cells(fila, 4).value=userform1.textbox1.value   Cells(fila, 6).value=userform1.textbox2.value  msgbox "registro exitoso" 

*Ahora bien aclaró que el rango que quiero verificar es la columna D, de tal modo que me impida registrar si el dato ya existe*

2 respuestas

Respuesta
1

Te anexo la macro con las validaciones

Private Sub commandbutton1_click()
    Dim fila As Long
    'VALIDACIONES
    If TextBox1.Value = "" Then
        MsgBox "Captura un dato en textbox1", vbExclamation
        TextBox1.SetFocus
        Exit Sub
    End If
    '
    Set b = Columns("D").Find(TextBox1.Value, lookat:=xlWhole)
    If Not b Is Nothing Then
        MsgBox "El dato ya existe", vbCritical
        Exit Sub
    End If
    '
    'AGREGAR REGISTRO
    fila = Range("D" & Rows.Count).End(xlUp).Row + 1
    Cells(fila, "D").Value = UserForm1.TextBox1.Value
    Cells(fila, "F").Value = UserForm1.TextBox2.Value
    MsgBox "registro exitoso", vbInformation
    TextBox1.Value = ""
    TextBox2.Value = ""
End Sub

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

Prueba con esta macro

Private Sub CommandButton1_Click()
valor = TextBox1.Text
cuenta = WorksheetFunction.CountIf(Range("d:d"), valor) > 0
fila = WorksheetFunction.CountA(Range("d:d")) + 1
If cuenta Then MsgBox ("registro ya existe"), vbCritical, "AVISO DE DUPLICADOS": GoTo sal
Cells(fila, 4).Value = UserForm1.TextBox1.Value
Cells(fila, 6).Value = UserForm1.TextBox2.Value
MsgBox ("registro capturado con exito"), vbInformation, "AVISO"
sal:
End Sub

¡Gracias! De verdad no he probado esto, lo haré a lo mejor para tener varios métodos, pero gracias x tomarse la molestia de responder a mi duda. 

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas