我在Excel中有一個用戶窗體,帶有四個文本框。每個文本框都對應於Access中Table1的一個字段。如何在Excel中查詢和更新Access中的表格
我想要從Access中的表中返回MAX行ID值,將1添加到該值,並將該值顯示在用戶窗體上的文本框中。
在我將值輸入到其他3個文本框之後,我想將數據導出到Access中的Table1。
這一切都可以在同一個子程序中完成嗎?請幫助我將sql語句合併到代碼中的正確位置。
謝謝
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim x As Long, i As Long
Dim PrimaryField As String
Dim MyTable As String
Dim GetLastPrimaryKey As Variant
PrimaryField = "ID"
MyTable = "Table1"
'Erro handler
On Error GoTo errHandler:
'dbPath = ActiveSheet.Range("H500").Value
dbPath = "H:\Annie\File.accdb"
Set cnn = New ADODB.Connection ' Initialise the collection class variable
'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
sql = "SELECT MAX([" & PrimaryField & "]) FROM [" & MyTable & "];"
'two primary providers used in ADO SQLOLEDB —-Microsoft.JET.OLEDB.4.0 —-Microsoft.ACE.OLEDB.12.0
'Object Linking and Embedding, Database
'ADO library is equipped with a class named Recordset
Set rst = New ADODB.Recordset 'assign memory to the recordset
'ConnectionString Open '—-5 aguments—-
'Source, ActiveConnection, CursorType, LockType, Options
rst.Open Source:="Table1", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
'rst.Open sql, cnn
GetLastPrimaryKey = rst.Fields(0).Value
MsgBox (GetLastPrimaryKey)
GetLastPrimaryKey = Arec1.Value
'you now have the recordset object
'alternative code
With rst
.AddNew
.Fields("ID").Value = Arec1
.Fields("patient").Value = Arec2
.Fields("test").Value = Arec3
.Fields("CommentTxt").Value = Arec4
.Update
End With
'clear the userform values
For x = 1 To 4
UserForm1.Controls("Arec" & x).Value = ""
Next
'add the next user ID
'Me.Arec1 = Sheet1.Range("J3").Value
' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
'commuinicate with the user
MsgBox " The data has been successfully sent to the access database"
On Error GoTo 0
Exit Sub
errHandler:
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure cmdAdd"
End Sub
請原諒我,但爲什麼不在MS Access中做所有事情?爲什麼重新創建Excel中的整個用戶界面和查詢處理器,因爲Access本身執行了此類操作。 – Parfait
原始報告被轉儲到Excel中。另外,我與拒絕使用Access的人一起工作。他們害怕它。 :) – user3781528
啊,是的,Excel的流行性和易用性是它自己的缺點,因爲人們將它用於太陽下的一切!如果你在Access中設計一個好用戶界面,用戶不應該害怕,因爲他們每天在網站上使用命令按鈕,下拉菜單,文本框!另外,Access表單比Excel用戶表單更具交互性。 – Parfait