我正在尝试为公司创建工作订单系统,我只能使用MS Access。我想在工作订单ID列中进行编码。此列将基于2个组合框选项:
BuildingName TargetDepartment
我需要一些VBA代码来查询表中的WOID列以检索下一个数字。条件如下例所示:
WOID BuildingName TargetDepartment BUILDA-DEPTA-1 BUILDA DEPTA BUILDA-DEPTB-1 BUILDA DEPTB BUILDA-DEPTA-2 BUILDA DEPTA
VBA代码将查询WOID列,并查明是否存在同一建筑物和部门的工单,然后将结尾处的数字增加1.但是如果没有与建筑物名称和目标部门匹配的WOID ,它会创建第一个条目。
因此,如果找到匹配的buildingname和targetdepartment:MaxNumber +1 如果它没有找到匹配的buildingname和targetdepartment:1
感谢您的帮助!
答案 0 :(得分:-1)
您可以使用DLookUp
:
where_condition = "[WOID] Like '" & Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-*'"
existing_woid = Nz(DLookUp("[WOID]","[TableName]", where_condition),"")
If(existing_woid = "") Then
next_id = 1
Else
next_id = DMax("Mid([WOID], InStrRev([WOID],""-"")+1)","[TableName]", where_condition) + 1
End If
woid = Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-" & next_id
你也可以在一行中完成,但我认为最好看看这背后的思维方式。
编辑(带记录锁定)
Dim s as String, rs as Recordset
s = " Select [WOID] From [TableName] " & _
" Where [WOID] Like '" & Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-*'" & _
" Order By 1 Desc"
'This will restrict table access
Set rs = CurrentDb.OpenRecordset(s, dbOpenDynaset, dbDenyRead + dbDenyWrite)
If rs.RecordCount > 0 Then
next_ind = Mid(rs(0), InStrRev(rs(0), "-") + 1) + 1
Else
next_ind = 1
End If
rs.AddNew
rs.Fields("WOID") = Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-" & next_ind
rs.Update
rs.Close
Set rs = Nothing