简体   繁体   中英

Excel: Split a delimited string and retrieve a numerical value of each element in the string

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.

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

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

Ps I believe though studying a solution using RegEx (Regular Expressions) would be more efficient, the pattern is not too complex.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM