Миф excel replace all

Find and Replace All With Excel VBA

What This VBA Code Does

These VBA macros will show you various ways to find and replace all for any text or numerical value.

Find/Replace All Within A Specific Worksheet

Sub FindReplaceAll()
‘PURPOSE: Find & Replace text/values throughout a specific sheet
‘SOURCE: www.TheSpreadsheetGuru.com

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

fnd = «April»
rplc = «May»

‘Store a specfic sheet to a variable
  Set sht = Sheets(«Sheet1»)

‘Perform the Find/Replace All
  sht.Cells.Replace what:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False

End Sub

Find/Replace All Throughout Entire Workbook 

Sub FindReplaceAll()
‘PURPOSE: Find & Replace text/values throughout entire workbook
‘SOURCE: www.TheSpreadsheetGuru.com

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

fnd = «April»
rplc = «May»

For Each sht In ActiveWorkbook.Worksheets
  sht.Cells.Replace what:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
Next sht

End Sub

Multiple Iterations of Find/Replace At Once!

If you need to perform a bunch of find and replace actions at once, you can use Arrays to store your values.

Sub Multi_FindReplace()
‘PURPOSE: Find & Replace a list of text/values throughout entire workbook
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array(«Canada», «United States», «Mexico»)
rplcList = Array(«CAN», «USA», «MEX»)

‘Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    ‘Loop through each worksheet in ActiveWorkbook
      For Each sht In ActiveWorkbook.Worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
      Next sht

    Next x

End Sub

Multiple Iterations of Find/Replace At Once (Feeding From A Table)

Sub Multi_FindReplace()
‘PURPOSE: Find & Replace a list of text/values throughout entire workbook from a table
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim fndList As Integer
Dim rplcList As Integer
Dim tbl As ListObject
Dim myArray As Variant

‘Create variable to point to your table
  Set tbl = Worksheets(«Sheet1»).ListObjects(«Table1»)

‘Create an Array out of the Table’s Data
  Set TempArray = tbl.DataBodyRange
  myArray = Application.Transpose(TempArray)

  ‘Designate Columns for Find/Replace data
  fndList = 1
  rplcList = 2

‘Loop through each item in Array lists
  For x = LBound(myArray, 1) To UBound(myArray, 2)
    ‘Loop through each worksheet in ActiveWorkbook (skip sheet with table in it)
      For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> tbl.Parent.Name Then

                    sht.Cells.Replace What:=myArray(fndList, x), Replacement:=myArray(rplcList, x), _
            LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
            SearchFormat:=False, ReplaceFormat:=False

                End If
      Next sht
  Next x

End Sub

Notifying How Many Cells Were Changed

You may find yourself wanting to report out how many changes were made after your code has run. You can accomplish this by using the COUNTIF() function to count how many cells contain your Find value before you actually perform your find & replace.

The one downside to using the COUNTIF() function is it will not count multiple occurrences within a single cell. I could not figure out a way around this and if you know of a way to accomplish this please let me know in the comments section (this article might point you in the right direction).

Sub FindReplaceAll_CountReplacements()
‘PURPOSE: Find & Replace text/values throughout entire workbook, notify user of how many cells were affected
‘SOURCE: www.TheSpreadsheetGuru.com

Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
Dim ReplaceCount As Long

fnd = «April»
rplc = «May»

For Each sht In ActiveWorkbook.Worksheets

  ReplaceCount = ReplaceCount + Application.WorksheetFunction.CountIf(sht.Cells, «*» & fnd & «*»)

  sht.Cells.Replace what:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False

    Next sht

MsgBox «I have completed my search and made replacements in » & ReplaceCount & » cell(s).»

End Sub

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

Замена части строкового выражения в VBA Excel по указанному шаблону поиска и замены и возврат преобразованной строки с помощью функции Replace.

Replace – это функция, которая возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз.

Если замену подстроки необходимо осуществить в диапазоне ячеек, функцию Replace следует применить к значению каждой ячейки заданного диапазона. Проще замену в диапазоне ячеек произвести с помощью метода Range.Replace.

Синтаксис и параметры

Replace(expression, find, replace, [start], [count], [compare])

  • expression – исходное строковое выражение, содержащее подстроку, которую необходимо заменить;
  • find – искомая подстрока, подлежащая замене;
  • replace – подстрока, заменяющая искомую подстроку;
  • start – порядковый номер символа исходной строки, с которого необходимо начать поиск, часть строки до этого номера обрезается, по умолчанию равен 1 (необязательный параметр);
  • count – количество замен подстроки, по умолчанию выполняется замена всех обнаруженных вхождений (необязательный параметр);
  • compare – числовое значение, указывающее вид сравнения (необязательный параметр).

Сокращенный синтаксис функции Replace с необязательными параметрами по умолчанию:

Replace(expression, find, replace)

Параметр compare

Константа Значение Описание
vbUseCompareOption -1 используется параметр, заданный оператором Option Compare
vbBinaryCompare 0 выполняется двоичное сравнение
vbTextCompare 1 применяется текстовое сравнение

По умолчанию используется двоичное (бинарное) сравнение. При таком сравнении буквенные символы в нижнем и верхнем регистрах различаются. Если необходимо провести замену подстроки независимо от регистра букв, используйте значение параметра compare – vbTextCompare (1).

Примеры кода VBA Excel

Пример 1

Замена единственного вхождения искомой подстроки в строковое выражение:

Sub Primer1()

Dim a

a = «Сливочное масло»

a = Replace(a, «Сливочное», «Рыжиковое»)

MsgBox a

‘Результат: «Рыжиковое масло»

End Sub

Пример 2

Замена нескольких вхождений искомой подстроки в строковое выражение:

Sub Primer2()

Dim a

a = «Идёт медведь, идёт лиса, идёт грач»

‘с параметром compare по умолчанию

a = Replace(a, «идёт», «бежит»)

MsgBox a

‘Результат:

‘Идёт медведь, бежит лиса, бежит грач

a = «Идёт медведь, идёт лиса, идёт грач»

‘с параметром compare=1(vbTextCompare)

a = Replace(a, «идёт», «бежит», , , 1)

MsgBox a

‘Результат:

‘бежит медведь, бежит лиса, бежит грач

End Sub

Пример 3

Замена одного вхождения искомой подстроки в строковое выражение из нескольких с обрезанием исходной строки до 15 символа:

Sub Primer3()

Dim a

a = «Идёт медведь, идёт лиса, идёт грач»

a = Replace(a, «идёт», «бежит», 15, 1)

MsgBox a

‘Результат:

‘бежит лиса, идёт грач

End Sub

VBA Replace function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. It replaces a sub-string with another string in a given string. It has three required parameters and three optional parameters. If expression is Null, then the function returns an error. Expression contains length, then it returns an empty string.

This function use as a VBA function and a Excel Worksheet function(It has different syntax in Excel). The Replace function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Replace function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Replace function, where we can use this Replace function and real-time examples in VBA.

Table of Contents:

  • Overview
  • Syntax of VBA Replace Function
  • Parameters or Arguments
  • Where we can apply or use the VBA Replace Function?
  • Ex 1: Replace all occurrences of substring “F1” with “Help”
  • Ex 2: Replace all occurrences of substring “Help” with “F1”
  • Ex 3: Replace all occurrences of substring “F1” with “Help” starting from position 13
  • Ex 4: Replace all occurrences of substring “F1” with “Help” starting from position 13 and keep whole string
  • Ex 5: Replace last occurrence of substring “F1” with “Help”
  • Ex 6: Remove all occurrences of substring ‘F1’
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA Replace function is

Replace(Expression, Find, Replace, [Start], [Count], [Compare])

Note: This Replace function returns a string.

Parameters or Arguments:

This function has three mandatory parameters and three optional parameters for the Replace Function.
Where

Expression: An Expression is a mandatory argument. It represents a string expression you want to replace sub-string in.
Find: Find is a mandatory argument. It represents a sub-string which we want to find or search within an expression.
Replace: Replace is a mandatory argument. It represents a sub-string which we want to replace within an expression.
Start: Start is an optional parameter. Default value is ‘1’. It represents the position in expression to start search.
Count: Count is an optional parameter. It represents the number of occurrences to replace sub-string within an expression. Default value is ‘-1’. If we ignore, it will replace all occurrences of sub-string with another specified sub-string.
Compare: Compare is an optional parameter. It represents a numeric value. It specifies the type of comparison to evaluate the sub-strings. This argument can have anyone of the following value. Default comparison is ‘vbBinaryCompare’.

VBA Constant Value Description
vbUseCompareOption -1 Performs a comparison using the Option Compare statement.
vbBinaryCompare 0 performs a binary comparison
vbTextCompare 1 performs a text comparison
vbDatabaseCompare 2 performs a database comparison. It applies only in MS Access.

Where we can apply or use the VBA Replace Function?

We can use this VBA Replace function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Replace all occurrences of sub-string “F1” with “Help”

Here is a simple example of the VBA Replace function. This below example macro returns a string. The output of the below macro is ‘VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help".
Sub VBA_Replace_Function_Ex1()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1"
    
    sSubString = Replace(sString, "F1", "Help")
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA Replace Function

Example 2: Replace all occurrences of substring “Help” with “F1”

Here is a simple example of the VBA Replace function. This below example macro returns a string. The output of the below macro is ‘VBAF1’.

'Replace all occurrences of sub-string "Help" with "F1".
Sub VBA_Replace_Function_Ex2()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1"
    
    sSubString = Replace(sString, "Help", "F1")
    
    MsgBox "Replace Help with F1 :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA Replace Function

Example 3: Replace all occurrences of sub-string “F1” with “Help” starting from position 13

Here is a simple example of the VBA Replace function. This below example macro returns a string. It ignores specified ‘N(start)’ characters, when we specify start position. The output of the below macro is ‘VBAHelp-VBAHelp-VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help" starting from position 13
Sub VBA_Replace_Function_Ex3()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Replace(sString, "F1", "Help", 13)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA Replace Function

Example 4: Replace all occurrences of sub-string “F1” with “Help” starting from position 13 and keep whole string

Here is a simple example of the VBA Replace function. This below example macro returns a string. It ignores specified ’13(start)’ characters, when we specify start position. In this example we are using left function to extract left most characters from the given string. And adding the output to original output. Here is the final output of the below macro is ‘VBAF1-VBAF1-VBAHelp-VBAHelp-VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help" starting from position 13 and keep whole string
Sub VBA_Replace_Function_Ex4()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Left(sString, 12) & Replace(sString, "F1", "Help", 13)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA Replace Function

Example 5: Replace last occurrence of sub-string “F1” with “Help”

Here is a simple example of the VBA Replace function. This below example macro returns a string. Here is the final output of the below macro is ‘VBAF1-VBAF1-VBAF1-VBAF1-VBAHelp’.

'Replace last occurrence of substring "F1" with "Help"
Sub VBA_Replace_Function_Ex5()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sString = StrReverse(sString)
    
    sString = Replace(sString, StrReverse("F1"), StrReverse("Help"), , 1)
    
    sSubString = StrReverse(sString)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA Replace Function

Example 6: Remove all occurrences of sub-string ‘F1’

Here is a simple example of the VBA Replace function. This below example macro returns a string. It removes all occurrences of sub-string within a string. Here is the final output of the below macro is ‘VBA-VBA-VBA-VBA-VBA’.

'Remove all occurrences of sub-string 'F1'
Sub VBA_Replace_Function_Ex6()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Replace(sString, "F1", "")
    
    MsgBox "Remove all occurences of F1 :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the sixth example output.
VBA Replace Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

In this Article

  • VBA Find
  • Find VBA Example
  • VBA Find without Optional Parameters
    • Simple Find Example
    • Find Method Notes
    • Nothing Found
  • Find Parameters
    • After Parameter and Find Multiple Values
    • LookIn Parameter
    • Using the LookAt Parameter
    • SearchOrder Parameter
    • SearchDirection Parameter
    • MatchByte Parameter
    • SearchFormat Parameter
    • Using Multiple Parameters
  • Replace in Excel VBA
    • Replace Without Optional Parameters
  • Using VBA to Find or Replace Text Within a VBA Text String
    • INSTR – Start
    • VBA Replace Function

This tutorial will demonstrate how to use the Find and Replace methods in Excel VBA.

VBA Find

Excel has excellent built-in Find and Find & Replace tools.

They can be activated with the shortcuts CTRL + F (Find) or CTRL + H (Replace) or through the Ribbon: Home > Editing > Find & Select.

find excel vba

By clicking Options, you can see advanced search options:

advanced find vba

You can easily access these methods using VBA.

Find VBA Example

To demonstrate the Find functionality, we created the following data set in Sheet1.

PIC 02

If you’d like to follow along, enter the data into your own workbook.

VBA Find without Optional Parameters

When using the VBA Find method, there are many optional parameters that you can set.

We strongly recommend defining all parameters whenever using the Find Method!

If you don’t define the optional parameters, VBA will use the currently selected parameters in Excel’s Find window. This means, you may not know what search parameters are being used when the code is ran. Find could be ran on the entire workbook or a sheet. It could search for formulas or values. There’s no way to know, unless you manually check what’s currently selected in Excel’s Find Window.

For simplicity, we will start with an example with no optional parameters defined.

Simple Find Example

Let’s look at a simple Find example:

Sub TestFind()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("employee")
MsgBox MyRange.Address
MsgBox MyRange.Column
MsgBox MyRange.Row

End Sub

This code searches for “employee” in the Used Range of Sheet1. If it finds “employee”, it will assign the first found range to range variable MyRange.

Next, Message Boxes will display with the address, column, and row of the found text.

In this example, the default Find settings are used (assuming they have not been changed in Excel’s Find Window):

  • The search text is partially matched to the cell value (an exact cell match is not required)
  • The search is not case sensitive.
  • Find only searches a single worksheet

These settings can be changed with various optional parameters (discussed below).

Find Method Notes

  • Find does not select the cell where the text is found.  It only identifies the found range, which you can manipulate in your code.
  • The Find method will only locate the first instance found.
  • You can use wildcards (*) e.g. search for ‘E*’

Nothing Found

If the search text does not exist, then the range object will remain empty. This causes a major problem when your code tries to display the location values because they do not exist.  This will result in an error message which you do not want.

Fortunately, you can test for an empty range object within VBA using the Is Operator:

If Not MyRange Is Nothing Then

Adding the code to our previous example:

Sub TestFind()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("employee")
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
    MsgBox MyRange.Column
    MsgBox MyRange.Row
Else
    MsgBox "Not found"
End If
End Sub 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Find Parameters

So far, we have only looked at a basic example of using the Find method.  However, there are a number of optional parameters available to help you refine your search

Parameter Type Description Values
What Required The value to search for Any data type such as a string or numeric
After Optional Single cell reference to begin your search Cell address
LookIn Optional Use Formulas, Values, Comments for search xlValues, xlFormulas, xlComments
LookAt Optional Match part or whole of a cell xlWhole, xlPart
SearchOrder Optional The Order to search in – rows or columns xlByRows, xlByColummns
SearchDirection Optional Direction for search to go in – forward or backward xlNext, xlPrevious
MatchCase Optional Search is case sensitive or not True or False
MatchByte Optional Used only if you have installed double byte language support e.g. Chinese language True or False
SearchFormat Optional Allow searching by format of cell True or False

After Parameter and Find Multiple Values

You use the After parameter to specify the starting cell for your search. This is useful where there is more than one instance of the value that you are searching for.

If a search has already found one value and you know that there will be more values found, then you use the Find method with the ‘After’ parameter to record the first instance and then use that cell as the starting point for the next search.

You can use this to find multiple instances of your search text:

Sub TestMultipleFinds()
Dim MyRange As Range, OldRange As Range, FindStr As String

'Look for first instance of "‘Light & Heat"
Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat")

'If not found then exit
If MyRange Is Nothing Then Exit Sub

'Display first address found
MsgBox MyRange.Address

'Make a copy of the range object
Set OldRange = MyRange

'Add the address to the string delimiting with a "|" character
FindStr = FindStr & "|" & MyRange.Address

'Iterate through the range looking for other instances
Do
    'Search for ‘Light & Heat’ using the previous found address as the After parameter   
    Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat", After:=Range(OldRange.Address))

    'If the address has already been found then exit the do loop – this stops continuous looping
    If InStr(FindStr, MyRange.Address) Then Exit Do
    
    'Display latest found address
    MsgBox MyRange.Address

    'Add the latest address to the string of addresses
    FindStr = FindStr & "|" & MyRange.Address

    'make a copy of the current range
     Set OldRange = MyRange
Loop
End Sub

This code will iterate through the used range, and will display the address every time it finds an instance of ‘Light & Heat’

Note that the code will keep looping until a duplicate address is found in FindStr, in which case it will exit the Do loop.

LookIn Parameter

You can use the LookIn parameter to specify which component of the cell you want to search in.  You can specify values, formulas, or comments in a cell.

  • xlValues – Searches cell values (the final value of a cell after it’s calculation)
  • xlFormulas – Searches within the cell formula itself (whatever is entered into the cell)
  • xlComments – Searches within cell notes
  • xlCommentsThreaded – Searches within cell comments

Assuming that a formula has been entered on the worksheet, you could use this example code to find the first location of any formula:

Sub TestLookIn()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("=", LookIn:=xlFormulas)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address   
Else
    MsgBox "Not found"
 End If
End Sub

If the ‘LookIn’ parameter was set to xlValues, the code would display a ‘Not Found’ message. In this example it will return B10.

VBA Programming | Code Generator does work for you!

Using the LookAt Parameter

The LookAt parameter determines whether find will search for an exact cell match, or search for any cell containing the search value.

  • xlWhole – Requires the entire cell to match the search value
  • xlPart – Searches within a cell for the search string

This code example will locate the first cell containing the text “light”. With Lookat:=xlPart, it will return a match for “Light & Heat”.

Sub TestLookAt()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("light", Lookat:=xlPart)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
  Else
    MsgBox "Not found"  
End If
End Sub

If xlWhole was set, a match would only return if the cell value was “light”.

SearchOrder Parameter

The SearchOrder parameter dictates how the search will be carried out throughout the range.

  • xlRows – Search is done row by row
  • xlColumns – Search is done column by column
Sub TestSearchOrder()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("employee", SearchOrder:=xlColumns)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

This influences which match will be found first.

Using the test data entered into the worksheet earlier, when the search order is columns, the located cell is A5.  When the search order parameter is changed to xlRows, the located cell is C4

This is important if you have duplicate values within the search range and you want to find the first instance under a particular column name.

SearchDirection Parameter

The SearchDirection parameter dictates which direction the search will go in – effectively forward or backwards.

  • xlNext – Search for next matching value in range
  • xlPrevious – Search for previous matching value in range

Again, if there are duplicate values within the search range, it can have an effect on which one is found first.

Sub TestSearchDirection()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", SearchDirection:=xlPrevious)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

Using this code on the test data, a search direction of xlPrevious will return a location of C9.  Using the xlNext parameter will return a location of A4.

The Next parameter means that the search will begin in the top left-hand corner of the search range and work downwards. The Previous parameter means that the search will start in the bottom right-hand corner of the search range and work upwards.

MatchByte Parameter

The MatchBye parameter is only used for languages which use a double byte to represent each character, such as Chinese, Russian, and Japanese.

If this parameter is set to ‘True’ then Find will only match double-byte characters with double-byte characters.  If the parameter is set to ‘False’, then a double-byte character will match with single or double-byte characters.

SearchFormat Parameter

The SearchFormat parameter enables you to search for matching cell formats. This could be a particular font being used, or a bold font, or a text color.  Before you use this parameter, you must set the format required for the search using the Application.FindFormat property.

Here is an example of how to use it:

Sub TestSearchFormat()
Dim MyRange As Range

Application.FindFormat.Clear
Application.FindFormat.Font.Bold = True
Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", Searchformat:=True)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
Application.FindFormat.Clear
End Sub

In this example, the FindFormat property is set to look for a bold font. The Find statement then searches for the word ‘heat’ setting the SearchFormat parameter to True so that it will only return an instance of that text if the font is bold.

In the sample worksheet data shown earlier, this will return A9, which is the only cell containing the word ‘heat’ in a bold font.

Make sure that the FindFormat property is cleared at the end of the code.  If you do not your next search will still take this into account and return incorrect results.

Where you use a SearchFormat parameter, you can also use a wildcard (*) as the search value.  In this case it will search for any value with a bold font:

Set MyRange = Sheets("Sheet1").UsedRange.Find("*", Searchformat:=True)

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Using Multiple Parameters

All the search parameters discussed here can be used in combination with each other if required.

For example, you could combine the ‘LookIn’ parameter with the ‘MatchCase’ parameter so that you look at the whole of the cell text, but it is case-sensitive

Sub TestMultipleParameters()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat", LookAt:=xlWhole, MatchCase:=True)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

In this example, the code will return A4, but if we only used a part of the text e.g. ‘heat’, nothing would be found because we are matching on the whole of the cell value.  Also, it would fail due to the case not matching.

Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", LookAt:=xlWhole, MatchCase:=True)

Replace in Excel VBA

There is, as you may expect, a Replace function in Excel VBA, which works in a very similar way to ‘Find’ but replaces the values at the cell location found with a new value.

These are the parameters that you can use in a Replace method statement.  These operate in exactly the same way as for the Find method statement.  The only difference to ‘Find’ is that you need to specify a Replacement parameter.

Name Type Description Values
What Required The value to search for Any data type such as a string or numeric
Replacement Required The replacement string. Any data type such as a string or numeric
LookAt Optional Match part or the whole of a cell xlPart or xlWhole
SearchOrder Optional The order to search in – Rows or Columns xlByRows or xlByColumns
MatchCase Optional Search is case sensitive or not True or False
MatchByte Optional Used only if you have installed double byte language support True or False
SearchFormat Optional Allow searching by format of cell True or False
ReplaceFormat Optional The replace format for the method. True or False

The Replace Format parameter searches for a cell with a particular format e.g. bold in the same way the SearchFormat parameter operates in the Find method. You need to set the Application.FindFormat property first, as shown in the Find example code shown earlier 

Replace Without Optional Parameters

At its simplest, you only need to specify what you are searching for and what you want to replace it with.

Sub TestReplace()
Sheets("Sheet1").UsedRange.Replace What:="Light & Heat", Replacement:="L & H"
End Sub

Note that the Find method will only return the first instance of the matched value, whereas the Replace method works through the entire range specified and replaces everything that it finds a match on.

The replacement code shown here will replace every instance of ‘Light & Heat’ with ‘L & H’ through the entire range of cells defined by the UsedRange object

Using VBA to Find or Replace Text Within a VBA Text String

The above examples work great when using VBA to interact with Excel data. However, to interact with VBA strings, you can use built-in VBA Functions like INSTR and REPLACE.

You can use the INSTR Function to locate a string of text within a longer string.

Sub TestInstr()
MsgBox InStr("This is MyText string", "MyText")
End Sub

This example code will return the value of 9, which is the number position where ‘MyText’ is found in the string to be searched.

Note that it is case sensitive. If ‘MyText’ is all lower case, then a value of 0 will be returned which means that the search string was not found. Below we will discuss how to disable case-sensitivity.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

INSTR – Start

There are two further optional parameters available.  You can specify the start point for the search:

MsgBox InStr(9, "This is MyText string", "MyText")

The start point is specified as 9 so it will still return 9.  If the start point was 10, then it would return 0 (no match) as the start point would be too far forward.

INSTR – Case Sensitivity

You can also set a Compare parameter to vbBinaryCompare or vbTextCompare. If you set this parameter, the statement must have a start parameter value.

  • vbBinaryCompare – Case-sensitive (Default)
  • vbTextCompare – Not Case-sensitive
MsgBox InStr(1, "This is MyText string", "mytext", vbTextCompare)

This statement will still return 9, even though the search text is in lower case.

To disable case-sensitivity you can also declare Option Compare Text at the top of your code module.

VBA Replace Function

If you wish to replace characters in a string with different text within your code, then the Replace method is ideal for this:

Sub TestReplace()
MsgBox Replace("This is MyText string", "MyText", "My Text")
End Sub

This code replaces ‘MyText’ with ‘My Text’.  Note that the search string is case sensitive as a binary compare is the default.

You can also add other optional parameters:

  • Start – defines position in the initial string that the replacement has to start from. Unlike in the Find method, it returns a truncated string starting from the character number defined by the Start parameter.
  • Count – defines the number of replacements to be made.  By default, Replace will change every instance of the search text found, but you can limit this to a single replacement by setting the Count parameter to 1
  • Compare – as in the Find method you can specify a binary search or a text search using vbBinaryCompare or vbTextCompare.  Binary is case sensitive and text is non case sensitive
MsgBox Replace("This is MyText string (mytext)", "MyText", "My Text", 9, 1, vbTextCompare)

This code returns ‘My Text string (mytext)’. This is because the start point given is 9, so the new returned string starts at character 9.   Only the first ‘MyText’ has been changed because the Count parameter is set to 1.

The Replace method is ideal for solving problems like peoples’ names containing apostrophes e.g. O’Flynn. If you are using single quotes to define a string value and there is an apostrophe, this will cause an error because the code will interpret the apostrophe as the end of the string and will not recognize the remainder of the string.

You can use the Replace method to replace the apostrophe with nothing, removing it completely.

Excel VBA Tutorial about replacing or substituting strings or characters within strings with macrosIn this VBA Tutorial, you learn how to replace or substitute substrings or characters within strings.

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

Use the following Table of Contents to navigate to the section you’re interested in.

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Learn about commonly-used VBA terms here.
    • Learn about the Excel Object Model here.
    • Learn about working with variables here.
    • Learn about data types here.
    • Learn about working with arrays here.
  • Practical VBA applications and macro examples:
    • Learn about referring to cell ranges here.
    • Learn about working with worksheet functions within VBA here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Replace String in Cell

VBA Code to Replace String in Cell

To replace a string in a cell with VBA, use a statement with the following structure:

Cell.Value = Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString, Count:=NumberOfReplacements)

Process Followed by VBA Code to Replace String in Cell

Work with Range.Value property of Cell > Replace StringToReplace with ReplacementString > Assign string to Range.Value property

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    1. VBA Construct: Assignment operator.
    2. Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
  4. Item: Replace(…).
    • VBA Construct: Replace function.
    • Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString) a specific number of times (NumberOfReplacements).
  5. Item: Expression:=Cell.Value.
    • VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
    • Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
  6. Item: Find:=StringToReplace.
    • VBA Construct: Find parameter of the Replace function.
    • Description: The Find parameter of the Replace function specifies the substring you search for and replace.

      If you explicitly declare a variable to represent StringToReplace, use the String data type.

  7. Item: Replace:=ReplacementString.
    • VBA Construct: Replace parameter of the Replace function.
    • Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.

      If you explicitly declare a variable to represent ReplacementString, use the String data type.

  8. Item: Count:=NumberOfReplacements.
    • VBA Construct: Count parameter of the Replace function.
    • Description: The Count parameter of the Replace function specifies the number of substitutions you want to carry out. In other words, the number of times you want to replace StringToReplace with ReplacementString.

      If you want VBA to replace all occurrences of StringToReplace with ReplacementString, omit the Count parameter. In such case, Count defaults to -1 and VBA carries out all possible substitutions. Please refer to the appropriate section (Replace All Occurrences of String in Cell) below for further information about this scenario.

Macro Example to Replace String in Cell

The following macro replaces the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) one time (myNumberOfReplacements) within the string in cell A5 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceStringInCell()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for string replacement (string to replace, replacement string, and number of replacements)
    Dim myStringToReplace As String
    Dim myReplacementString As String
    Dim myNumberOfReplacements As Long

    'identify cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A5")

    'specify parameters for string replacement (string to replace, replacement string, and number of replacements)
    myStringToReplace = "replace"
    myReplacementString = "substitute"
    myNumberOfReplacements = 1

    'replace string in cell you work with, and assign resulting string to Range.Value property of cell you work with
    myCell.Value = Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString, Count:=myNumberOfReplacements)

End Sub

Effects of Executing Macro Example to Replace String in Cell

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “replace” with the string “substitute” one time within the string in cell A5.

Macro replaces string in cell

#2: Replace String in Cell Specifying a Starting Position for Search

VBA Code to Replace String in Cell Specifying a Starting Position for Search

To replace a string in a cell and specify the starting position to search for the string with VBA, use a statement with the following structure:

Cell.Value = Left(String:=Cell.Value, Length:=StartPosition - 1) & Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString, Start:=StartPosition, Count:=NumberOfReplacements)

Process Followed by VBA Code to Replace String in Cell Specifying a Starting Position for Search

Work with Range.Value property > Return first characters of string > Replace StringToReplace with ReplacementString > Concatenate > Assign string to Range.Value property

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    • VBA Construct: Assignment operator.
    • Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
  4. Item: Left(…).
    • VBA Construct: Left function.
    • Description: The Left function returns a string containing the number of characters specified by the Length parameter (StartPosition – 1) from the left side of the string specified by the String parameter (Cell.Value).

      Within this macro structure, you use the Left function to return the substring containing the first characters of the string within the cell you work with. This substring goes from the first character of the string to the character immediately before the position within the string where you start searching for the substring you want to replace (StringToReplace).

      You need to do this because the Replace function doesn’t return a copy of the string (with substitutions) from start to finish. The string that Replace returns starts at the position within the string where you start searching for the substring you want to replace (StartPosition). Therefore, VBA truncates the string and the characters to the left of StartPosition aren’t part of the string returned by Replace.

  5. Item: String:=Cell.Value.
    • VBA Construct: String parameter of the Left function, Range object and Range.Value property.
    • Description: The String parameter of the Left function specifies the string expression containing the substring you want to replace (StringToReplace).

      Within this macro structure, String is the value (string) within Cell, as returned by the Range.Value property. The value of the String parameter of the Left function is the same as the value of the Expression parameter of the Replace function.

  6. Item: Length:=StartPosition – 1.
    • VBA Construct: Length parameter of the Left function.
    • Description: The Length parameter of the Left function specifies the number of characters the Left function returns from the string you work with. StartPosition is the position within the string where you start searching for the substring you want to replace (StringToReplace). (StartPosition – 1) is the position of the character immediately before StartPosition. Therefore, the Left function returns the substring containing the first characters of the string within the cell you work with, up until the character located in position (StartPosition – 1).

      If you explicitly declare a variable to represent StartPosition, use the Long data type. The value of StartPosition within the Length parameter of the Left function is the same as the value of the Start parameter of the Replace function.

  7. Item: &.
    • VBA Construct: Concatenation operator.
    • Description: The & operator concatenates the strings returned by the Left and Replace functions.
  8. Item: Replace(…).
    • VBA Construct: Replace function.
    • Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString) a specific number of times (NumberOfReplacements).
  9. Item: Expression:=Cell.Value.
    • VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
    • Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
  10. Item: Find:=StringToReplace.
    • VBA Construct: Find parameter of the Replace function.
    • Description: The Find parameter of the Replace function specifies the substring you search for and replace.

      If you explicitly declare a variable to represent StringToReplace, use the String data type.

  11. Item: Replace:=ReplacementString.
    • VBA Construct: Replace parameter of the Replace function.
    • Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.

      If you explicitly declare a variable to represent ReplacementString, use the String data type.

  12. Item: Start:=StartPosition.
    • VBA Construct: Start parameter of the Replace function.
    • Description: The Start parameter of the Replace function specifies the position within the string you work with where you start searching for StringToReplace.

      The default value of the Start parameter is 1. In such case, the Replace function doesn’t truncate the string. Therefore, you generally don’t have to work with the Left function and concatenation operator. Please refer to the appropriate section (Replace String in Cell) above for further information about this scenario.

  13. Item: Count:=NumberOfReplacements.
    • VBA Construct: Count parameter of the Replace function.
    • Description: The Count parameter of the Replace function specifies the number of substitutions you want to carry out. In other words, the number of times you want to replace StringToReplace with ReplacementString.

      If you want VBA to replace all occurrences of StringToReplace after StartPosition with ReplacementString, omit the Count parameter. In such case, Count defaults to -1 and VBA carries out all possible substitutions. Please refer to the appropriate section (Replace All Occurrences of String in Cell) below for further information about this scenario.

Macro Example to Replace String in Cell Specifying a Starting Position for Search

The following macro replaces the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) one time (myNumberOfReplacements) within the string in cell A6 of the worksheet named “Excel VBA Replace” (myCell). The search for myStringToReplace begins in position 14 (myStartPosition) of the string in myCell.

Sub replaceStringInCellWithStartPosition()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for string replacement (string to replace, replacement string, start position for search of string to replace, and number of replacements)
    Dim myStringToReplace As String
    Dim myReplacementString As String
    Dim myStartPosition As Long
    Dim myNumberOfReplacements As Long

    'identify cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A6")

    'specify parameters for string replacement (string to replace, replacement string, start position for search of string to replace, and number of replacements)
    myStringToReplace = "replace"
    myReplacementString = "substitute"
    myStartPosition = 14
    myNumberOfReplacements = 1

    'return and concatenate the following strings, and assign the resulting (concatenated) string to Range.Value property of cell you work with
        '(i) string containing the first characters within the cell you work with (from first position up to the character before the start position for search of string to replace)
        '(ii) string resulting from working with the Replace function and the parameter for string replacement you specify
    myCell.Value = Left(String:=myCell.Value, Length:=myStartPosition - 1) & Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString, Start:=myStartPosition, Count:=myNumberOfReplacements)

End Sub

Effects of Executing Macro Example to Replace String in Cell Specifying a Starting Position for Search

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “replace” with the string “substitute” one time within the string in cell A6. The search for myStringToReplace begins in position 14 of the string in cell A6. This matches with the second occurrence of the “replace” string.

Macro replaces string in cell starting search in specified position

#3: Replace All Occurrences of String in Cell

VBA Code to Replace All Occurrences of String in Cell

To replace all occurrences of a string in a cell with VBA, use a statement with the following structure:

Cell.Value = Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString)

Process Followed by VBA Code to Replace All Occurrences of String in Cell

Work with Range.Value property of Cell > Replace all occurrences of StringToReplace with ReplacementString > Assign string to Range.Value property

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    1. VBA Construct: Assignment operator.
    2. Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
  4. Item: Replace(…).
    • VBA Construct: Replace function.
    • Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString). Within this macro structure, Replace carries out all possible substitutions.
  5. Item: Expression:=Cell.Value.
    • VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
    • Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
  6. Item: Find:=StringToReplace.
    • VBA Construct: Find parameter of the Replace function.
    • Description: The Find parameter of the Replace function specifies the substring you search for and replace.

      If you explicitly declare a variable to represent StringToReplace, use the String data type.

  7. Item: Replace:=ReplacementString.
    • VBA Construct: Replace parameter of the Replace function.
    • Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.

      If you explicitly declare a variable to represent ReplacementString, use the String data type.

Macro Example to Replace All Occurrences of String in Cell

The following macro replaces all occurrences of the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) within the string in cell A7 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceAll()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for string replacement (string to replace and replacement string)
    Dim myStringToReplace As String
    Dim myReplacementString As String

    'identify cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A7")

    'specify parameters for string replacement (string to replace and replacement string)
    myStringToReplace = "replace"
    myReplacementString = "substitute"

    'replace all occurrences within string in cell you work with, and assign resulting string to Range.Value property of cell you work with
    myCell.Value = Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString)

End Sub

Effects of Executing Macro Example to Replace All Occurrences of String in Cell

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all (2) occurrences of the string “replace” with the string “substitute” within the string in cell A7.

Macro replaces all occurrences of string in cell

#4: Replace Character in String

VBA Code to Replace Character in String

To replace a character in a string within a cell with VBA, use a statement with the following structure:

Cell.Value = Replace(Expression:=Cell.Value, Find:=CharacterToReplace, Replace:=ReplacementCharacter)

Process Followed by VBA Code to Replace Character in String

Work with Range.Value property > Replace all occurrences of CharacterToReplace with ReplacementCharacter > Assign string to Range.Value property

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    1. VBA Construct: Assignment operator.
    2. Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
  4. Item: Replace(…).
    • VBA Construct: Replace function.
    • Description: The Replace function returns a string where a specific character (CharacterToReplace) is replaced by another character (ReplacementCharacter). Within this macro structure, Replace carries out all possible substitutions.
  5. Item: Expression:=Cell.Value.
    • VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
    • Description: The Expression parameter of the Replace function specifies the string expression containing the character you want to replace (CharacterToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
  6. Item: Find:=CharacterToReplace.
    • VBA Construct: Find parameter of the Replace function.
    • Description: The Find parameter of the Replace function specifies the character you search for and replace.

      If you explicitly declare a variable to represent CharacterToReplace, use the String data type.

  7. Item: Replace:=ReplacementCharacter.
    • VBA Construct: Replace parameter of the Replace function.
    • Description: The Replace parameter of the Replace function specifies the character you want to use as replacement for CharacterToReplace.

      If you explicitly declare a variable to represent ReplacementCharacter, use the String data type.

Macro Example to Replace Character in String

The following macro replaces all occurrences of the character “a” (myCharacterToReplace) with the character “e” (myReplacementCharacter) within the string in cell A8 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceCharacterInString()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for character replacement (character to replace and replacement character)
    Dim myCharacterToReplace As String
    Dim myReplacementCharacter As String

    'identify cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A8")

    'specify parameters for string replacement (character to replace and replacement character)
    myCharacterToReplace = "a"
    myReplacementCharacter = "e"

    'replace all occurrences of character within string in cell you work with, and assign resulting string to Range.Value property of cell you work with
    myCell.Value = Replace(Expression:=myCell.Value, Find:=myCharacterToReplace, Replace:=myReplacementCharacter)

End Sub

Effects of Executing Macro Example to Replace Character in String

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all occurrences of the character “a” with the character “e” within the string in cell A8.

Macro replaces character in string

#5: Replace Multiple Characters in String

VBA Code to Replace Multiple Characters in String

To replace multiple characters in a string with VBA, use a macro with the following statement structure:

Dim StringReplace As String
StringReplace = Cell.Value
For Each Character In Array(CharactersList)
    StringReplace = Replace(Expression:=StringReplace, Find:=Character, Replace:=ReplacementCharacter)
Next Character
Cell.Value = StringReplace

Process Followed by VBA Code to Replace Multiple Characters in String

Assign value returned by Range.Value to StringReplace > Loop through all elements of array containing CharactersList > Replace all occurrences of current array element > Assign string to StringReplace variable

VBA Statement Explanation

Line #1: Dim StringReplace As String

  1. Item: Dim StringReplace As String.
    • VBA Construct: Dim statement.
    • Description: The Dim statement declares the StringReplace variable as of the String data type.

      StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).

Line #2: StringReplace = Cell.Value

  1. Item: StringReplace.
    • VBA Construct: Variable of the string data type.
    • Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
  2. Item: =.
    • VBA Construct: Assignment operator.
    • Description: The = operator assigns the string returned by the Range.Value property to the StringReplace variable.
  3. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  4. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property returns the value (in this case string) within Cell.

Lines #3 and #5: For Each Character In Array(CharactersList) | Next Character

  1. Item: For Each… In… Next.
    • VBA Construct: For Each… Next statement.
    • Description: The For Each… Next statement repeats the statement within the loop (line #4) for each element (Character) in the array returned by the Array function (Array(CharactersList)).
  2. Item: Character.
    • VBA Construct: Element of For Each… Next statement and variable of the Variant data type.
    • Description: The Element of the For Each… Next statement is a variable used to iterate through the elements of the array returned by the Array function (Array(CharactersList)).

      If you explicitly declare a variable to represent Character, use the Variant data type.

  3. Item: Array(CharactersList).
    • VBA Construct: Array function.
    • Description: The Array function returns a Variant containing an array. CharactersList is the comma-delimited list of characters (passed as strings) that you assign to each of the array elements

Line #4: StringReplace = Replace(Expression:=StringReplace, Find:=Character, Replace:=ReplacementCharacter)

  1. Item: StringReplace.
    • VBA Construct: Variable of the String data type.
    • Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
  2. Item: =.
    1. VBA Construct: Assignment operator.
    2. Description: The = operator assigns the string returned by the Replace function to StringReplace.
  3. Item: Replace(…).
    • VBA Construct: Replace function.
    • Description: The Replace function returns a string (starting with StringReplace) where a specific character (Character) is replaced by another character (ReplacementCharacter). Within this macro structure, Replace carries out all possible substitutions.
  4. Item: Expression:=StringReplace.
    • VBA Construct: Expression parameter of the Replace function and variable of the String data type.
    • Description: The Expression parameter of the Replace function specifies the string expression (StringReplace) containing the characters you want to replace (CharactersList).
  5. Item: Find:=Character.
    • VBA Construct: Find parameter of the Replace function and variable of the Variant data type.
    • Description: The Find parameter of the Replace function specifies the character you search for and replace.

      Within this macro structure, Character is also the Element of the For Each… Next statement. This is the variable used to iterate through the elements of the array returned by the Array function (Array(CharactersList)).

      If you explicitly declare a variable to represent Character, use the Variant data type.

  6. Item: Replace:=ReplacementCharacter.
    • VBA Construct: Replace parameter of the Replace function.
    • Description: The Replace parameter of the Replace function specifies the character you want to use as replacement for the characters you want to replace (CharactersList).

      If you explicitly declare a variable to represent ReplacementCharacter, use the String data type.

Line #6: Cell.Value = StringReplace

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    • VBA Construct: Assignment operator.
    • Description: The = operator assigns the string represented by the StringReplace variable to the Range.Value property of Cell.
  4. Item: StringReplace.
    • VBA Construct: Variable of the String data type.
    • Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).

Macro Example to Replace Multiple Characters in String

The following macro replaces all occurrences of the characters “a”, “e” and “i” (myCharactersArray) with the character “o” (myReplacementCharacter) within the string in cell A9 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceMultipleCharactersInString()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold string you work with and replacement character
    Dim myString As String
    Dim myReplacementCharacter As String

    'declare variable to hold Variant containing array whose elements are characters to replace, and variable used to iterate through the elements of the array
    Dim myCharactersArray() As Variant
    Dim iCharacter As Variant

    'identify the cell you work with and the string within that cell
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A9")
    myString = myCell.Value

    'specify elements of array (characters to replace) and replacement character
    myCharactersArray = Array("a", "e", "i")
    myReplacementCharacter = "o"

    'loop through each element (iCharacter) of the array (myCharacterArray)
    For Each iCharacter In myCharactersArray

        'replace all occurrences of element (iCharacter) within current version of string you work with (myString), and assign resulting string to myString variable
        myString = Replace(Expression:=myString, Find:=iCharacter, Replace:=myReplacementCharacter)

    Next iCharacter

    'assign string represented by myString variable to Range.Value property of cell you work with
    myCell.Value = myString

End Sub

Effects of Executing Macro Example to Replace Multiple Characters in String

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all occurrences of the characters “a”, “e” and “i” with the character “o” within the string in cell A9.

Macro replaces multiple characters in string

#6: Replace Wildcard

VBA Code to Replace Wildcard

To replace characters in a string within a cell using a wildcard with VBA, use a statement with the following structure:

Cell.Replace What:=StringToReplace, Replacement:=ReplacementString, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

Process Followed by VBA Code to Replace Wildcard

Identify Cell > Replace StringToReplace with ReplacementString and use wildcards when specifying StringToReplace

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Replace.
    • VBA Construct: Range.Replace method.
    • Description: The Range.Replace method replaces a specific substring (StringToReplace) by another substring (ReplacementString) within Cell.
  3. Item: What:=StringToReplace.
    • VBA Construct: What parameter of the Range.Replace method.
    • Description: The What parameter of the Range.Replace method specifies the string you want to replace (StringToReplace).

      When specifying StringToReplace, use the following wildcards as required:

      • Question mark (?): The question mark represents any single character. For example, “w?ldcard” represents a string (i) starting with a “w”, (ii) followed by any single character (including “i”), and (iii) ending with “lcard”.
      • Asterisk (*): The asterisk represents any group of characters. For example, “w*card” represents a string (i) starting with a “w”, (ii) followed by any group of characters (including “ild”), and (iii) ending with “card”.

      If you explicitly declare a variable to represent StringToReplace, use the String data type.

  4. Item: Replacement:=ReplacementString.
    • VBA Construct: Replacement parameter of the Range.Replace method.
    • Description: The Replacement parameter of the Range.Replace method specifies the substring you want to use as replacement for StringToReplace.
  5. Item: LookAt:=xlPart.
    • VBA Construct: LookAt parameter of the Range.Replace method.
    • Description: The LookAt parameter of the Range.Replace method specifies that Range.Replace looks at (and matches) a part (xlPart) of the search data.
  6. Item: SearchOrder:=xlByRows.
    • VBA Construct: SearchOrder parameter of the Range.Replace method.
    • Description: The SearchOrder parameter of the Range.Replace method specifies that Range.Replace searches by rows (xlByRows).
  7. Item: MatchCase:=False.
    • VBA Construct: MatchCase parameter of the Range.Replace method.
    • Description: The MatchCase parameter of the Range.Replace method specifies that the search isn’t case sensitive (False).
  8. Item: SearchFormat:=False.
    • VBA Construct: SearchFormat parameter of the Range.Replace method.
    • Description: The SearchFormat parameter of the Range.Replace method specifies that the search doesn’t consider formatting (False).
  9. Item: ReplaceFormat:=False.
    • VBA Construct: ReplaceFormat parameter of the Range.Replace method.
    • Description: The ReplaceFormat parameter of the Range.Replace method specifies that no replace format is set (False).

Macro Example to Replace Wildcard

The following macro replaces the string (i) starting with a “w”, (ii) followed by any group of characters (including “ild”), and (iii) ending with “card” (myStringToReplace), with the string “question mark” (myReplacementString) within the string in cell A10 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceWildcard()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for string replacement (string to replace and replacement string)
    Dim myStringToReplace As String
    Dim myReplacementString As String

    'identify the cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A10")

    'specify parameters for string replacement (string to replace and replacement string). Use wildcards (? or *) to specify string to replace
    myStringToReplace = "w*card"
    myReplacementString = "question mark"

    'replace all occurrences within string in cell you work with, and assign resulting string to Range.Value property of cell you work with
    myCell.Replace What:=myStringToReplace, Replacement:=myReplacementString, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

End Sub

Effects of Executing Macro Example to Replace Wildcard

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “wildcard” which (i) starts with a “w”, (ii) followed by a group of characters (“ild”), and (iii) ends with “card”, with the string “question mark” within the string in cell A10.

Macro replaces wildcard

#7: Replace Character in String by Position

VBA Code to Replace Character in String by Position

To replace a character in a string within a cell according to its position with VBA, use a statement with the following structure:

Cell.Value = WorksheetFunction.Replace(Cell.Value, CharacterPosition, CharactersToReplace, ReplacementString)

Process Followed by VBA Code to Replace Character in String by Position

Identify substring to replace based on position and number of characters > Replace with ReplacementString > Assign string to Range.Value property

VBA Statement Explanation

  1. Item: Cell.
    • VBA Construct: Range object.
    • Description: Range object representing the cell you work with.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.

  2. Item: Value.
    • VBA Construct: Range.Value property.
    • Description: The Range.Value property specifies the value (in this case string) within Cell.
  3. Item: =.
    1. VBA Construct: Assignment operator.
    2. Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
  4. Item: WorksheetFunction.Replace(…).
    • VBA Construct: WorksheetFunction.Replace method.
    • Description: The WorksheetFunction.Replace method replaces a substring with a different string (ReplacementString). The replaced substring is determined based on its position within the string you work with (CharacterPosition) and the number of characters to replace (CharactersToReplace).
  5. Item: Cell.Value.
    • VBA Construct: Arg1 parameter of the WorksheetFunction.Replace method, Range object and Range.Value property.
    • Description: The Arg1 parameter of the WorksheetFunction.Replace method specifies the string containing the substring you want to replace. Within this macro structure, Arg1 is the value (string) within Cell, as returned by the Range.Value property.

      If you explicitly declare a variable to represent Arg1, use the String data type.

  6. Item: CharacterPosition.
    • VBA Construct: Arg2 parameter of the WorksheetFunction.Replace method.
    • Description: The Arg2 parameter of the WorksheetFunction.Replace method specifies the starting position within Arg1 (Cell.Value) of the substring you want to replace with Arg4 (ReplacementString).

      If you explicitly declare a variable to represent Arg2 (CharacterPosition), use the Double data type.

  7. Item: CharactersToReplace.
    • VBA Construct: Arg3 parameter of the WorksheetFunction.Replace method.
    • Description: The Arg3 parameter of the WorksheetFunction.Replace method specifies the number of characters within Arg1 (Cell.Value) you want to replace with Arg4 (ReplacementString).

      If you explicitly declare a variable to represent Arg3 (CharactersToReplace), use the Double data type.

  8. Item: ReplacementString.
    • VBA Construct: Arg4 parameter of the WorksheetFunction.Replace method.
    • Description: The Arg4 parameter of the WorksheetFunction.Replace method specifies the substring you want to use as replacement.

      If you explicitly declare a variable to represent Arg4 (ReplacementString), use the String data type.

Macro Example to Replace Character in String by Position

The following macro replaces the string starting in position 10 (myCharacterPosition) with a length of 1 character (myCharactersToReplace) with the string “+” (myReplacementString) within the string in cell A11 of the worksheet named “Excel VBA Replace” (myCell).

Sub replaceCharacterByPosition()

    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/

    'declare object variable to hold reference to cell you work with
    Dim myCell As Range

    'declare variables to hold parameters for string replacement (starting position of string to replace, number of characters to replace, and replacement string)
    Dim myCharacterPosition As Double
    Dim myCharactersToReplace As Double
    Dim myReplacementString As String

    'identify the cell you work with
    Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A11")

    'specify parameters for string replacement (starting position of string to replace, number of characters to replace, and replacement string)
    myCharacterPosition = 10
    myCharactersToReplace = 1
    myReplacementString = "+"

    'replace string in cell you work with, and assign resulting string to Range.Value property of cell you work with
    myCell.Value = WorksheetFunction.Replace(myCell.Value, myCharacterPosition, myCharactersToReplace, myReplacementString)

End Sub

Effects of Executing Macro Example to Replace Character in String by Position

The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string starting in position 10 with a length of 1 character with the string “+” within the string in cell A11.

Macro replaces character in string by position

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage in the Microsoft Developer Network:

  • Identify the workbook and worksheet you work with:
    • Workbook object.
    • Application.ThisWorkbook property.
    • Worksheet object.
    • Workbook.Worksheets property.
  • Identify the cell you work with:
    • Range object.
    • Worksheet.Range property.
    • Worksheet.Cells property.
    • Range.Item property.
    • Range.Offset property.
  • Obtain or set the string within the cell you work with:
    • Range.Value property.
  • Assign a new string to the cell you work with or to the variable representing the string you work with:
    • = operator.
  • Replace characters or strings:
    • Replace function.
    • Range.Replace method.
    • WorksheetFunction.Replace method.
  • Complete and concatenate truncated strings:
    • Left function.
    • & operator.
  • Create an array containing characters and loop through its elements:
    • For Each… Next statement.
    • Array function.
  • Work with variables and data types:
    • Dim statement.
    • Set statement.
    • Data types:
      • Double data type.
      • Long data type.
      • String data type.
      • Variant data type.

Понравилась статья? Поделить с друзьями:
  • Миф excel listbox to listbox
  • Миф excel для всех кнопок
  • Миф excel from outlook
  • Миф excel диалоговое окно да нет
  • Миф excel for с массивом