我目前正在使用 Excel VBA 制作一个简单的库存系统应用程序。我有一个用户表单来获取输入,我想将导入数据保存到几个 Microsoft Access 表中。
我正在尝试从用户窗体中提取数据并在用户按 Enter 时将其输入到访问表中。当我运行此代码时,会使用表 ID 创建一条新记录,但我尝试导入的两条记录留空。
Public Sub AddDatabaseEntry()
'Initialize all variables
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim orderNum As String
Dim orderDate As String
orderNum = txtOrderNum
orderDate = txtDate
stDB = "Data Source= " & ThisWorkbook.Path & "\obsDatabase.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
'Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
'SQL Statement of what I want from the database
stSQL = "INSERT INTO Orders (OrderNumber, OrderDate) " & _
"Values ('" & orderNum & "', '" & orderDate & "')"
Set rs = cn.Execute(stSQL)
'Looping through the records I pulled and inserting the data into the comboBox
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Private Sub btnAdd_Click()
AddProduct
AddDatabaseEntry
End Sub