2015-09-30 73 views
0

我是Excel VBA的新手。我有一个用户表单,我试图填写那些AMO员工的名字。我有一个名为Ofc的数据库。根据这个我有一个表EmployeeDetails。主键是PeoplesoftId从查询表中提取员工详细信息的SQL查询

这里的结构和Employee表的内容:

PeoplesoftId Nameofemployee RacifId Employeeid Designation 
43243309  Maddala   V43309 99651823 AMO 
43243310  Abhishek  A43301 99651824 AMO 
43243311  Atanu   A43311 99651825 MO 
43243312  Rajiv   R43312 99651826 CSE 

这是我到目前为止已经编写的代码:你需要通过在每个记录移动

Dim cnn As ADODB.Connection 'dim the ADO collection class 
Dim rs As ADODB.Recordset 'dim the ADO recordset class 
Dim dbPath As String 
Dim SQL As String 
Dim i As Integer 
Dim var 
'add error handling 
On Error GoTo errHandler: 
'Disable screen flickering. 
Application.ScreenUpdating = False 
dbPath = "E:\office_hsbc\ofc.accdb" 
var = "AMO" 
Set cnn = New ADODB.Connection ' Initialise the collection class variable 
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath 
cnn.Open 
SQL = "SELECT Nameofemployee FROM EmployeeDetails where Designation= '" & var & "'" 
Set rs = New ADODB.Recordset 'assign memory to the recordset 
rs.Open SQL, cnn 
If rs.EOF And rs.BOF Then 
rs.Close 
cnn.Close 
'clear memory 
Set rs = Nothing 
Set cnn = Nothing 
'Enable the screen. 
Application.ScreenUpdating = True 
MsgBox "There are no records in the recordset!", vbCritical, "No Records" 
Exit Sub 
End If 
For i = 0 To rs.Fields.Count - 1 
    comboamo.AddItem rs.Fields(i).Value, i 
Next 
rs.Close 
cnn.Close 
Set rs = Nothing 
Set cnn = Nothing 
MsgBox "Congratulation the data has been successfully Imported", vbInformation, "Import successful" 
'error handler 
On Error GoTo 0 
Exit Sub 
errHandler: 
'clear memory 
Set rs = Nothing 
Set cnn = Nothing 
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Import_Data" 
+0

请解释究竟是什么问题? –

回答

0

记录。目前,您正试图从单个记录中读取所有字段,但您的查询只返回一个字段。试试这个:

MsgBox "There are no records in the recordset!", vbCritical, "No Records" 
Exit Sub 
End If 
i = 0 
Do Until rs.EOF 
    comboamo.AddItem rs.Fields("Nameofemployee").Value, i 
    rs.MoveNext 
    i = i + 1 
Loop 
rs.Close 
+1

谢谢你这个作品。赞赏你的帮助 – user3395230