Access中实现GroupConcat效果

Option Compare Database

Public Function GroupConcat(sColumn As String, sTable As String, Optional sCriteria As String, Optional sDelimiter As String = “,”)
On Error GoTo ErrHandler
Dim rs As New ADODB.Recordset
Dim sSQL As String
Dim sResult As String
sResult = “”
sSQL = “select ” & sColumn & ” from ” & sTable
If sCriteria <> “” Then
sSQL = sSQL & ” where ” & sCriteria
End If
rs.Open sSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
Do While Not rs.EOF
If sResult <> “” Then
sResult = sResult & sDelimiter
End If
sResult = sResult & rs.Fields(0).Value
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
GroupConcat = sResult
Exit Function
ErrHandler:
If rs.State <> adStateClosed Then
rs.Close
End If
Set rs = Nothing
GroupConcat = Err.Number & ” : ” & Err.Description

End Function