View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Ron Rosenfeld Ron Rosenfeld is offline
external usenet poster
 
Posts: 5,651
Default Extract data from String

On Thu, 9 Feb 2006 06:41:31 -0800, "SL" wrote:

I hope someone can help as this is driving me up the wall.

I have a text file that imports into Excel with data for each row in the
same cell. I need to split this data out into separate columns. The string is
a random length depending on the data in it. The example below shows the
string as it is, the following one shows how it should be split up into
separate columns.

"C W RUSSELL HAULAGE & PLA 5023 1 1 JCB 31-MAY-05 51 Hours 18.00 918.00"

C W RUSSELL HAULAGE & PLA
5023
1
1
JCB
31-MAY-05
51
Hours
18.00
918.00

The string will always be in the order above but will be different lengths
depending on the data within that row.

I have been trying to use the occurence of the first number to indicate the
end of the 1st part and go from there but have not had much success. There
will be a random number of spaces in the first part of the string depending
on the name of the supplier.

Any pointers would be greatly received.

Thank You

Regards

Sonya


It would be fairly simple to implement a solution in either worksheet functions
or VBA depending on the precise nature of the data.

But for something like what you have:

Some assumptions:

1. String length <=255 characters
2. After the initial name, the remaining fields are separated by <space's; no
<space's are present which are not field separators; no empty fields.
3. No error checking is required for any of the fields

Worksheet solution: (there may be more elegant solutions as I'm new at regular
expressions, so if these don't work on your data please let me know).

1. Download and install Longre's free morefunc.xll add-in from
http://xcell05.free.fr

2. Your string in A1

B1: =REGEX.MID($A$1,"((^|\s+)\S+)+(?=(\s+\S+){9})")
C1: =REGEX.MID($A$1,"\S+(?=(\s\S+){" & 9-COLUMNS($A:A)& "}$)")

Select B3 and copy/drag across to K1

The same functions (from morefunc.xll) can be run from within VBA using the RUN
method, or you can set a reference to the VBScript Regular Expressions and use
the functions in there (that would also be required if your string length was
255. Some setup is required for that, so I'd just use the morefunc routines
even if I were using VBA.


--ron