我想在使用VBA ADO连接的访问中添加组合框中的值。我从谷歌获得编码,但它是2003年及以下的帐户。我有访问2013安装。请告诉我在下面的代码中需要更改的内容
Private Sub UserForm_Initialize()
On Error GoTo UserForm_Initialize_Err
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Databases\StaffDatabase.mdb"
rst.Open "SELECT DISTINCT [Department] FROM tblStaff ORDER BY [Department];", _
cnn, adOpenStatic
rst.MoveFirst
With Me.ComboBox1
.Clear
Do
.AddItem rst![Department]
rst.MoveNext
Loop Until rst.EOF
End With
UserForm_Initialize_Exit:
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
Exit Sub
UserForm_Initialize_Err:
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
Resume UserForm_Initialize_Exit
End Sub
答案 0 :(得分:0)
应该有效。您需要添加adodb的参考。
在您的vba ide中,您必须转到下拉菜单工具 - >参考并选择“Microsoft ActiveX Data Ovjects 2.8 Library”
答案 1 :(得分:0)
检查您的Access DB保存的文件类型。大多数已经切换到.accdb文件类型,所以如果是,你应该使用
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"
另外,请确保引用了Microsoft Access 14.0对象库
答案 2 :(得分:0)
您需要ACE.OLEDB.12.0
提供商,使用AddItem
的速度非常慢。我建议:
Private Sub UserForm_Initialize()
On Error GoTo UserForm_Initialize_Err
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Databases\StaffDatabase.mdb"
rst.Open "SELECT DISTINCT [Department] FROM tblStaff ORDER BY [Department];", _
cnn, adOpenStatic
Me.ComboBox1.Column = rst.GetRows
UserForm_Initialize_Exit:
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
Exit Sub
UserForm_Initialize_Err:
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
Resume UserForm_Initialize_Exit
End Sub