Invalid Operation Setting Result Set Object VBA - vba

Hi Maybe someone can enlighten me here. Using VBA code and I want to include a check for zero record count from a query and it now fails at the code I added where it was fine before. Code below shows set up:
Sub MySub()
Dim db As DAO.Database
Set db = CurrentDb()
Dim qdf As DAO.QueryDef
Dim sqlQry As String
Dim rst As DAO.Recordset
sqlQry = "My Query String"
If DLookup("Name", "MSysObjects", "Name= 'QueryName1'") <> "" Then
Set qdf = CurrentDb.QueryDefs("QueryName1")
qdf.SQL = sqlQry
Else
Set qdf = CurrentDb.CreateQueryDef("QueryName1", sqlQry)
End If
Set rst = db.OpenRecordset(qdf.Name) << FAILS HERE
If rst.RecordCount <> 0 Then
DoCmd.OpenQuery (qdf.Name)
Else
MsgBox "no data returned"
Exit Sub
End If
Set qdf = Nothing
Set db = Nothing
End Sub
It fails on the line shown above with run "time error 3219 Invalid Operation". the only thing I changed is added an object reference for business objects for another part of the code, not this part. It ran fine before and only other change is start of a new sub below this code but running only this bit code (not the whole module) in debug mode it came up with the error.

Related

How to read from Access databases into visualbasic

I would like to be able to see a line of text in a textbox from an access database.
I know how to write and delete data from the database through visual basic code, but how can you read data?
If for example, I have something that says "Hi" saved in my database. How can I use a line of code in visual basic to read "Hi" and then show it in a textbox or simply in the console app?
Sub SayHi()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim strCity As String
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("SELECT Foo FROM tblCustomers WHERE Foo = " & "'Hi'")
'Begin row processing
Do While Not rst.EOF
MsgBox rst!Foo
Loop
'Cleanup
rst.Close
Set rst = Nothing
End Sub

How to add YES/NO checkbox column to existing table using VBA?

To begin with, I'm quite new to access.
I have a table , call it 'A'. I also have a form with a button which triggers an event when pushed. Using VBA I want to add a YES/NO column to 'A'.
I have accomplished that with the following code:
Dim strSQL As String
strSQL = "ALTER TABLE 'A' ADD COLUMN test YESNO;"
CurrentDb.Execute strSQL
But it's just zeros on each row. I want to have the checkbox style. I know how to set it manually in "Display Control" but since I'm creating a "program" for a friend I want it to be set automatically when the button is pushed.
I have tried working around this problem for a while now and to be honest I don't even remember all the results I have gotten, all I know is that it's not what I want.
On different forums, with posts as old as 2003, I find some people recommending changing the "fld.CreateProperty..." to "fld.Append..." and vice versa. Not working for me.
The code following below is what I have tried but I get:
"Run-time error '3421' Data type conversion error."
Set db = CurrentDb
Set td = db.TableDefs("A")
Set fld = td.Fields("test")
Set prp = fld.CreateProperty("DisplayControl", dbInteger, 106)
fld.Properties.Append prp
After some help in the comments my VBA code looks like this:
Private Sub Command13_Click()
Dim strSQL As String
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim prp As DAO.Property
Set dbs = CurrentDb
strSQL = "ALTER TABLE table ADD COLUMN test YESNO;"
dbs.Execute strSQL
Set tdf = dbs.TableDefs("table")
Set fld = tdf.Fields("test")
Set prp = fld.CreateProperty("DisplayControl", dbInteger, 106)
fld.Properties.Append prp`
End Sub
When this code runs from a press of a button, I get the error
"Compile error: User-defined type not defined".
The debugger highlights the following yellow:
Private Sub Command13_Click()
and the following blue:
Dim dbs As DAO.Database
Your SQL syntax is not correct. Once corrected, this runs smoothly and as intended here:
Public Function SetFieldDisplay()
Dim strSQL As String
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim prp As DAO.Property
Set dbs = CurrentDb
strSQL = "ALTER TABLE TestTable ADD COLUMN DisplayTest YESNO;"
dbs.Execute strSQL
Set tdf = dbs.TableDefs("TestTable")
Set fld = tdf.Fields("DisplayTest")
Set prp = fld.CreateProperty("DisplayControl", dbInteger, 106)
fld.Properties.Append prp
End Function

Error executing a saved Access query that depends on parameter values from a form

I'm trying to simply open a query and SELECT everything from it. The query requires FROM and TO dates. I have a frmA through which I pass the parameters to the query. I open the frmA and put in 2 dates. Funny thing is, when I do docmd.openQuery "qryInsurance" it opens it wihout a problem, however, when I try to Select * from qryInsurance, it tells me that it's expecting 2 parameters.
here is the code:
Public Function CountFollowup() As Boolean
On Error GoTo error_handler:
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim strsql As String
Dim rcount As Integer
Set DB = CurrentDb
CountFollowup = False
DoCmd.OpenQuery "qryInsurance"
strsql = "SELECT * FROM [qryInsurance];"
'CurrentDb.Execute "Delete * FROM temp_InsData"
Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs2 = CurrentDb.OpenRecordset("temp_InsData")
Debug.Print strsql
Exit Function
error_handler:
MsgBox Err.Number & " - " & Err.Description
End Function
It seems qryInsurance includes references to form controls, maybe like this ... Forms!frmA!From
Those references are resolved when you use DoCmd.OpenQuery, but not when you use the DAO.Database.OpenRecordset method. With OpenRecordset, they are interpreted as parameters for which you have not supplied values.
If you open the query's QueryDef and then feed each parameter Name to Eval(), it will give you the values of those form controls ... so you can then supply them as the values for the parameters.
That description may not be easy to follow, but the code is pretty easy.
Add these variable declarations before Set db = CurrentDb ...
Dim db As DAO.Database
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Dim CountFollowup ' As what? Boolean?
Then later ...
Set db = CurrentDb
CountFollowup = False
'DoCmd.OpenQuery "qryInsurance"
'strsql = "SELECT * FROM [qryInsurance];"
'CurrentDb.Execute "Delete * FROM temp_InsData"
Set qdf = db.QueryDefs("qryInsurance")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next
'Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs1 = qdf.OpenRecordset(dbOpenSnapshot)
' and the rest ...

Updating table with VBA

I have been struggling with getting this code to work for a few days. If you could offer any solutions I would really appreciate it.
Private Sub Command0_Click()
If IsNull(NewSupBox.Value) Or IsNull(NewNumberBox.Value) Then
MsgBox ("All fields must be filled")
GoTo ErrorExit
End If
If Not IsNull(DLookup("SupplierNumber", "SupGenInfo ", "SupGenInfo.SupplierNumber =" & NewSupBox)) = Then
MsgBox ("This supplier number already exists. You can edit the current record on the Edit supplier page.")
GoTo ErrorExit
End If
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("select * from SupGenInfo")
rec.AddNew
rec("SupplierNumber") = Me.NewSupBox.Value
rec("SupplierName") = Me.NewNameBox.Value
rec.Update
Set rec = Nothing
Set db = Nothing
MsgBox "Records added successfully."
ErrorExit:
End Sub
Edit: Forgot to mention that I am not getting any error message. The command will simply not add a new record to my table.
Edit2: The code above will output the msg "Records Added Successfully" when i remove the following block of code.
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("SupGenInfo")
rec.AddNew
rec("SupplierNumber") = Me.NewSupBox
rec("SupplierName") = Me.NewNameBox
rec.Update
Set rec = Nothing
Set db = Nothing
It is when this code is included that my command click becomes unresponsive.
I believe, you are reading a table (for display purposes) with your select * ... statement, then you're adding a new record to that list rather than the actual database. When you open OpenRecordset, just supply the table name, not a whole SQL query shebang...
I created a new table, so edit this code to match your parameters/values, otherwise this has been tested to work:
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("Table1")
rec.AddNew
rec("Field1") = 1234
rec("Field2") = "blah2"
rec("Field3") = "blah3"
rec.Update
Set rec = Nothing
Set db = Nothing
Hope this helps.

Terminating Query If Not Connection

I have a code that uploads data to a SQL server database, I am trying to add in an IF line of code saying if there is a connection then to continue, but if there is not a connection then to END. I am having a difficult time figuring out the wording and placement though. The beginning of the code that connects is:
Public Function Update()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim err As DAO.Error
Const ConnectionString = _
"ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=SERV;" & _
"Database=DB;" & _
"UID=ID;" & _
"PWD=PWD;"
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
Set rs = CurrentDb.OpenRecordset("CDData", dbOpenTable)
qdf.Connect = ConnectionString
Do While Not rs.EOF
While one can simple attempt to execute any query or command, the “time out” and delay to test for an active connection can result in a VERY LONG delay. As a result a wonderful trick exists that uses a DIFFERENT connection mechanism in Access and thus “reduces” the potential VERY long delay when attempting to use a saved query that is based on linked tables. (that "different" connection system occurs when you create a queryDef as opposed to a linked table or a query based on a linked table to sql server)
The follow code will return true or false if you have a working SQL connection:
Function TestLogin(strcon As String) As Boolean
On Error GoTo TestError
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("")
qdf.Connect = strcon
qdf.ReturnsRecords = False
'Any VALID SQL statement that runs on server will work below.
qdf.SQL = "SELECT 1 as test"
qdf.Execute
TestLogin = True
Exit Function
TestError:
TestLogin = False
Exit Function
End Function
So in code you now with your connection string code go:
If TestLogIn(strConn) = false then
msgbox "no connection or logon invalid"
exit sub
End If
' record processing code goes here for successful logon/connection.