Identify a 3-column PK duplicate in VBA Access

后端 未结 2 1978
傲寒
傲寒 2020-12-22 05:05

I cannot seem to figure out the best way to identify whether my record table already has the unique 3-column combination of the data using VBA.

My table is as follow

2条回答
  •  清歌不尽
    2020-12-22 05:36

    I found 2 general ways of handling this. (1) would include error handling - which I find to be a bad practise. (2) would include DCount function to find the row of data first, then an if condition to determine whether UPDATE or INSERT should be used.

    Hence I used (2) as follows:

    If DCount("*", "sometable", "[col1]= " & Me.col1.value & " AND [col2] = " & Me.col2.value & " AND [col3] = " & Me.col3.value) = 0 Then
        CurrentDB.Execute "INSERT ..."
    Else
        CurrentDB.Execute "UPDATE ..."
    End If
    

    The (1) solution would be something like:

    On Error Resume Next
    CurrentDb.Execute "INSERT ...", dbFailOnError
    If Err.Number = 3022 Then
        Err.Clear        
        CurrentDb.Execute "UPDATE ...", dbFailOnError
    End If
    

提交回复
热议问题