Замена части строкового выражения в 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 |
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
Replace
Функция Replace
Возвращаемое значение В результате действия функции Replace возвращается исходная строка с замененным строковым фрагментом Параметры
Пример Sub Function_String_Replace() Dim STRsample$, STRfind$, STRnew$, STRresult$ STRsample = "Мир MS Excel" 'строка, часть которой будем менять STRfind = "MS " 'подстрока для замены STRnew = "" ' новая подстрока для замены STRresult = Replace(STRsample, STRfind, STRnew, 1, 1) ' меняем один раз, начиная с первого символа MsgBox STRsample 'просмотр исходного текста MsgBox STRresult ' просмотр результата замены End Sub Исходный текст: Результат замены: Категория |
||||||||||||
Счетчики: 73568 | Добавил: Serge_007 | Теги: Replace, функция, Excel, vba, заменить, ВБА, function |
Всего комментариев: 8 | |
Порядок вывода комментариев: 1 А можно ли с помощью этой функции в шаблоне задать замену допустим двух пробелов на один в открываемом документе 0
Replace («1011112», «1», «2», 5, 1) выдаёт 212, а надо 1011212 Это что — глюк или фича? И как в таких случаях быть? На сайте Микрософт к функции Replace висит заметка Значение, возвращаемое функцией Replace является строкой, которая начинается с позиции, указанной параметром Start, и завершается в конце строки Expression, с заменой подстрок Find значениями Replace. Т.е. Если хочешь получить нормальную замену, надо к результату добавить начало исходной строки до позиции Start.
Т.е. логика такая — у меня есть несколько шаблонов строк. Я беру входную строку, с помощью RegExp определяю, к какому шаблону относится данная строка, и далее меняю ее в зависимости опять же от шаблона. Т.е. в каком то случае это будет добавление к строке «.», в каком то случае пробела и тд. Пример функции в экселе: ЕСЛИМН(RegExp1(A1;C1;D1) != 0; RegExp(A1;C1;D1); RegExp1(A1;C2;D2) != 0; RegExp1(A1;C2;D2); … ), где С* — это столбец с паттернами (вида (d{1})(d{1})(..*!) ), а D* — столбец с заменяемыми значениями вида $1.$2 $3. Т.е. идея такая, что делим исходную строку на группы, и далее в зависимости от вида шаблона добавляем между группами в нужные места символы (точки и тд). В таком случае вопрос, как показать в функции RegExp, что после чтения строки-паттерна в объект (regex.Pattern = Pattern), надо связать переданную в функцию строку-шаблон ( $1.$2 $3) с входным текстом? Потому что есть подозрение, что входную строку-шаблон он воспримет просто как строку, и выполнит замену 1 в 1 ( $1.$2 $3), а надо чтобы он понял, что вот эти знаки $ относятся именно к входной строке. Для примера код функции с основными частями: Public Function RegExpExtract_myversion(Text As String, Pattern As String, myRep As String) As String Заранее извиняюсь за такой развернутый вопрос, если можно хотелось бы получить хотя бы направление, куда двигаться, потому что везде идет замена строки на готовую заранее строку, а вот чтобы брать входную, менять, и заменять на нее, такого увы не встречал. Спасибо! |
|
Добавлять комментарии могут только зарегистрированные пользователи.
[
Регистрация
|
Вход
]
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Replace function (Visual Basic for Applications) |
vblr6.chm1008930 |
vblr6.chm1008930 |
office |
a24e3da4-fc94-56e7-d718-f4c2d0a31072 |
12/13/2018 |
medium |
Returns a string, which is a substring of a string expression beginning at the start position (defaults to 1), in which a specified substring has been replaced with another substring a specified number of times.
Syntax
Replace(expression, find, replace, [ start, [ count, [ compare ]]])
The Replace function syntax has these named arguments:
Part | Description |
---|---|
expression | Required. String expression containing substring to replace. |
find | Required. Substring being searched for. |
replace | Required. Replacement substring. |
start | Optional. Start position for the substring of expression to be searched and returned. If omitted, 1 is assumed. |
count | Optional. Number of substring substitutions to perform. If omitted, the default value is -1, which means, make all possible substitutions. |
compare | Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. |
Settings
The compare argument can have the following values:
Constant | Value | Description |
---|---|---|
vbUseCompareOption | -1 | Performs a comparison by using the setting of the Option Compare statement. |
vbBinaryCompare | 0 | Performs a binary comparison. |
vbTextCompare | 1 | Performs a textual comparison. |
vbDatabaseCompare | 2 | Microsoft Access only. Performs a comparison based on information in your database. |
Return values
Replace returns the following values:
If | Replace returns |
---|---|
expression is zero-length | Zero-length string («») |
expression is Null | An error. |
find is zero-length | Copy of expression. |
replace is zero-length | Copy of expression with all occurrences of find removed. |
start > Len(expression) | Zero-length string. String replacement begins at the position indicated by start. |
count is 0 | Copy of expression. |
Remarks
The return value of the Replace function is a string, with substitutions made, that begins at the position specified by start and concludes at the end of the expression string. It’s not a copy of the original string from start to finish.
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
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