Below is the code you need. You'll have to substitute your actual field/table names where you see
tblTest
Brand
Model
Version
and you'll also have to have a field named UK (unique key) on your tblTest (or rename it in both code and table) for this to work.
Code:
Dim db As Database
Dim rstBrand As Recordset
Dim rstModel As Recordset
Dim rstVersion As Recordset
Dim sSQL As String
Dim sBrand As String
Dim sModel As String
Dim sVersion As String
Dim sUK As String
Dim iMax As Integer
Dim iVersion As Integer
Set db = CurrentDb
sSQL = "SELECT Brand FROM tblTest GROUP BY Brand ORDER BY Brand"
Set rstBrand = db.OpenRecordset(sSQL)
If rstBrand.RecordCount > 0 Then
Do While rstBrand.EOF <> True
sBrand = rstBrand.Fields("Brand")
Debug.Print sBrand
sSQL = "SELECT Model FROM tblTest WHERE ((Brand) = '" & sBrand & "' AND (UK) Is Null) GROUP BY Model ORDER BY Model"
Set rstModel = db.OpenRecordset(sSQL)
If rstModel.RecordCount > 0 Then
'determines current maximum integer assigned to this brand/model
If DCount("[UK]", "tblTest", "[Brand] = '" & sBrand & "' AND [Model] = '" & rstModel.Fields("Model") & "'") = 0 Then
iMax = 1
Else
iMax = CInt(Mid(DMax("UK", "tblTest", "[Brand] = '" & sBrand & "' AND [Model] = '" & rstModel.Fields("Model") & "'"), 3, 4)) + 1
End If
Do While rstModel.EOF <> True
sModel = rstModel.Fields("Model")
Debug.Print " " & sModel
sSQL = "SELECT Version, UK FROM tblTest WHERE ((Brand) = '" & sBrand & "' AND (Model) = '" & sModel & "' AND (UK) Is Null)"
Set rstVersion = db.OpenRecordset(sSQL)
If rstVersion.RecordCount <> 0 Then
'determines current maximum integer assigned to this version
If DCount("[UK]", "tblTest", "[Brand] = '" & sBrand & "' AND [Model] = '" & sModel & "'") = 0 Then
iVersion = 1
Else
iVersion = CInt(Right(DMax("UK", "tblTest", "[Brand] = '" & sBrand & "' AND [Model] = '" & sModel & "'"), 2)) + 1
End If
Do While rstVersion.EOF <> True
sVersion = rstVersion.Fields("Version")
Debug.Print " " & sVersion
sUK = UCase(Left(sBrand, 2)) & Right("0000" & iMax, 4) & "_" & Right("00" & iVersion, 2)
rstVersion.Edit
rstVersion!UK = sUK
rstVersion.Update
iVersion = iVersion + 1
Debug.Print " " & sUK
rstVersion.MoveNext
Loop
End If
rstVersion.Close
iMax = iMax + 1
rstModel.MoveNext
Loop
End If
rstModel.Close
rstBrand.MoveNext
Loop
End If
rstBrand.Close
Set db = Nothing