Reputation: 33
I have the following situation: In a sheet (Dropdown) I have 2 columns containing product names and their respective IDs. In a different sheet (SelectProduct) I have a dropdown list of the product names for which I wrote some VBA code to allow multiple selection.
What way is there to perform something like a split on the string of products and retrieve EACH product's ID, then put each ID in a different cell as a string?
eg. initial string in Cell A2 is Product1;Product2;Product3, I want to end up with ID1;ID2;ID3 in another cell.
EDIT: Above was just an example to get an idea of what I need. My column has 606 products, with IDs ranging from 1 to 606
another example: string in cell- Tire;Bumper;Helmet
the outcome of IDs of those specific products- 156;35;310
the IDs won't be in order, as it depends on the order the products were selected.
Upvotes: 1
Views: 817
Reputation: 96753
With the lookup table in C3:D10 and data in A1, this little UDF():
Public Function GetIds(r1 As Range, r2 As Range) As String
Dim t As String
ary = Split(r1.Text, ";")
For Each a In ary
For i = 1 To r2.Rows.Count
If a = r2(i, 1).Value Then
GetIds = GetIds & ";" & r2(i, 2)
End If
Next i
Next a
GetIds = Mid(GetIds, 2)
End Function
will produce:
The IDs can be either numerical or non-numerical
Upvotes: 1
Reputation: 306
The easiest way, to get ID#s, would be to loop through each character and strip out any non alpha numberic.
str2 = ""
str1 = ActiveSheet.Range("A1").Value
For i = 1 To Len(str1)
c = Mid(str1, i, 1)
If IsNumeric(c) Or c = ";" Then
str2 = str2 & c
End If
Next i
just set A1 to whatever range your cell is in,
the str2 will bee all numbers with ; separater
Upvotes: 0
Reputation: 12645
As quick approach I would do this:
First, I would split by the separator (which I understood being a semi-column):
a = "Product1;Product2;Product3"
b = Split(a, ";")
In that case, b
will be an array of elements. Hence, I would parse starting from right until I don't find any number any longer:
Set c = New Collection
For j = 0 To UBound(b)
cnt1 = ""
cnt2 = 1
Do While IsNumeric(Left(Right(b(j), cnt2), 1))
cnt1 = Left(Right(b(j), cnt2), 1) & cnt1
cnt2 = cnt2 + 1
Loop
c.Add "ID" & cnt1
Next j
Please note your "ID + number" will be in the collection c
.
Which means you can build them up by just looping once through it:
newString = ""
For Each element In c
newString = element & ";"
Next element
P.s. I believe though studying a solution using RegEx (Regular Expressions) would be more efficient, the pattern is not too complex.
Upvotes: 0