Замена части строкового выражения в 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 |
Find & Replace Function in VBA
If your Excel job involves routine tasks finding and replacing something with something, then you need this article at any cost. Because after reading this article, you would probably save 80% of your time by learning this VBA coding technique. Find and Replace in ExcelFind and Replace is an Excel feature that allows you to search for any text, numerical symbol, or special character not just in the current sheet but in the entire workbook. Ctrl+F is the shortcut for find, and Ctrl+H is the shortcut for find and replace.read more is an often used tool. We can implement the same with VBA as well. Our earlier article, “VBA Find,” shows you how to use the FIND method in VBA. This article will show you how to use the VBA “Find & Replace” method.
Table of contents
- Find & Replace Function in VBA
- VBA Find and Replace Syntax
- Examples of VBA Find and Replace in Excel
- Example #1 – VBA Find and Replace the Word
- Example #2 – Case Sensitive Replacement
- Recommended Articles
Follow the article to learn this technique.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Find and Replace (wallstreetmojo.com)
VBA Find and Replace Syntax
We must follow the steps below to use the Find and Replace method in VBA. First, we have selected the range of cells, so mention the range of cells using RANGE object in VBARange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.
Now put a dot (.) to see the IntelliSense list.
Select the Replace method from the list.
We can see the huge parameter list of the Replace method. Now, we will see each parameter explanation below.
- What: This is nothing but what we need to find to replace the value.
- Replacement: With the found value, what should be the new value to be replaced with?
- Look At: This is to mention whether we want to look at the full content or just the part of the content. We can supply two parameters here “xlWhole” & “xlPart.”
- Search Order: This mentions the search order, either rows or columns. We can supply two parameters here “xlByRows” & “xlByColumns.”
- Match Case: The content we are searching for is case-sensitive. Suppose the case-sensitive argument is TRUE or else FALSE.
- Search Format: We can also search the content by formatting the value we are looking for.
- Replace Format: We can replace one format with another format as well.
Examples of VBA Find and Replace in Excel
Below are some examples of the Excel VBA Find and Replace method.
You can download this VBA Find and Replace Excel Template here – VBA Find and Replace Excel Template
Example #1 – VBA Find and Replace the Word
Let us look at the following example to understand the VBA Find and Replace method. First, take a look at the following data.
Step 1: First, mention the Range of cells we are replacing. In this example, the range is from A1 to B15 so the code will be Range (“A1: B15”).
Code:
Sub Replace_Example1() Range ("A1:B15") End Sub
Step 2: Now, put a dot to see the IntelliSense list.
Step 3: Select the Replace method from the IntelliSense list.
Step 4: Mention what parameter as “September.”
Code:
Range("A1:B15").Replace What:="September"
Step 5: Next, Replace with parameter should be the new value we are replacing with, i.e., “December.”
Code:
Range("A1:D4").Replace What:="September", Replacement:="December"
As of now, ignore all the other parameters. Now, run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more to see the replacement method with VBA.
So, it has replaced all of September with the word “December.”
Example #2 – Case Sensitive Replacement
The more advanced example of the VBA Find & Replace method will be using case sensitive replacement methods. We have created this sample data for this example, as shown in the image below.
We have two cell data in capital letters, “HELLO.” Wherever we have a capital “HELLO,” it should be replaced by the new word “Hiii.”
As usual, write the code, and mention what to find and replace first.
Code:
Sub Replace_Example2() Range("A1:D4").Replace What:="HELLO", Replacement:="Hiii" End Sub
For the next argument, “Match Case,” write the condition as TRUE.
Code:
Range("A1:D4").Replace What:="HELLO", Replacement:="Hiii", MatchCase:=True
Now, run the code. It will replace only the capital “HELLO” with “Hiii.”
Imagine you have not applied the Match Case argument in VBAIn VBA, the match function is used as a lookup function and is accessed by the application. worksheet method. The arguments for the Match function are similar to the worksheet function.read more, then it will replace all the “Hello” with “Hiii.”
Note: I have removed the Match Case argument here. By default, the MATCH CASE argument value is FALSE.
As we can see in the above image, it has replaced all the “hello” words with “hiii.”
So, whenever we want to use MATCH CASE criteria, we should apply the argument as “TRUE.” By default, this argument value is “FALSE.” Like this, we can use the “FIND & REPLACE” method to find something and replace the found value with something else.
Recommended Articles
This article has been a guide to the VBA Find and Replace Method. Here we will learn how to find and replace the word in VBA Excel with examples and downloadable Excel sheets. You may also have a look at other articles related to Excel VBA: –
- VBA Charts
- What does StrConv do in Excel VBA?
- End Property in VBA
- ROUND Function in VBA
In this Article
- Replace Function
- Starting Position
- Replace a Few Occurrences Only
- Case Sensitivity
- Double Quotes
- Replace Break Line in Cell
This tutorial will demonstrate how to use the VBA Replace Function to replace strings of text.
Replace Function
The VBA Replace function replaces a substring of text with another substring.
Sub ReplaceExample_1()
MsgBox Replace("ABCABCABC", "A", "!")
'Result is: "!BC!BC!BC"
MsgBox Replace("I like pink, red and black", "pink", "purple")
'Result is: "I like purple, red and black"
MsgBox Replace("A, B, C, A, B, C, A, B, C", ", ", ",")
'Result is: "ABCABCABC"
MsgBox Replace("ABCABCABC", "ABC", "!")
'Result is: "!!!"
MsgBox Replace("ABCABCABC", "ABc", "!")
'Result is: "ABCABCABC"
MsgBox Replace("ABCABCABC", "ZBC", "!")
'Result is: "ABCABCABC"
End Sub
Starting Position
By assigning a start position, you can indicate what character position to start with (default = 1).
Sub ReplaceExample_2()
MsgBox Replace("ABCABCABC", "A", "123") 'Result is: "123BC123BC123BC"
MsgBox Replace("ABCABCABC", "A", "123", 2) 'Result is: "BC123BC123BC"
MsgBox Replace("ABCABCABC", "A", "123", 7) 'Result is: "123BC"
MsgBox Replace("ABCABCABC", "A", "123", 8) 'Result is: "BC"
MsgBox Replace("ABCABCABC", "ABC", "!@") 'Result is: "!@!@!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 2) 'Result is: "BC!@!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 6) 'Result is: "C!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 7) 'Result is: "!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 8) 'Result is: "BC"
End Sub
Replace a Few Occurrences Only
You can also indicate how many instances of the substring to replace (default All)
Sub ReplaceExample_3()
MsgBox Replace("ABCABCABC", "A", "12") 'Result is: "12BC12BC12BC"
MsgBox Replace("ABCABCABC", "A", "12", , 1) 'Result is: "12BCABCABC"
MsgBox Replace("ABCABCABC", "A", "12", , 2) 'Result is: "12BC12BCABC"
MsgBox Replace("ABCABCABC", "A", "12", , 3) 'Result is: "12BC12BC12BC"
MsgBox Replace("ABCABCABC", "A", "12", , 5) 'Result is: "12BC12BC12BC"
MsgBox Replace("ABCABCABC", "A", "12", 3, 1)
'Result is: "C12BCABC"
'We replaced A with 12, 1 time starting from position 3 of the original string.
End Sub
Case Sensitivity
The Replace Function is case sensitive by default. You can switch to case insensitive by adding the optional parameter (vbTextCompare). Here, you must also define the starting position of the search.
Sub ReplaceExample_4()
MsgBox Replace("ABcABCABc", "ABc", "12")
'Result is: "12ABC12"
MsgBox Replace("ABcABCABc", "ABc", "12", , , vbTextCompare)
'Result is: "121212"
'When we use vbTextCompare we need to add the 2 other optional arguments:
'start and count
MsgBox Replace("ABcABCABcABc", "ABc", "12", 3, 1)
'Result is: "cABC12ABc"
'Started from position3 and replaced ABC only 1 time.
End Sub
You can also perform a case-insensitive Replace, by adding Option Compare Text to the top of your module:
Option Compare Text
Double Quotes
The Replace Function can replace the double quotes character used to delimit the start and end of a string.
VBA Chr function can return a character from its number in the character set.
MsgBox Chr(34) 'Result is: "
Or
MsgBox Chr(64) 'Result is: @
Double quotes can be used inside the Replace Function using “””” or VBA Function Chr(34).
Sub ReplaceExample_5()
Dim StrEx As String
StrEx = "AB""AB"""
MsgBox StrEx 'Result is: AB"AB"
MsgBox Replace(StrEx, Chr(34), "12")
'Result is: AB12AB12
MsgBox Replace(StrEx, """", "DQ")
'Result is: "ABDQABDQ"
End Sub
Replace Break Line in Cell
The Replace Function can find the break line special character in a cell and remove it or replace it with a space character. The break line special character can be entered in a cell using the keyboard shortcut Alt+Enter and can be used in VBA code with its Character set number using VBA function Chr(10).
Sub ReplaceExample_6()
Dim StrEx As String 'Define a string variable
'Read the value of cell A2 in worksheet Sheet1
StrEx = ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
'The break line character entered with Alt+Enter is Chr(10) and is invisible.
'This code line replaces that character with space
StrEx = Replace(StrEx, Chr(10), " ")
'Write the replaced value in cell B2 in worksheet Sheet1
ThisWorkbook.Worksheets("Sheet1").Range("B2").Value = StrEx
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.
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.
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.
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.
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.
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.
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
Excel VBA Replace String
Excel VBA Replace looks for a substring within a list and replaces the substring with a second substring. When we use Excel VBA Replace Strings in Data there are some situations when we need to replace some character or a string from a sentence. If we have a large set of data that we want to replace it can be a tedious task to do it manually but with this function, it is very easy to provide the arguments and replace the string.
Syntax:
The syntax for Replace String function:
Replace ( Expression as String, Old String, New String, Start, Count, Compare)
Now the expression is the main string from where we want to remove the old string and new string which will replace the old string. The other arguments are optional. If we compare this function to excel worksheet substitute function we will find that Replace in VBA is the replacement of the substitute function in excel.
How to Replace Text in String Using VBA?
We will learn how to Replace Text in String using the VBA Code in Excel.
You can download this VBA Replace String Excel Template here – VBA Replace String Excel Template
Example #1
Let us start with a basic example of using the replace function where we will replace a simple word name from the sentence “My name is Anand”. Here we will replace Anand to Aran. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Insert a new subprocedure for example 1.
Code:
Sub Example1() End Sub
Step 3: Declare a variable as a string.
Code:
Sub Example1() Dim Str As String End Sub
Step 4: Now let us use replace function while providing a string as the expression to the variable.
Code:
Sub Example1() Dim Str As String Str = Replace("My name is Anand", "Anand", "Aran") End Sub
Step 5: Let us use the Msgbox function to display the value we have in this variable.
Code:
Sub Example1() Dim Str As String Str = Replace("My name is Anand", "Anand", "Aran") MsgBox Str End Sub
Step 6: When we execute the code.
Example #2
Let us begin with the second example where we can use the arguments used in the replace function as the variables. We will use a different statement for this example. For this, follow the below steps:
Step 1: In the same module let us start another subprocedure.
Code:
Sub Example2() End Sub
Step 2: Now let us declare three different variables as a string.
Code:
Sub Example2() Dim Str, Str1, Str2 As String End Sub
Step 3: In the first variable we can provide any string statement.
Code:
Sub Example2() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" End Sub
Step 4: Now in the second variable we can use the Input Box function to get input from the user.
Code:
Sub Example2() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") End Sub
Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string.
Code:
Sub Example2() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1) End Sub
Step 6: We will use the Msgbox function to display the result in the third string.
Code:
Sub Example2() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1) MsgBox Str2 End Sub
Step 7: When we execute the code above and give input as “girl”.
Example #3
Now we will discuss one of the optional arguments in the function which is the start option where we can define from which position we want. For this, follow the below steps:
Step 1: In the same module let us start another subprocedure.
Code:
Sub Example3() End Sub
Step 2: Now let us declare three different variables as a string.
Code:
Sub Example3() Dim Str, Str1, Str2 As String End Sub
Step 3: In the first variable we can provide any string statement.
Code:
Sub Example3() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" End Sub
Step 4: Now in the second variable we can use the Input Box function to get input from the user.
Code:
Sub Example3() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") End Sub
Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string and give start position as 7.
Code:
Sub Example3() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1, Start:=7) End Sub
Step 6: We can use the Msgbox function to show the result and when we execute the code which will ask us for a string.
Code:
Sub Example3() Dim Str, Str1, Str2 As String Str = " I am a Good Boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1, Start:=7) MsgBox Str2 End Sub
Step 7: When we press Ok we will see the final result.
Example #4
Now there is another optional argument which is the number of times we want to replace a string. For this, follow the below steps:
Step 1: In the same module let us start another subprocedure.
Code:
Sub Example4() End Sub
Step 2: Now let us declare three different variables as a string.
Code:
Sub Example4() Dim Str, Str1, Str2 As String End Sub
Step 3: In the first variable we can provide any string statement.
Code:
Sub Example4() Dim Str, Str1, Str2 As String Str = " I am a Good Boy, but you are a bad boy" End Sub
Step 4: Now in the second variable we can use the Input Box function to get an Input from the user.
Code:
Sub Example4() Dim Str, Str1, Str2 As String Str = " I am a Good Boy, but you are a bad boy" Str1 = InputBox("Enter a String") End Sub
Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string as shown in the below screenshot and use the number of instances we want to replace the string as follows and then use msgbox function to display the result.
Code:
Sub Example4() Dim Str, Str1, Str2 As String Str = " I am a Good Boy, but you are a bad boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1, Count:=1) End Sub
Step 6: Use the number of instances we want to replace the string as follows and then use the Msgbox function to display the result.
Code:
Sub Example4() Dim Str, Str1, Str2 As String Str = " I am a Good Boy, but you are a bad boy" Str1 = InputBox("Enter a String") Str2 = Replace(Str, "Boy", Str1, Count:=1) MsgBox Str2 End Sub
Step 7: Once we execute the code and provide a second string as “girl” we will see the following result.
Explanation of VBA Replace String:
We have seen from the above examples that the Replace function is the replacement of the substitute function of excel. It has three mandatory arguments and other arguments are optional. We can use the optional arguments together or one at a time. Start refers to the position of the string whereas count refers to the number of times we want to replace the old string with the new string.
How to Use VBA Replace String?
The method to use this function is very simple and similar to excel worksheet function. This function needs three mandatory arguments:
- First is the expression or the main string.
- Then we have to provide a target string which needs to replaced.
- And the final argument is the string which is the new string that needs to be replaced.
Things to Remember
There are few things which we need to remember about Replace string in VBA such as follows:
- There are three arguments in the Replace function of excel and there are two optional arguments.
- The two optional arguments are either for the number of times we want to replace or the position where we want to replace.
- This function is similar to a substitute function in excel.
Recommended Articles
This is a guide to the VBA Replace String. Here we discuss How to Replace Text in String in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA RGB
- VBA CDEC
- VBA XML
- VBA IsError