I have to run reports from excel files on a regular basis for a certain project. The data comes to me with comma seperated values in a column . I needed to find a way to remove the leading and trailing commas and spaces without removing the commas and spaces from the middle of the strings. I was able to write something in VBA that works, but I can't figure out why it works.
Sample data
sample what I need the data to look like (also what the function i wrote is actually giving me) ,, asdf , lkjh , , asdf , lkjh , asdf, asdf , asdf , asdf , asdf , asdf
Here is the function that I wrote
What I can't figure out is why it is catching multiple commas and a spaces at the beginning and end of the string without a DO Loop.Option Explicit Function cleaner(s As String) As String If Right(s, 1) = " " Then cleaner = cleaner(Left(s, Len(s) - 1)) ElseIf Right(s, 1) = "," Then cleaner = cleaner(Left(s, Len(s) - 1)) ElseIf Left(s, 1) = " " Then cleaner = cleaner(Right(s, Len(s) - 1)) ElseIf Left(s, 1) = "," Then cleaner = cleaner(Right(s, Len(s) - 1)) Else cleaner = s End If End Function
Last edited by carpe.cervisiam; 01-06-2012 at 11:06 PM.
carpe.cervisiam,
It is looping becuase you have the function calling itself:
That means every time it makes a correction, the function calls itself, so it loops over and over until the last Else statement where it no longer calls itself, but simply sets itself to the already cleaned stringcleaner = cleaner(...)
Hope that helps,
~tigeravatar
Forum Rules: How to use code tags, mark a thread solved, and keep yourself out of trouble
Thank You! I know just enough about VBA to be dangerous and this one was making my brain hurt.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks