Excel 2010を使用してAccess 2010データベースを(UserForms経由で)照会します。Excel VBA SQLからアクセスできない結果
コードを実行すると、メッセージボックスに「結果なし」(サブメッセージの最後に表示されます)が表示されます。ただし、特定の検索文字列を入力すると、12個のレコードが表示されます。
多分私のSQL文字列が間違っていると思ったので、私はSheet1セルA2にSQLステートメントを書きました。私はその後、Accessデータベースを開いてSQLクエリを作成し、A2セルからSQLステートメントをコピー/ペーストしました。完全に機能しました。 - >これはSQL文ではありません。
なぜデータが見つからないのですか? SQLステートメントは正常に動作します。私はADODB接続を確立しようとするとエラーは出ません。
EDIT:私は他のサブと全く同じデータベース接続設定を使用していますが、正常に動作します。
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