I have an MS Access Database which has a Field called Field1
that contains multiple values delimited by commas. i.e.,
Value1,Value 2, Value3, Value 4,Value5
I am trying to split the values not into separate fields, but by duplicating the record and storing each value in another field. This will be such that a record containing a cell with three values will be duplicated three times, with each record varying in the value contained in the new field. For example,
Before query/running module:
+-----------+------------------------+
| App Code | Field1 |
+-----------+------------------------+
| AB23 | Value1, Value 2,Value3 |
+------------------------------------+
After query/running module:
+-----------------------------------------------+
| App Code | Field1 | Field2 |
+-----------+------------------------+----------+
| AB23 | Value1, Value 2,Value3 | Value1 |
+-----------+------------------------|----------+
| AB23 | Value1, Value 2,Value3 | Value 2 |
+-----------+------------------------+----------+
| AB23 | Value1, Value 2,Value3 | Value3 |
+-----------+------------------------+----------+
So far, I have found several questions about splitting a field into two or even several different fields, but I have not found any solution for splitting the record vertically. Of these solutions, some use queries and others use modules but I am also uncertain of which is most efficient, so I decided to go with a VBA module.
And so, here is the VBA module that I have found to be the most useful so far:
Function CountCSWords (ByVal S) As Integer
' Counts the words in a string that are separated by commas.
Dim WC As Integer, Pos As Integer
If VarType(S) <> 8 Or Len(S) = 0 Then
CountCSWords = 0
Exit Function
End If
WC = 1
Pos = InStr(S, ",")
Do While Pos > 0
WC = WC + 1
Pos = InStr(Pos + 1, S, ",")
Loop
CountCSWords = WC
End Function
Function GetCSWord (ByVal S, Indx As Integer)
' Returns the nth word in a specific field.
Dim WC As Integer, Count As Integer, SPos As Integer, EPos As Integer
WC = CountCSWords(S)
If Indx < 1 Or Indx > WC Then
GetCSWord = Null
Exit Function
End If
Count = 1
SPos = 1
For Count = 2 To Indx
SPos = InStr(SPos, S, ",") + 1
Next Count
EPos = InStr(SPos, S, ",") - 1
If EPos <= 0 Then EPos = Len(S)
GetCSWord = Trim(Mid(S, SPos, EPos - SPos + 1))
End Function
Yet how could I use this in an Access Query to achieve the aforementioned desired results? Otherwise, is there a better way to come to the same conclusion other than a Query (i.e. solely with a VBA module)?
EDIT
Note that the primary key in the Table is
Application Code
and not autonumber. This primary key is textual and distinct. In order for a record to be split, this will require the primary key to be duplicated, which is fine.