我创建了一个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
答案 0 :(得分: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
答案 1 :(得分:1)
使用VBA,以下是如何查询某个ID
以检查其是否存在的示例。如果没有,则通过INSERT
语句添加:
Dim rs As DAO.Recordset
Dim StrSql As String
StrSql = "SELECT * FROM MyTable WHERE ID = " & txtMyID
Set rs = CurrentDb.OpenRecordset(StrSql, dbOpenDynaset)
If (rs.RecordCount = 0) Then
DoCmd.RunSQL "INSERT INTO MyTable (ID, Field1, Field2) VALUES " & _
"(" & txtID & ", '" & txtField1 & "', '" & txtField2 & "');"
End If