Private Sub Txt_Cpf_LostFocus()
if opt_cpf.value = true then
If ValidaCPF(Txt_CPF.Text) = False Then
MsgBox "CPF inválido!"
Txt_CPF.SetFocus
Exit Sub
End If
End if
if opt_cnpj.value = true then
If ValidaCGC(Txt_CPF.Text) = False Then
MsgBox "Cnpj inválido!"
Txt_Cpf.SetFocus
Exit Sub
End If
End if
End Sub
' Coloca isto no módulo
Public Function ValidaCGC(CGC As String) As Boolean
If Len(CGC) <> 14 Then
ValidaCGC = False
Exit Function
End If
If CalculaCGC(Left(CGC, 12)) <> Mid(CGC, 13, 1) Then
ValidaCGC = False
Exit Function
End If
If CalculaCGC(Left(CGC, 13)) <> Mid(CGC, 14, 1) Then
ValidaCGC = False
Exit Function
End If
ValidaCGC = True
End Function
'A função que faz o calculo do dígito verificador é a seguinte:
Public Function CalculaCGC(Numero As String) As String
Dim i As Integer
Dim prod As Integer
Dim mult As Integer
Dim digito As Integer
If Not IsNumeric(Numero) Then
CalculaCGC = ""
Exit Function
End If
mult = 2
For i = Len(Numero) To 1 Step -1
prod = prod + (Val(Mid(Numero, i, 1)) * mult)
mult = IIf(mult = 9, 2, mult + 1)
Next
digito = 11 - Int(prod Mod 11)
digito = IIf(digito = 10 Or digito = 11, 0, digito)
CalculaCGC = Trim(Str(digito))
End Function
Public Function ValidaCPF(CPF As String) As Boolean
If Len(CPF) <> 11 Then
ValidaCPF = False
Exit Function
End If
If CalculaCPF(Left(CPF, 9)) <> Mid(CPF, 10, 1) Then
ValidaCPF = False
Exit Function
End If
If CalculaCPF(Left(CPF, 10)) <> Mid(CPF, 11, 1) Then
ValidaCPF = False
Exit Function
End If
ValidaCPF = True
End Function
'A função que faz o calculo do dígito verificador é a seguinte:
Public Function CalculaCPF(Numero As String) As String
Dim i As Integer
Dim prod As Integer
Dim mult As Integer
Dim digito As Integer
If Not IsNumeric(Numero) Then
CalculaCPF = ""
Exit Function
End If
mult = 2
For i = Len(Numero) To 1 Step -1
prod = prod + (Val(Mid(Numero, i, 1)) * mult)
mult = mult + 1
Next
digito = 11 - Int(prod Mod 11)
digito = IIf(digito = 10 Or digito = 11, 0, digito)
CalculaCPF = Trim(Str(digito))
End Function
End Sub