Como evitar que un campo correlativo 001/2013 se repita

Tengo un código para hacer que un nº de expediente vaya incrementado automáticamente en 1 durante 2013, 001/2013, 002/2013 y así sucesivamente y cuando cambie el año empiece de nuevo por 1, 001/2014, etc...

Si el nuevo registro va ordenado por fecha todo va bien, el NUMEXPTE va perfecto, el problema viene cuando se añade un nuevo registro con una fecha anterior al último registro guardado, ya que toma la fecha anterior a la que he indicado en este último registro para asignarle el NUMEXPTE, ignorando que este ya existe. Ejemplo
001/2013 10/05/2013
002/2013 14/05/2013
003/2013 19/05/2013
002/2013 11/05/2013
003/2013 12/05/2013
004/2013 13/05/2013
Este es el código que utilizo:

Private Sub
txtFecha_LostFocus()
Dim db As Database
Dim rs1 As Recordset
Dim rs2 As Recordset
Dim baño As String
Dim vCorrelativo As Integer
Set db = CurrentDb
Set rs1 =
db.OpenRecordset("Select Max(FECHA) as MáximatxtFecha from ENTRADA")
If IsNull(rs1!MáximatxtFecha) Then
Me.NUMEXPTE = "001/" & Trim(Str(Year(Me.FECHA)))
Else
Set rs2 =
db.OpenRecordset("Select Max(NUMEXPTE) as MáximoCorrelativo from ENTRADA
where Fecha=cdate('" & rs1!MáximatxtFecha & "')")
baño = Right(rs2!MáximoCorrelativo, 4)
vCorrelativo = Val(Left(rs2!MáximoCorrelativo, 3))
If baño = Trim(Str(Year(Me.FECHA))) Then
vCorrelativo = vCorrelativo
+ 1
Me.NUMEXPTE = String(3 -
Len(Trim(Str(vCorrelativo))), "0") & Trim(Str(vCorrelativo))
& "/" & baño
Else
vCorrelativo = 1
baño = Trim(Str(Year(Me.FECHA)))
Me.NUMEXPTE = String(3 -
Len(Trim(Str(vCorrelativo))), "0") & Trim(Str(vCorrelativo))
& "/" & baño
End If
End If
Me.Refresh
End Sub

Experto que alguien me pueda ayudar.

1 respuesta

Respuesta
1

Prueba a ver si te gusta más este código:

Dim rs As Recordset
Dim txtSql As String
Dim n As Integer
txtSql = "select max(NUMEXPTE) as maxNum from Entrada " & _
"where NUMEXPTE like '*/" & Format$(Me.fecha, "yyyy") & "'"
Set rs = CurrentDb().OpenRecordset(txtSql)
rs.MoveFirst
If IsNull(rs!maxnum) Then
n = 0
Else
n = Val(Left$(rs!maxnum, 3))
End If
rs.Close
Me.NUMEXPTE = Format$(n + 1, "000") & "/" & Format$(Me.fecha, "yyyy")

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas