Link to home
Create AccountLog in
Avatar of Clive Beaton
Clive BeatonFlag for Australia

asked on

Can I pass a field name to a function to return the value of the field?

I have a table containing 1 record with 2 fields ShowAddress and ApplyTax, both type Text containing either 'Yes' or 'No".  

Is it possible to pass the field names to a function and get the text value back.  Something like:

Public Function UserOption(MyOption As String) As String
   Dim db As Database, rs As Recordset
   Set db = CurrentDb
   Set rs = db.OpenRecordset("tblUserOptions")
   If Not rs.EOF Then
      UserOption = [Field value]
   End If
End Function

Thanks in advance

Avatar of dqmq
dqmq
Flag of United States of America image

Access already has a function for that:  DLOOKUP

UserOption = dlookup("ShowAddress","tblUserOptions")

Your function also works, like this:

Public Function UserOption(MyOption As String) As String
   Dim db As Database, rs As Recordset
   Set db = CurrentDb
   Set rs = db.OpenRecordset("tblUserOptions")
   If Not rs.EOF and not rs.BOF Then
      useroption = rs!Fields(myOption).value
End Function

ASKER CERTIFIED SOLUTION
Avatar of dqmq
dqmq
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Clive Beaton

ASKER

I got 'Item not found in this collection' but I changed rs!Fields  to rs.Fields and it worked fine.

Thanks very much.