Hi,
I am trying to execute an Access 2007 saved query from my VBA code, and am encountering some weirdness. The function below should return a recordset from the specified saved query. I have hard-coded the query name and the parameters for simplicity.
Using ADOX, I can see what the query parameters are, and my function loads each parameter, including trimming the length of string-type parameters if needed.
The proper record IS being returned in the recordset. I have the particular fields, which I can access by:
Dim rs As ADODB.Recordset
Set rs=MyTest
? rs.Fields(0)
? rs.Fields(fieldName)
, etc.
The weirdness is that I can't get the AbsolutePosition or RecordCount properties after invoking the function. They both return -1. My calling code wants to test for a valid result by saying
If rs.AbsolutePosition = 1 Then
.....
But, this isn't working. I've tried playing with properties of the recordset object, the command object & the catalog object, to no avail.
Any ideas?
Thanks...
Code:
Friend Function myTest() As ADODB.RecordSet
Dim cmd As New ADODB.Command
Dim rs As ADODB.RecordSet
Dim cat As New ADOX.Catalog
Dim parmType As ADODB.DataTypeEnum
Dim parmsSupplied As Integer
Dim parmVal As Variant
Dim parmNo As Integer
Dim tries As Integer
Dim params() As Variant
Const my_query As String = "GetPellAmountForProfile"
On Error GoTo err_handler
params = Array(1519, 500)
cat.ActiveConnection = CurrentProject.Connection
tries = 0
find_cmd:
'If query not found as an ADOX Procedure, try finding it as an ADOX View.
If tries = 0 Then
Set cmd = cat.Procedures(my_query).Command
Else
Set cmd = cat.Views(my_query).Command
End If
parmsSupplied = UBound(params) - LBound(params) + 1
If parmsSupplied = cmd.Parameters.Count Then
For parmNo = 0 To cmd.Parameters.Count - 1
With cmd.Parameters(parmNo)
parmVal = params(parmNo)
Select Case .Type
Case adBSTR, adChar, adLongVarChar, adLongVarWChar, adVarChar, adVarWChar, adWChar
parmVal = Left$(parmVal, .Size - 1)
End Select
.Value = parmVal
End With
Next
Set rs = cmd.Execute
Set myTest = rs
Set cmd = Nothing
Set rs = Nothing
Set cat = Nothing
Else
myError = "Wrong number of parameter values supplied. Expected " & CStr(cmd.Parameters.Count)
End If 'Right number of parameters supplied.
exit_handler:
On Error Resume Next
Set cat = Nothing
On Error GoTo 0
Exit Function
err_handler:
'Could be a view, not a procedure.
If Err.Number = 3265 Then
If tries = 0 Then
tries = 1
Resume find_cmd
Else
update_query_params = False
Resume exit_handler
End If
Else
update_query_params = False
myError = Err.Description
Resume exit_handler
End If
End Function