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

标签 ms-access excel vba

我创建了一个 Excel 用户表单来收集数据。我已将其连接到 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

最佳答案

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

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

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

关于ms-access - 如何使用ID检查记录,如果记录存在则更新如果不添加新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21706069/

相关文章:

sql - MS Access 中的条件默认值

sql - 对于 SQL 中最后一个表中的每个元素,如何返回一个表中实体的值,该值小于但最接近另一个表中的值?

c# - 从 Access 2003 调用托管代码

excel - 查找最后一个大于 0 之前的单元格

c# - 将 CSV 文件复制到 MS Access 表

wpf - VSTO 应用部署错误

excel - 将连接放在计数内 if

python - 如何使用 Pandas 或 Spark Dataframe 展平嵌套 Excel 数据?

Excel VBA 将 XL-2007 启用宏的工作簿复制为不带宏的 excel-2003 文件

internet-explorer - 使用 VBA Excel 通过更改下拉值来导航网站