2015-09-30 70 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