SQL with variables in currentDb.OpenRecordset (1 Viewer)

Chrisopia

Registered User.
Local time
Today, 15:52
Joined
Jul 18, 2008
Messages
279
I am trying to create a function which will use variables to extract which fields are needed from an SQL statement and therefore retrieved via OpenRecordSet.

Code:
Public Function DoSomething(pName As String)
Dim PrtSthg As String
Dim pr As DAO.Recordset
Dim tray As String

PrtSthg = "SELECT ID, Branch, " & pName & " FROM tblBranch WHERE ID=" & BranchhID & ";"
Set pr = CurrentDb.OpenRecordset(PrtSthg)

tray = pr!pName
msgBox tray


I know usually, with recordset, it's as easy as pointing to the field using '!'
For example, if I used the function:
Code:
DoSomething("truck")
It should somehow retrieve 'pr!truck' and message box me the value.

with pr!pName - I get "Item not found in this collection"
with pr! & pName - I get "Type-declaration character foes not match declared data type"

How can I string the variable with the RecordSet pointer?
 

JHB

Have been here a while
Local time
Tomorrow, 00:52
Joined
Jun 17, 2012
Messages
7,732
Try the below, (not tested).
Code:
tray = pr(pName)
 

namliam

The Mailman - AWF VIP
Local time
Tomorrow, 00:52
Joined
Aug 11, 2003
Messages
11,695
Obviously pName isnt a column in this query, you are replacing in its value and its probably assigned a (semi-)random column name since you are not giving it an alias.

Try: pr.Fields(3)
As your field reference, this should work regardless of column name... or try assigning a column alias.
 

Chrisopia

Registered User.
Local time
Today, 15:52
Joined
Jul 18, 2008
Messages
279
pr(pName) - didn't work JHB, and neither did pr.Fields(3) namliam...

However, if I combined the two, I got pr.Fields(prName) ... and now it does :D

Maybe you two should become crime solving partners...
 

pr2-eugin

Super Moderator
Local time
Today, 23:52
Joined
Nov 30, 2011
Messages
8,494
namliam's solution would have worked, provided the 3 was replaced with 2.. As the Field names referred by the DAO object are ZERO based.. So Field 1 would be referred as 0 and Field 2 as 1 and so on..

Apart from that, why not simply use DLookUp instead of opening Recordsets? That would be more neat in your situation?
 

namliam

The Mailman - AWF VIP
Local time
Tomorrow, 00:52
Joined
Aug 11, 2003
Messages
11,695
I always fall for the ZERO based nonsense !
 

Users who are viewing this thread

Top Bottom