Split a string (cell) in Excel without VBA (e.g. for array formula)

后端 未结 6 539
执笔经年
执笔经年 2020-11-27 21:30

I have data in an Excel spreadsheet with delimited strings. For simplicity, think of something like \"4#8#10\", with an arbitrary number of pieces.

Is

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:34

    To sum the entries 4,8,10 you could use something like:

    =SUMPRODUCT(1*TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),(ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1))-1)*99+((ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)))=1),99)))
    

    The array that is returned is a text array, so the 1* at the beginning is one way to convert them to numbers

    This part:

    TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),(ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1))-1)*99+((ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)))=1),99))
    

    returns the array:

    {"4";"8";"10"}
    

    And with 1* before it:

    {4;8;10}
    

    Edit After six years, more succinct formulas are available to create the array:

    With Excel O365 and the SEQUENCE function:

    =1*(TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),IF(SEQUENCE(LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)=1,1,(SEQUENCE(LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)-1)*99),99)))
    

    With Excel 2010+ for Windows (not MAC versions) with the FILTERXML funcdtion:

    =FILTERXML("" & SUBSTITUTE(A1,"#","") & "","//s")
    

    Note that the FILTERXML function extracts the values as numbers, whereas the first formula extracts the numbers as text which must be converted to numbers before being used in a numeric formula.

提交回复
热议问题