使用Excel 2010查詢Access 2010數據庫(通過UserForms)。來自Access的Excel VBA SQL沒有結果
當我執行代碼時,我得到我的消息框「無結果」(稱爲在子結尾附近)。但是,當我輸入特定的搜索字符串時,應該有12條記錄拉起來。
我想也許我的SQL字符串不正確,所以我寫了SQL語句給Sheet1 Cell A2。然後我打開了我的Access數據庫,創建了一個SQL查詢,並從單元格A2複製/粘貼了SQL語句 - 它完美地工作。 - >所以這不是SQL語句。
爲什麼我的代碼沒有找到數據? SQL語句正常工作。當我嘗試建立ADODB連接時,我沒有收到任何錯誤。
編輯:我使用完全相同的數據庫連接設置在另一個子,它工作正常。
Private Sub searchAllInJobs(searchStr As String)
Dim con As Object, rs As Object, accessFile As String, strTable As String, sql As String, keyStr As String, i As Integer
accessFile = "******************" '<--hidden on purpose
Set con = CreateObject("ADODB.connection")
If Err.Number <> 0 Then
MsgBox "Failed database connection", vbCritical, "Connection Error"
Exit Sub
End If
On Error GoTo 0
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
'Wild card string
keyStr = """*" & searchStr & "*"""
'I have tested this SQL statement in the Access database and works great
sql = "SELECT * FROM tbl_job_tables WHERE ([MODELNO] LIKE " & keyStr & ");"
'Write the SQL to a cell, to make sure the statement was constructed properly
Sheets("Sheet1").Range("A2").value = sql
Set rs = CreateObject("ADODB.Recordset")
'Open the database recordset from the SQL statement
rs.Open sql, con
'Clear the current ListBox
Me.list_SearchJobs.Clear
i = 0
If Not (rs.EOF and rs.BOF) Then
'Move to the first item
rs.MoveFirst
'While going through the records, if you haven't reached the End-of-file then...
Do While Not rs.EOF
With Me.list_SearchJobs
.AddItem
.List(i, 0) = rs!JOB_NUM
.List(i, 1) = rs!customer
.List(i, 2) = rs!MODELNO
.List(i, 3) = rs!CREATE_DATE
End With
i = i + 1
rs.MoveNext
Loop
'Close the recordset and database connection
rs.Close
con.Close
'Set the objects to "Nothing" (clears the cache)
Set rs = Nothing
Set con = Nothing
Else
'Close the recordset and database connection
rs.Close
con.Close
'Set the objects to "Nothing" (clears the cache)
Set rs = Nothing
Set con = Nothing
MsgBox "No Results", vbCritical, "No results"
Exit Sub
End If
End Sub
你的錯誤信息**,而不是是否可以」連接到數據庫。在測試之前移動'con.Open'語句以查看是否可以打開它,然後讓我們知道是否收到「數據庫連接失敗」消息。 – YowE3K
好的。不,沒有產生錯誤。謝謝你抓住那個。 – Sanya