您好我正在尝试编写一个从excel表单获取用户输入并将其添加到访问表的宏。使用以下代码:
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim wsh As Excel.Application
Set cnn = "db.accdb.connection"
Set rst = New ADODB.Recordset
rst.Open "table", cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
With rst
.AddNew
.Fields("column1").Value = textboxvar
.Update
End With
以前定义过textboxvar。但它不会工作,我不知道为什么。
答案 0 :(得分:0)
声明,设置,打开连接的示例:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; DataSource='C:\path\databasename.accdb'"
rs.Open "SELECT * FROM MyTable", cn, adOpenKeyset, adLockOptimistic
答案 1 :(得分:0)
搜索了很长时间之后。该主题中投票最高的帖子已经回答了这个问题: Using Excel VBA to export data to MS Access table
这仅需要更新才能与Access 2016一起使用:
Public Sub UploadExcel()
Set cn = CreateObject("ADODB.Connection")
dbPath = 'type your database path in here
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
ssql = "INSERT INTO TableName ([Field1], [Field2], [Field3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub