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(' ');
The problem is that I can't be sure that there is more than one word in the cell. If I try to use the FIND()
or SEARCH()
functions, they return #VALUE
if there is not space. Is there any easy way to split the string so that it returns the individual words (or even better, so that it returns either the first word or all the other words)?
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
This will firstly check if the cell contains a space, if it does it will return the first value from the space, otherwise it will return the cell value.
Edit
Just to add to the above formula, as it stands if there is no value in the cell it would return 0. If you are looking to display a message or something to tell the user it is empty you could use the following:
A formula to return either the first word or all the other words.
Examples and results
Comments on Formula:
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:
Which is only valid in Excel 2007 or later.
Break it up as follows:
It's just a little easier to work on, a chunk at a time. Once it's done, you can turn it into
if you so desire.
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.
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
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","/")