View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.misc
Ron Rosenfeld Ron Rosenfeld is offline
external usenet poster
 
Posts: 5,651
Default Select specific text in cell

On Fri, 15 Feb 2008 21:36:13 -0500, Ron Rosenfeld
wrote:

On Fri, 15 Feb 2008 18:07:05 -0800, John Gregory
wrote:

The text strings are random length - file path names:

c:\sampledir1\filename - description

In this example, I want to get the string "filename", but I have many
directories, all with differnt length names.

c:\samplelongname2\filename345 - longer description

etc.

In all cases I want to get the text between the "/" and the "-". The right
and left functions do not work because the number of characters varies.

Any ideas



In your example, the - is surrounded by <space on both sides.

If this is the case in your strings, it would be more robust to look for that
sequence, than just for the "-".

With your string in A1, here is a formula that will extract the string that is
between the last "\" and the last "-" :

=TRIM(MID(A1,1+FIND(CHAR(1),SUBSTITUTE(A1,"\",CHA R(1),
LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))),-1+FIND(CHAR(1),
SUBSTITUTE(A1,"-",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"-",""))))
-FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-
LEN(SUBSTITUTE(A1,"\",""))))))
--ron


By the way, here are some UDF's that will do the same thing. They can be
entered in a regular module and then used as a function.

To enter into a regular module, <alt-F11 opens the VBEditor. Ensure your
project is highlighted in the project explorer window, then Insert/Module and
paste one of the codes below into the window that opens:

=============================================
Option Explicit
Function fn(str As String) As String
Dim s1() As String
Dim s2() As String
s1 = Split(str, "\")
s2 = Split(s1(UBound(s1)), "-")
fn = Trim(s2(LBound(s2)))
End Function
==========================================

The above as a "one-liner" in deference to Rick:

============================================
Function fn(str As String) As String
fn = Trim(Split(Split(str, "\")(UBound(Split _
(str, "\"))), "-")(LBound(Split(Split _
(str, "\")(UBound(Split(str, "\"))), "-"))))
End Function
==========================================

and using Regular Expressions, which, although a bit longer, took a fraction of
the time to develop and test of any of the other solutions.

================================
Option Explicit
Function fn(str As String) As String
Dim re As Object, mc As Object
Set re = CreateObject("vbscript.regexp")
re.Pattern = "\\([^\-\\]*\S)\s?-[^\\]*$"
If re.test(str) = True Then
Set mc = re.Execute(str)
fn = mc(0).submatches(0)
End If
End Function
=================================
--ron