我创建了一个 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/