I work on an Access DB and I have to use a Datasource connection to a SQL Server.
To do that I use the ADODB object with :
-ADODB.Connection
-ADODB.Recordset
Code Up-to-date, following an observation of Ian Kenney
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection
Dim rs As ADODB.Recordset
cnn.ConnectionString = "driver={SQL Server};provider=SQLOLEDB;server=10.****;uid=****readonly;pwd=****readonly;database=****"
cnn.Open
Set rs = cnn.Execute("SELECT [MATRI], [NOMPRE] FROM SCHEME_DB.TABLE WHERE NOMPRE LIKE '*" & Me.Textbox_recherche.Text & "*'")
Me.Liste_choix.RowSourceType = "Table/List"
Me.Liste_choix.Recordset = rs
rs.Close
cnn.Close
(This code (a part of the code) is a way to do an Autocompletion in Access with a TextBox and a ListBox)
And I have an error 91 when I run this code : "Error 91: Object variable or With block variable not set" .
I don't understand how to resolve this issue.
Thanks in advance.
You have closed the recordset and connection before you use it
rs closed here
and the connection is closed here
rs used here
Update From the docs:
SQL INJECTION There is also an sql injection risk by building sql directly from user input.
This question (MS Access prepared statements) shows how to use a parametrised query - might be worth a look.
You told us that code throws Error 91, "Object variable or With block variable not set". Unfortunately, you didn't indicate which line triggers the error. That forces us to guess where the problem lies.
One issue is here:
That attempts an assignment of one object to another. The
=
sign is sufficient for assignments with simple data types ... ieMyVariable = 2
. However you must include theSet
keyword with object assignments.Although you should make that change, I'm not certain that was the cause of error 91; I would have guessed Access would complain "Invalid use of property" instead.
The
SELECT
statement is another problem, but again I'm uncertain whether it contributes to the error you reported. TheWHERE
clause uses aLike
comparison with a pattern which has*
as the wild card character. That query might return what you expect when you run it from DAO. But you're using ADO which treats*
as just an asterisk character without any special meaning. So that query probably returns no rows when you run it from ADO. Replace*
with%
.As general advice, if your code module does not already include
Option Explicit
in its Declarations section, add it. Then run Debug->Compile from the VB Editor's main menu. Fix anything the compiler complains about. Make sure you've done those things before any further troubleshooting.I solved my problem (Error 91), There was three problems : the creation of the ADODB.Connection, the * in the Select (Thanks to HansUp) and the Set for the listbox.recordset (Thanks to HansUp again)
I solved the error :