Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace variable string in VBA

I need to replace somethin in a string, but what to replace may vary. It can be

XY - test
XXxY-test
XXyyXx-TEST
yXyy     -Test

and virtually any other combination of whitespaces and cases of the above.

I need to replace the "-test" part and leave the "XXX" alone. So, when using a simple replace

Replace("XXX  -test", "- test", "")

It won't work, obviously. So I need a more sophisticated version of Replace that could handle this task. Is there something I could use or do I have to write it on my own?

like image 565
F.P Avatar asked May 04 '11 12:05

F.P


People also ask

How do I find and replace a string in VBA?

Example #1 – VBA Find and Replace the WordStep 1: First, mention the Range of cells we are replacing. In this example, Range is from A1 to B15, so the code will be Range (“A1: B15”). Step 2: Now put a dot to see the IntelliSense list. Step 3: Select the Replace method from the IntelliSense list.

How do I replace a value in VBA?

The VBA REPLACE function is listed under the text category of VBA functions. When you use it in a VBA code, it replaces a substring from string with a new sub-string. In simple words, you can use REPLACE to replace a part of text with another text and it returns that new text in the result.

Can I use substitute in VBA?

Description. The Microsoft Excel REPLACE function replaces a sequence of characters in a string with another set of characters. The REPLACE function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel.


2 Answers

If you need more flexibility than that provided by mj82's method (for example, you may not know the length of the initial expression), you can use a regular expression. For example:

Regex.Replace("XXX  -test", "\s*-\s*test", "", RegexOptions.IgnoreCase)
like image 73
eggyal Avatar answered Nov 15 '22 07:11

eggyal


This is to compliment eggyal's answer. This is a VBA regexreplace function so that you can use his answer. You'll notice I added ignore_case as an option for flexibility, so your call would be:

=RegexReplace(cell, "\s*-\s*test", "", TRUE)

Here is the function, I hope you find it useful:

' -------------------------------------------------------------------
' Search and Replace using a regular expression
' -------------------------------------------------------------------

Function RegexReplace(ByVal text As String, _
                      ByVal replace_what As String, _
                      ByVal replace_with As String, _
                      Optional ByVal ignore_case As Boolean = False) As String

Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.ignorecase = ignore_case
RE.pattern = replace_what
RE.Global = True
RegexReplace = RE.Replace(text, replace_with)

End Function
like image 29
aevanko Avatar answered Nov 15 '22 09:11

aevanko