Help Writing Field Names to a String

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • birdDBheadache
    New Member
    • Mar 2014
    • 16

    Help Writing Field Names to a String

    I am trying to concatenate field names (separated by a comma or some of the delimiter) and write them to record in my database, or store them as a string that I can use in an expression later on. So far I have code that pulls all the field names from a query and writes them to the debug window. But I am stuck after that. I can't figure out how to get the output into another format. Any suggestions would be appreciated.


    Code:
    Sub Fieldnames()
        Dim Rst As Recordset
        Dim db As Database
        Dim f As Field
        Dim qdfParmQry As QueryDef
            Set db = CurrentDb()
            Set qdfParmQry = db.QueryDefs("qry_1test")
            qdfParmQry("Forms!Occu_formatting!Species") = [Forms]![Occu_formatting]![Species]
            Set Rst = qdfParmQry.OpenRecordset()
        For Each f In Rst.Fields
        Debug.Print f.Name
        Next
        Rst.Close
    End Sub
    Last edited by Rabbit; Mar 13 '14, 07:17 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Seth Schrock
    Recognized Expert Specialist
    • Dec 2010
    • 2965

    #2
    You would need a string variable to store the field names.
    Code:
    Dim strFields As String
    Now, just below your Debug.Print line, put this
    Code:
    strFields = strFields & f.Name & ", "
    This will leave you with a comma and a space at then end of the string when you are done, so after your loop, you will probably want to drop those.
    Code:
    strFields = Left(strFields, Len(strFields) - 2)
    You might have to play with the number that you are subtracting to make sure it works, but otherwise it should work.

    Comment

    • birdDBheadache
      New Member
      • Mar 2014
      • 16

      #3
      That worked, thanks!
      Last edited by NeoPa; Mar 14 '14, 12:17 AM. Reason: New questions require their own new thread.

      Comment

      • NeoPa
        Recognized Expert Moderator MVP
        • Oct 2006
        • 32634

        #4
        That works Seth, but an alternative approach is to use :
        Code:
        strFields = strFields & ", " & f.Name
        This has the benefit of being easier to tidy up afterwards using :
        Code:
        strFields = Mid(strFields, 3)

        Comment

        Working...