View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein Rick Rothstein is offline
external usenet poster
 
Posts: 5,934
Default remove text after character

I'm writing a macro that will do a number of things, but I'm having
trouble
with one part of it. I have a column that has text in it's values. What
i
want to do is remove any text that is in parenthesis. So I a basically
need
to remove anything after the "(" in a text string. If there are no
parenthesis in the cell then it should leave it alone. I'm sure this is
pretty easy, but I can't get the Find method to combine with Left to
make
is
work.

Try this function:

Function remove_after_character(s As String, c As String) As String
If InStr(s, c) Then
remove_after_character = Left(s, InStr(s, c))
Else
remove_after_character = s
End If
End Function

use e.g. like this:

Cells(1,1) = remove_after_character(Cells(1,1), "(")


You accidentally left out the -1 (minus one) off of the second argument in
the Left function call. Without it, the character passed into the 'c'
argument will be displayed.

As a point of interest, you can simplify this function down to a one-liner
by doing it this way...

Function Remove_After_Character(s As String, c As String) As String
Remove_After_Character = Left(s, InStr(s & c, c) - 1)
End Function


Well, I had the -1 to start with, but then I chose to interpret the
OP request 'remove anything after the "(" in a text string', as after
and not including.
But it is always difficult with ambigous requests.
'remove any text that is in parenthesis'. What if there is text after
the closing parenthesis ")", like xxxxxx(xxxxx)xxxx
What if there is more than one parenthesis, like xxx(xx)xx(xx)xx
and so on?

But the one-liner is very nice. With the -1, I would name the function
Remove_From_Character.


Ah, now I see why you didn't include the -1 (I knew you knew about it, I
just thought you typed it out directly and simply forgot it). Yeah, the OP's
request does say "after", but I just assumed he wouldn't really want the
outputted text to end with an opening parenthesis (hence my posting to you).

--
Rick (MVP - Excel)