Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Wildcards in 'Replace With' Text.

Wildcards in 'Replace With' Text

by Allen Wyatt
(last updated September 1, 2014)

8

Anne-Mie realizes that she can use wildcards (*?) to search in Excel, but she wonders if she can use wildcards in the replace string. For instance, she would like to search for "ab*de" and replace it with "aa*de", where the asterisk represents any number of characters, or none at all.

The short answer is that there is no way to do this in Excel, as described. If you only wanted to convert the second character of a text value from "b" to "a", then that can be done rather easily:

=REPLACE(A1,2,1,"a")

This, however, is probably not what you want to do; you want a way to use wildcards in the "replace with" text. The technical term for doing such string replacements is called REGEX, which is short for Regular Expressions. REGEX started with languages like Perl but was so powerful that many other programming languages added it on.

The VBA used in Excel is no exception. REGEX was added to Visual Basic 6.0, which means that it made its way to Excel's VBA in Excel 2003. The first step in using REGEX is to turn it on. You do this in the VBA Editor by choosing Tools | References and then making sure there is a check mark next to the Microsoft VBScript Regular Expressions 5.5 option.

Enabling this reference allows you to create REGEX objects. These objects possess a Test method and a Pattern property. This means that you set the Pattern property, and then the Test method checks to see if the pattern exists. A REGEX object also has a Replace method, which is used to do replacements.

Before proceeding, it is important to understand that regular expressions can get very complex and, well, "geeky." There is no way around it; how to work with regular expressions has been the subject of entire books. Fortunately, for the purposes of this tip, the expressions are rather simple in nature. In this case we'll use the pattern "^ab.*de$". This pattern refers to a word that starts (indicated by the ^) with "ab" followed by an arbitrary expression (indicated by *) consisting of at least one character (indicated by the period) and ending (indicated by the $) with "de".

Here is the code that implements the use of the REGEX object to do the actual replacements.

Public Function SearchNReplace1(Pattern1 As String, _
  Pattern2 As String, Replacestring As String, _
  TestString As String)
    Dim reg As New RegExp

    reg.IgnoreCase = True
    reg.MultiLine = False
    reg.Pattern = Pattern1
    If reg.Test(TestString) Then
        reg.Pattern = Pattern2
        SearchNReplace = reg.Replace(TestString, ReplaceString)
    Else
        SearchNReplace = TestString
    End If
End Function

To use this macro, start with the strings you want to change in column A. Assuming that the first string is in cell A1, you could place the following into another cell in order to get the changed text:

=SearchNReplace1("^ab.*de$","^ab","aa",A1)

This tells the macro that the pattern you want to look for is "^ab.*de$" (the first parameter), and that you want to replace "^ab" with "aa". This formula can be pasted down the column, and you end up with a conversion of column A where the string "ab*de" is replaced by "aa*de".

If you are using an older version of Excel that does not allow you to create REGEX objects, or if you would prefer not to do so, then you can create a macro that will simply step through a group of selected cells and look for any cell that begins with "ab" and ends with "de", and then replaces the beginning part with "aa".

Sub SearchNReplace2()
    Dim sFindInitial As String
    Dim sReplaceInitial As String
    Dim iLenInitial As Integer
    Dim sFindFinal As String
    Dim sReplaceFinal As String
    Dim iLenFinal As Integer
    Dim sTemp As String
    Dim rCell As Range

    sFindInitial = "ab"
    sReplaceInitial = "aa"
    sFindFinal = "de"
    sReplaceFinal = "de"

    For Each rCell In Selection
        sTemp = rCell.Value
        iLenInitial = Len(sFindInitial)
        iLenFinal = Len(sFindFinal)
        If Left(sTemp, iLenInitial) = sFindInitial And _
            Right(sTemp, iLenFinal) = sFindFinal Then
            sTemp = Mid(sTemp, iLenInitial + 1)
            sTemp = Left(sTemp, Len(sTemp) - iLenFinal)
            sTemp = sReplaceInitial & sTemp & sReplaceFinal
            rCell.Value = sTemp
        End If
    Next
    Set rCell = Nothing
End Sub

To use this routine, simply select the cells you want to change, and then execute the macro. You should also make changes to the sFindInitial, sReplaceInitial, sFindFinal, and sReplaceFinal variables, as needed.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (3303) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Wildcards in 'Replace With' Text.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Preventing Changes to Formatting and Page Size

When you create workbooks for others to use, you might want to make sure that they can't change the formatting and paper size ...

Discover More

Getting a Count of Unique Names

When you've got a column full of names, you may want to get a count of how many of those names are unique. You can make quick ...

Discover More

Getting Rid of Leading Zeros in a Number Format

Excel, by default, displays numbers with a leading zero, if they are less than 1. Here's how you can get rid of those leading ...

Discover More

Solve Real Business Problems Master business modeling and analysis techniques with Excel and transform data into bottom-line results. This hands-on, scenario-focused guide shows you how to use the latest Excel tools to integrate data from multiple tables. Check out Microsoft Excel 2013 Data Analysis and Business Modeling today!

More ExcelTips (menu)

Superscripts in Find and Replace

The find and replace used in Excel is less powerful than its counterpart in Word, so it is not able to do some of the ...

Discover More

Limiting Searching to a Column

When you use Find and Replace, Excel normally looks through all the cells in a worksheet. You may want to limit the search to ...

Discover More

Replacing Characters at the End of a Cell

The Find and Replace capabilities of Excel can come in handy, but they can't accomplish all your replacement needs. One such ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is six more than 8?

2016-10-25 15:06:10

Robin

@Dave Wilson from June 2015: I have done search & replace sequences like this before, with the first step being to replace "=" with " =", (replace equal with space-equal), and then reverse that as the last step.

This changes the formula into a text string, which then isn't affected by parenthesis imbalance. When you have the text string the way you want it, then change it back to a formula by removing the space in front of the equal sign.

HTH


2015-08-05 14:16:10

Chris

@BenK - that only appears to apply to Word. When you follow the instructions in Excel, there is no "Use Wildcards" option


2015-06-09 08:36:26

Dave Wilson

I want to change about 1200 formulae on a sheet to include the LEFT function as below

=IF(AND(Planning!J$317>0,(cellcolor(Planning!J$319,TRUE))=$D$9),Planning!J$317,"")
=IF(AND(Planning!I$317>0,(LEFT((cellcolor(Planning!I$319,TRUE)),2))=$D$9),Planning!I$317,"")

It can be done with 2x find/replaces, which isnt allowed because the first replace upsets the parenthesis balance

1st replace: cellcolor = LEFT((cellcolor
2nd replace: TRUE)) = TRUE)),2))

Can this tip do it in one? What expression would I type?

Thanks!


2015-04-15 15:57:46

Tony

I have a slightly different problem. I'm trying to change the following -
1.49 TB
1.68 TB
to
1490
1680
Is there a way to do a search on a row and change all to numerical values, deleting the "TB" and shifting the decimal? Thx!


2015-04-09 14:58:30

Gregg

Works perfectly!!!!

Thanks!!

Just changed .value per .Formula because I needed to modify the formulas.


2014-12-04 21:05:56

BenK

Office now supports backreferences in the replace text, ie you can group parts of the search string (with wildcards) using brackets, and refer to them in the replace string using 1 2 etc.

https://support.office.com/en-us/article/Find-and-replace-text-by-using-regular-expressions-Advanced-eeaa03b0-e9f3-4921-b1e8-85b0ad1c427f


2014-04-11 04:36:28

Jos

I can't get it to work
This is the text (tekststr) :
;Woonplaats>Veenendaal;/Woonplaats>;
It must be altered to:
Veenendaal

This was the expression
SearchNReplace1(";*>$", "*", "", tekststr)

(I dont want to use the phrase Woonplaats because there are more simular tags to alter)

What do i wrong?
Can you heklp me??


2011-11-04 18:23:03

Peter

Yip, perfect, just what I was looking for, Thank you


This Site

Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.