Avatar of bfuchs
bfuchs
Flag 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
Microsoft AccessVBA

Avatar of undefined
Last Comment
Zakaria Acharki

8/22/2022 - Mon
Daniel Pineault

RegEx might be a good option for this.

See: https://stackoverflow.com/a/43166192/9706001
Jim Dettman (EE MVE)

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
Zakaria Acharki

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
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
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
bfuchs

ASKER
Thanks to all participants!
Zakaria Acharki

You're welcome @bfuchs, glad to help.