如何使用ID检查记录,如果记录存在则更新,如果不添加新记录

Cra*_*ara 7 excel ms-access vba excel-vba access-vba

我创建了一个excel userform来收集数据.我已将其连接到Access以转储数据.但是,每次用户按下提交按钮时,我都想更新Access.

基本上我需要Select语句来确定id存在,然后如果它不存在我需要使用INSERT来添加新行.我对任何SQL都很新,所以任何帮助都会很棒.

这是我现在的代码,我需要将它改编为ADO.

Sub Update()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim StrSql As String

Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB

With cnn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open MyConn

Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:="Foam", ActiveConnection:=cnn, _
        CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
        Options:=adCmdTable





StrSql = "SELECT * FROM Foam WHERE FoamID = " & txtMyID
Set rst = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)

If (rst.RecordCount = 0) Then
     DoCmd.RunSQL "INSERT INTO Foam (ID, Part, Job, Emp, Weight, Oven) VALUES " & _
          "(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "', '" & txtField3 & "', '" & txtField4 & "', '" & txtField5 & "' );"

End If

 ' Close the connection
    rst.Close
    cnn.Close
    Set rst = Nothing
    Set cnn = Nothing


End With

End Sub
Run Code Online (Sandbox Code Playgroud)

Han*_*sUp 4

我对您的代码示例进行了足够的修改,使其能够在我的系统上运行,并在 Excel 2007 中测试了该版本。

lngId当我使用与现有记录匹配的值时id,该记录将在记录集中打开,并且我可以更新其字段的值。

当与现有记录lngId不匹配时id,记录集将打开空[ (.BOF And .EOF) = True]。在这种情况下,我添加一条新记录并向其中添加字段值。

Sub Update()
    Const TARGET_DB As String = "database1.mdb"
    Dim cnn As ADODB.Connection
    Dim MyConn As String
    Dim rst As ADODB.Recordset
    Dim StrSql As String
    Dim lngId As Long

    Set cnn = New ADODB.Connection
    MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
    With cnn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .Open MyConn
    End With

    lngId = 4
    StrSql = "SELECT * FROM tblFoo WHERE id = " & lngId
    Set rst = New ADODB.Recordset
    With rst
        .CursorLocation = adUseServer
        .Open Source:=StrSql, ActiveConnection:=cnn, _
                CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
                Options:=adCmdText
        If (.BOF And .EOF) Then
            ' no match found; add new record
            .AddNew
            !ID = lngId
            !some_text = "Hello World"
        Else
            ' matching record found; update it
            !some_text = "Hello World"
        End If
        .Update
        .Close
    End With

    Set rst = Nothing
    cnn.Close
    Set cnn = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)