Link to home
Start Free TrialLog in
Avatar of bfuchs
bfuchsFlag for United States of America

asked on

Create custom Replace function

Hi Experts,

I am looking to create a function that will accept a string and only return the alpha/numeric values, except for dashes all special characters should get stripped out.

So instead of having to use the following
fieldName = Left(Replace(Replace(Replace(Mid(ColumnName, 2, Len(ColumnName) - 2), " ", ""), "&", ""), "+", ""), 32)

Open in new window

I can call my function something like
MyReplace(sTrVar,"_")

Open in new window


P.S. If possible, would prefer to have the 2nd variable of the function (the one holding the dash) capable of managing more than one character as an exception, so I can send "_,-,' ') and all 3 of them would be considered valid characters, not getting stripped out.

Thanks
Avatar of Daniel Pineault
Daniel Pineault

RegEx might be a good option for this.

See: https://stackoverflow.com/a/43166192/9706001
Here's a good article on EE about regex:

https://www.experts-exchange.com/articles/1336/Using-Regular-Expressions-in-Visual-Basic-for-Applications-and-Visual-Basic-6.html

 beyond that, there is a lot of generic "find and replace" code floating around.    But this seems specific enough for you to write your own.

 It's simple enough....just loop through the string and dump anything you don't want.   Generally done with an In and out string, the latter of which you build up as you read the "in" string.

Jim.
ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bfuchs

ASKER

@Zakaria,

Middle of testing yours...seems to work-:)

Can you explain why do I get into the debug line?
fieldName = Left(Replace(Replace(Replace(Replace(Mid(ColumnName, 2, Len(ColumnName) - 2), " ", ""), "&", ""), "+", ""), "-", ""), 32)
                        If fieldName <> Left(MyReplace(Mid(ColumnName, 2, Len(ColumnName) - 2), "_"), 32) Then
                            Debug.Print fieldName
                        End If

Open in new window


See attached.

Thanks,
Ben
Untitled.png
Avatar of bfuchs

ASKER

Thanks to all participants!
You're welcome @bfuchs, glad to help.