Simulate string split function in Excel formula

后端 未结 8 1712
难免孤独
难免孤独 2020-12-09 09:15

I am trying to split a string in an excel formula, something like I can do in many programming languages, e.g.

string words = \"some text\".split(\' \');


        
相关标签:
8条回答
  • 2020-12-09 09:24

    The following returns the first word in cell A1 when separated by a space (works in Excel 2003):

    =LEFT(A1, SEARCH(" ",A1,1))
    
    0 讨论(0)
  • 2020-12-09 09:24

    These things tend to be simpler if you write them a cell at a time, breaking the lengthy formulas up into smaller ones, where you can check them along the way. You can then hide the intermediate calculations, or roll them all up into a single formula.

    For instance, taking James' formula:

    =IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)
    

    Which is only valid in Excel 2007 or later.

    Break it up as follows:

    B3: =FIND(" ", A3)
    C3: =IF(ISERROR(B3),A3,LEFT(A3,B3-1))
    

    It's just a little easier to work on, a chunk at a time. Once it's done, you can turn it into

    =IF(ISERROR(FIND(" ", A3)),A3,LEFT(A3,FIND(" ", A3)-1))
    

    if you so desire.

    0 讨论(0)
  • 2020-12-09 09:29

    If you need the allocation to the columns only once the answer is the "Text to Columns" functionality in MS Excel.

    See MS help article here: http://support.microsoft.com/kb/214261

    HTH

    0 讨论(0)
  • 2020-12-09 09:30

    Some great worksheet-fu in the other answers but I think they've overlooked that you can define a user-defined function (udf) and call this from the sheet or a formula.

    The next problem you have is to decide either to work with a whole array or with element.

    For example this UDF function code

    Public Function UdfSplit(ByVal sText As String, Optional ByVal sDelimiter As String = " ", Optional ByVal lIndex As Long = -1) As Variant
        Dim vSplit As Variant
        vSplit = VBA.Split(sText, sDelimiter)
        If lIndex > -1 Then
            UdfSplit = vSplit(lIndex)
        Else
            UdfSplit = vSplit
        End If
    End Function
    

    allows single elements with the following in one cell

    =UdfSplit("EUR/USD","/",0)

    or one can use a blocks of cells with

    =UdfSplit("EUR/USD","/")

    0 讨论(0)
  • 2020-12-09 09:32

    Highlight the cell, use Dat => Text to Columns and the DELIMITER is space. Result will appear in as many columns as the split find the space.

    0 讨论(0)
  • 2020-12-09 09:42

    AFAIK the best you can do to emulate Split() is to use FILTERXML which is available from Excel 2013 onwards (not Excel Online or Mac).

    The syntax more or less always is:

    =FILTERXML("<t><s>"&SUBSTITUTE(A1,"|","</s><s>")&"</s></t>","//s")
    

    This would return an array to be used in other functions and would even hold up if no delimiter is found. If you want to read more about it, maybe you are interested in this post.

    0 讨论(0)
提交回复
热议问题