Private Sub Device_BeforeUpdate(Cancel As Integer)
Dim ExistingDevice As String
Dim CountOfDevice As String
Dim ExistingJoin As String
Dim ExistingUser As String
Dim ExistingUserName As String
Dim Msg, Style, Title, Help, Ctxt, Response, MyString
'check for deletion
If IsNull(Me![Device]) Then
UpdateSql = "UPDATE tblJoin"
SetSql = "Set Device = Null"
WhereSql = "Where [JoinID] = Me!JoinID"
strsql = UpdateSql & vbCrLf & SetSql & vbCrLf & WhereSql
DoCmd.RunSQL (strsql)
Else
'check if duplicate value
CountOfDevice = DCount("[Device]", "tblJoin", "[Device] = " & Me!Device)
If CountOfDevice > 0 Then
'retrive existing device in tblJoin
ExistingDevice = DLookup("[Device]", "tblJoin", "[JoinID] = " & Me!JoinID)
'check if chosen device is current device
If ExistingDevice <> Me!Device Then
'retrieve the UserID who has device already
ExistingUser = DLookup("[User]", "tblJoin", "[Device] = " & Me!Device)
'retrieve the existing username
ExistingUserName = DLookup("[UserName]", "tblUser", "[UserID] = " & ExistingUser)
'retrive current username
CurrentUsername = DLookup("[UserName]", "tblUser", "[UserID] = " & Me!User)
Msg = "This device currently belongs to " & ExistingUserName & ". Do you wish to transfer the device to " & CurrentUsername
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "Duplicate warning"
Help = "DEMO.HLP"
Ctxt = 1000
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then
'retrieve the DeviceID for duplicate value
ExistingJoin = DLookup("[JoinID]", "tblJoin", "[Device] = " & Me!Device)
'delete Device from existing User
UpdateSql = "UPDATE tblJoin"
SetSql = "Set Device = Null"
WhereSql = "Where [JoinID] = ExistingJoin"
strsql = UpdateSql & vbCrLf & SetSql & vbCrLf & WhereSql
DoCmd.RunSQL (strsql)
'check new value in table
ExistingDevice = DLookup("[Device]", "tblJoin", "[JoinID] = " & ExistingJoin)
'set device for current user
UpdateSql = "UPDATE tblJoin"
SetSql = "Set Device = Me!Device"
WhereSql = "Where [JoinID] = Me!JoinID"
strsql = UpdateSql & vbCrLf & SetSql & vbCrLf & WhereSql
DoCmd.RunSQL (strsql)
'audit here
Else
Cancel = True
End If
Else
UpdateSql = "UPDATE tblJoin"
SetSql = "Set Device = Me!Device"
WhereSql = "Where [JoinID] = Me!JoinID"
strsql = UpdateSql & vbCrLf & SetSql & vbCrLf & WhereSql
DoCmd.RunSQL (strsql)
End If
Else
UpdateSql = "UPDATE tblJoin"
SetSql = "Set Device = Me!Device"
WhereSql = "Where [JoinID] = Me!JoinID"
strsql = UpdateSql & vbCrLf & SetSql & vbCrLf & WhereSql
DoCmd.RunSQL (strsql)
'audit here
End If
End If
End Sub