How to combine records into one in a datasheet

hockey8837

Registered User.
Local time
Today, 14:56
Joined
Sep 16, 2009
Messages
106
Hi,
I have a contact table and a category table. One contact can be assigned several categories.

I want to be able to have a datasheet in a form show me all vital contact info (name, address, etc) across one row as well as show in one cell of the row a string of however many of the categories this contact has been assigned, separated by commas.

For instance, I'd like the columns to look like this:
Code:
Name-------Phone------------Address------------Category
Joe Smith---(555) 555-5555---123 North Street---Volunteer, Civic Leader, Government

Is there a way to write into a query to take the contact ID and for every category assigned to it, string them together (like, above, *Volunteer, Civic Leader, and Government* are 3 categories) into one 'sentence'? Then, I could set the record source for Category in my datasheet to this column in the query.
 
Hi,
So I've been trying to play around with this and can't seem to get it to work.

I used the code from http://allenbrowne.com/func-concat.html and pasted it into a module, as the site says.

Code:
Public Function ConcatRelated(strField As String, _
    strTable As String, _
    Optional strWhere As String, _
    Optional strOrderBy As String, _
    Optional strSeparator = ", ") As Variant
On Error GoTo Err_Handler
    'Purpose:   Generate a concatenated string of related records.
    'Return:    String variant, or Null if no matches.
    'Arguments: strField = name of field to get results from and concatenate.
    '           strTable = name of a table or query.
    '           strWhere = WHERE clause to choose the right values.
    '           strOrderBy = ORDER BY clause, for sorting the values.
    '           strSeparator = characters to use between the concatenated values.
    'Notes:     1. Use square brackets around field/table names with spaces or odd characters.
    '           2. strField can be a Multi-valued field (A2007 and later), but strOrderBy cannot.
    '           3. Nulls are omitted, zero-length strings (ZLSs) are returned as ZLSs.
    '           4. Returning more than 255 characters to a recordset triggers this Access bug:
    '               http://allenbrowne.com/bug-16.html
    Dim rs As DAO.Recordset         'Related records
    Dim rsMV As DAO.Recordset       'Multi-valued field recordset
    Dim strSql As String            'SQL statement
    Dim strOut As String            'Output string to concatenate to.
    Dim lngLen As Long              'Length of string.
    Dim bIsMultiValue As Boolean    'Flag if strField is a multi-valued field.
    
    'Initialize to Null
    ConcatRelated = Null
    
    'Build SQL string, and get the records.
    strSql = "SELECT " & strField & " FROM " & strTable
    If strWhere <> vbNullString Then
        strSql = strSql & " WHERE " & strWhere
    End If
    If strOrderBy <> vbNullString Then
        strSql = strSql & " ORDER BY " & strOrderBy
    End If
    Set rs = DBEngine(0)(0).OpenRecordset(strSql, dbOpenDynaset)
    'Determine if the requested field is multi-valued (Type is above 100.)
    bIsMultiValue = (rs(0).Type > 100)
    
    'Loop through the matching records
    Do While Not rs.EOF
        If bIsMultiValue Then
            'For multi-valued field, loop through the values
            Set rsMV = rs(0).Value
            Do While Not rsMV.EOF
                If Not IsNull(rsMV(0)) Then
                    strOut = strOut & rsMV(0) & strSeparator
                End If
                rsMV.MoveNext
            Loop
            Set rsMV = Nothing
        ElseIf Not IsNull(rs(0)) Then
            strOut = strOut & rs(0) & strSeparator
        End If
        rs.MoveNext
    Loop
    rs.Close
    
    'Return the string without the trailing separator.
    lngLen = Len(strOut) - Len(strSeparator)
    If lngLen > 0 Then
        ConcatRelated = Left(strOut, lngLen)
    End If

Exit_Handler:
    'Clean up
    Set rsMV = Nothing
    Set rs = Nothing
    Exit Function

Err_Handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "ConcatRelated()"
    Resume Exit_Handler
End Function
I saved this module as fnConcatRelated.

I then tried to call the module from a text box with:
Code:
=ConcatRelated("ContactID","CategoriesAndContactsExtended","CategoryID = " & [CategoryID])
When I open the form with this text box in it, it only displays '#Name?'. If I make it a Combobox, the drop down list is 3 columns (ContactID, CategoryID, and CategoryName). But, the list is all records in the query, not specific to the current record or combined into a simple phrase (i.e. 'volunteer group, civic association, government')

I'm not formally trained in Access, so when it comes to the background code, it's a little over my head. I want the code to call the ContactID of the current record and display all CategoryID (or, really, the categories not the ID#) possible.

I have a query, CategoriesAndContactsExtended, which matches the two ID fields and populates a table, CategoriesAndContacts, with that data. I'm not sure which of the two I should be pulling information from for this function.

Any suggestions would be appreciated!
 
Can you post the db?
 
Hi,
Here's a slimmed-down version of the DB. I think I copied over all pertinent data/forms/tables etc.

When working with a contact, I open the contact details form, and add categories to the contact through this subform.

I use access '07, and it wouldn't let me save into an earlier version b/c of some features I currently am using in the DB. If you cannot open, let me know and I'll try to figure out what it is that is keeping me from saving into an older version and delete it.

Thanks!
 

Attachments

I've only had time to glance at it, but the query CategoriesAndContactsExtended does not return any records, so obviously the function won't be able to find anything. There's also no data in the CategoriesAndContacts table, so I'm not sure the function has any data to work with.
 
Hi,
Sorry, I'd deleted all the records to make the DB smaller, and then imported a handful back in for demonstration purposes, but I attached the wrong DB.

Try this one...

Thanks!
 

Attachments

Where are you trying to use it? I put it on the CategoryDetails form (actually I think it was on the subform) and it appeared to correctly return data.
 
I'd like to use it on the Contact List form, and in reports.
When I put it on the Contact List form, it returned #Name? in the field.

I just added it to the Category Details form myself, and it appears to be working, however it's only displaying the ID# and not the category name. How should I change it so that it would do this?
 
The Contact List form does not have CategoryID in its source, hence the error. The first argument is where you tell it what you want returned:

strField = name of field to get results from and concatenate.

You've told it to return the ContactID, so that's what it's doing.
 
Could I put something into a query, say 'Contacts Extended', by adding CategoriesAndContacts table to it, and joining the ContactIDs (while still returning all Contacts in the DB through the join properties), to return the [FONT=&quot]concatenated Category field?

Then, it would be in the record source for this query, right?
[/FONT]
 
Sure; any table/query that returns the appropriate data can be the source for the function.
 
Sure; any table/query that returns the appropriate data can be the source for the function.


Hi,
So, I put the following into a query:

Code:
AllCategories: ConcatRelated("CategoryID","CategoriesAndContacts","ContactID = " & [ContactID])

It returns the ID#s instead of the Category name... I tried to make "CategoryID" just category and got an error. What should it be instead?? I think I'm almost there!
 
It returns an error because Category isn't in that table. I thought you were going to make a query that returned both so you could use that?
 

Users who are viewing this thread

Back
Top Bottom