views:

5607

answers:

2

Is there a smart macro in Excel (2000 upwards) to remove the last part of a string, if it has a certain separator?

If the separator is not there, the string should be preserved

For instance, for "."

 abcd.1          =>  abcd
 abcd            =>  abcd

I guess I could write something using a combination of Instr and Mid and such, but I am curious to know whether there is a smarter shorthand for it, like "Strip('abcd.1';'.')" or so.

+4  A: 

I do not believe there is any function that will do this for you.

You can probably use something like this:


=LEFT(A1,IF(ISERROR(SEARCH(".",A1)),LEN(A1),SEARCH(".",A1) - 1))

This will remove all characters after the first instance of the seperator, if you want to remove from the last instance you may need to write your own function to do a search on the reversed string.

A full list of available functions can be found at:

http://www.techonthenet.com/excel/formulas/index.php

Chris
Thanks, the list of functions was informative! Thanks also for the expression, it is good to know for future situations, my current need was for so few rows that only a built-in function was worth looking for, but the need is bound to appear again, so your solution is appreciated.
Brummo
+1  A: 

You can also create you own User Defined Function (UDF) for this.

Function Strip(ByVal oCell As Range, ByVal sSeperator As String) As String

    Dim iPos As Integer
    Dim sValue As String

    sValue = oCell.Value
    iPos = InStr(sValue, sSeperator)

    If (iPos <= 0) Then
        Strip = sValue
    Else
        Strip = Left(sValue, iPos - 1)
    End If

End Function

Then you can call that in your formula bar using

=Strip(A1, ".")

bendewey
Thanks for taking the time to answer, but I am guessing that for me to use an UDF I would need to put it in a template somewhere, so that it could benefit new spread sheets I create, and I would have to "allow macros", which is something I may not be able to do.
Brummo
By "able" I mean, it is not practical for me to do so in my current situation
Brummo
Deployment of this could be an issue if you want to use it across multiple sheets I would recommend creating an AddIn.
bendewey