create comma seperated list from column

S

smbrowne

Hi,

I'm quite new to access and was hoping someone here might be able to
tell me how I can get the values from one column in my table returned
as a comma seperated list

Thanks
Sarah
 
G

Graham Mandeno

Hi Sarah

Try this function:

Public Function DelimitedList( _
RecordSource As String, _
Optional ListField As Variant = 0, _
Optional Delimiter As String = ", ") As String
Dim db As dao.Database, rs As dao.Recordset, sList As String
On Error GoTo ProcErr
Set db = CurrentDb()
Set rs = db.OpenRecordset(RecordSource, dbOpenSnapshot, dbForwardOnly)
Do Until rs.EOF
sList = sList & rs(ListField) & Delimiter
rs.MoveNext
Loop
If Len(sList) Then sList = Left(sList, Len(sList) - Len(Delimiter))
ProcEnd:
On Error Resume Next
rs.Close
DelimitedList = sList
Exit Function
ProcErr:
MsgBox Err.Description, vbExclamation
Resume ProcEnd
End Function

Using Northwind's Employees table as an example, you can call it like this:

?DelimitedList("Employees", "City")

or, to sort the list, use a SQL statement:

?DelimitedList("Select City from Employees order by City")

or to eliminate duplicates, use SELECT DISTINCT:

?DelimitedList("Select distinct City from Employees")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top