Замена ячеек в excel vba

Замена подстроки, содержащейся в текстовых значениях ячеек указанного диапазона, другой подстрокой с помощью метода Range.Replace из кода VBA Excel.

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

Метод имеет некоторые особенности, которые заключаются в следующем:

  • при присвоении булева значения, возвращаемого методом Range.Replace, переменной, необходимо список параметров (аргументов) метода заключать в круглые скобки;
  • если метод используется без присвоения возвращаемого значения переменной, параметры должны быть указаны без заключения их в круглые скобки.

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

Синтаксис

Синтаксис при замене подстроки и присвоении переменной возвращаемого значения типа Boolean:

variable = expression.Replace(What, Replacement, [LookAt], [SearchOrder], [MatchCase], [MatchByte], [SearchFormat], [ReplaceFormat])

Синтаксис при замене подстроки без присвоения переменной возвращаемого значения:

expression.Replace What, Replacement, [LookAt], [SearchOrder], [MatchCase], [MatchByte], [SearchFormat], [ReplaceFormat]

  • variable – переменная (тип данных — Boolean);
  • expression – выражение, возвращающее объект Range.

Параметры

Параметр Описание
What Искомая подстрока или шаблон*, по которому ищется подстрока в диапазоне ячеек. Обязательный параметр.
Replacement Подстрока, заменяющая искомую подстроку. Обязательный параметр.
LookAt Указывает правило поиска по полному или частичному вхождению искомой подстроки в текст ячейки:
1 (xlWhole) – поиск полного вхождения искомого текста;
2 (xlPart) – поиск частичного вхождения искомого текста.
Необязательный параметр.
SearchOrder Задает построчный или постолбцовый поиск:
1 (xlByRows) – построчный поиск;
2 (xlByColumns) – постолбцовый поиск.
Необязательный параметр.
MatchCase Поиск с учетом или без учета регистра:
0 (False) – поиск без учета регистра;
1 (True) – поиск с учетом регистра.
Необязательный параметр.
MatchByte Способы сравнения двухбайтовых символов:
0 (False) – двухбайтовые символы сопоставляются с однобайтовыми эквивалентами;
1 (True) – двухбайтовые символы сопоставляются только с двухбайтовым символами.
Необязательный параметр.
SearchFormat Формат поиска. Необязательный параметр.
ReplaceFormat Формат замены. Необязательный параметр.

* Смотрите знаки подстановки для шаблонов, которые можно использовать в параметре What.

Работа метода в VBA Excel

Исходная таблица для всех примеров:

Пример 1

Примеры записи строк кода с методом Range.Replace и поиском по частичному совпадению подстроки с содержимым ячейки:

Sub Primer1()

‘Запись 1:

Range(«A1:C6»).Replace «Лиса», «Рысь», 2

‘Запись 2:

Range(«A1:C6»).Replace What:=«Лиса», Replacement:=«Рысь», LookAt:=2

‘Запись 3:

If Range(«A1:C6»).Replace(«Лиса», «Рысь», 2) Then

End If

‘Запись 4:

Dim a

a = Range(«A1:C6»).Replace(«Лиса», «Рысь», 2)

End Sub

Результат выполнения любого из вариантов кода примера 1:

Пример 2

Поиск по шаблону с использованием знаков подстановки и по полному совпадению подстроки с содержимым ячейки:

Sub Primer2()

Range(«A1:C6»).Replace «Ли??», «Рысь», 1

End Sub

Обратите внимание, что слово «Лиса» заменено словом «Рысь» не во всех ячейках. Это произошло из-за того, что мы использовали параметр LookAt:=1 – поиск полного вхождения искомого текста в содержимое ячейки.

excelWhile  working with MS Excel , sometimes you may need to delete values in strings or change them. You can automate that by using the powerful Replace() which is available in Excel VBA (Visual Basic for Applications). Today, we walk you through the series of steps to understand and master the Replace() function. The prerequisites for this intermediate course are the basic knowledge of Excel (here’s a course that can give you an introduction to Excel 2o13), strings and preliminary understanding of Excel VBA. If not, we recommend that you go through this beginner’s course on Excel VBA and macros. For a quick refresher, you can do a quick read through of our VBA tutorial.

 Excel VBA Replace() is a simple yet very useful string function. As the name suggests, Replace() is used to replace a set of characters in a string with a new set of characters. The basic syntax of a VBA Replace function looks like this:

Replace(Source_string, Old_string, Replacement_string, [start, [count, [compare]]] )

Let’s go through each parameter to understand them better.

  • Source_string: This is the complete source string, of which you want some characters to be replaced.
  • Old_string: It’s the string which is to be replaced, ie the subset of source_string that you want to replace
  • Replacement_string: Is the string or a set of characters with which you want “Old_string” is to be replaced.
  • Start: Stands for the numerical position in the “Source_string” from which the search should start. This is an optional parameter. If this parameter is omitted, then by default the search begins at position 1.
  • Count: This parameter stands for the frequency of occurrences of Old_string to be replaced. Like “start”, it’s an optional parameter. If this argument is omitted, then each occurrence of “Old_string” in the “Source_string” will be replaced.
  • Compare: This is also an optional parameter. It represents the type of comparison algorithm to be used while the Replace Function searches for the occurrences of “Old_string” in the “Source_string.” Here are your options:
    1. vbBinaryCompare is the parameter value for binary comparison.
    2. vbTextCompare is the argument for textual comparison.
    3. Finally, the parameter value vbDatabaseCompare does a comparison based on information in your database.

Now that we’re familiar with the syntax of Replace function, lets move on to a few simple practical examples.

Examples

Replace (“Thank You", "You", "Everybody")

This example will return, “Thank Everybody”.

Replace ("Software Program", "Unique","code")

Guess what this will return? The code will return “Software Program.” The reason is we have asked the Replace function to replace “Unique.” However, you can see that “Unique” text string is not present inside the source string. So, Replace will leave the source string unchanged.

Replace ("Animal", "a", "f",2)

This code will return, “Animfl.” The reason is in the Replace function code, the search for character “a” starts from the second position. Wherever, “a” is found, it is replaced with “f”.

Replace ("Animal", "a", "f",1,1)

Here the Replace() will return “fnimal”.  The reason being we have instructed the VBA Replace statement to replace only one occurrence of “a” with “f”.

We suggest you work out these examples and learn a bit more about VBA macros (you can use this VBA course) before moving on to more complex programs using Replace function. Here on, we will use the Visual Basic Editor to write the code. We assume that you know how to save, compile and run programs on this editor. You can always look up our course on Excel VBA and Macros here.

How  to Remove Space from a String

Sub removeSpace()
Dim stringSpace As String
stringSpace = " this string contains spaces "
stringSpace = Replace(stringSpace, " ", "")
End Sub

Here we have declared stringSpace to be a variable of type string. It is initialized to a string which contains spaces. Replace() has the ‘stringSpace’ to the be source string. Every occurrence of space in the source string is removed using VBA Replace statement. Finally, stringSpace contains “thisstringcontainsspaces” which is the end result.

How to Replace a String within Inverted Comma

Sub replaceQuotedString()
Dim y, longString, resultString1 As String
y = Chr(34) & "abc" & Chr(34)
longString = "Let's replace this string: " &y
resultString1 = Replace(longString, y, "abc")
End Sub

Here we declare y, longString, resultString1 as variables of data type string. Chr() converts the numerical values to string data type. In other words, it introduces the quotation marks to the numerical values. And(&) operator concatenates strings. Value of “y” is “34abc34.” The  “longString” value is “Let’s replace this string: 34abc34″. In the Replace() value of source string is  the “longString.” That is “34abc34” is replaced by “abc”.  The resultstring1 now stores the value “Let’s replace this string: abc”

How to Remove Square Brackets from a String using Excel VBA

Sub removeSquareBrackets1()
Dim trialStr As String
trialStr = "[brackets have to be removed]"
trialStr = Replace(trialStr, "[", "")
trialStr = Replace(trialStr, "]", "")
MsgBox (trialStr)
End Sub

In this program, we’ve declared trialStr as a variable of type string.  It’s assigned the value”[brackets have to be removed].” The first occurrence of the replace function removes the left square bracket from trialStr. The variable now contains “brackets have to be removed].” In the second occurrence of the Replace function, the right square bracket is removed. Finally the value of trialStr is “brackets have to be removed.” Note that there are no square brackets in trialStr now. And the MsgBox() displays  the result.

How to Edit a Url Using Replace()

Enter this formula into any cell in your current Excel sheet.

=HYPERLINK("http://www.microsoft.com", "Microsoft Headquarters")

This creates a hyperlinked URL in the active cell of your worksheet. In the VBA editor, write the following code

Sub editURL1()
Dim URL1, NewURL
URL1 = ActiveCell.Formula
NewURL = Replace(URL1, "Microsoft Headquarters", "World Office")
ActiveCell.Formula = NewURL
End Sub

In this program, we’ve declared URL1 and NewURL as variables. URL1 is initialized to the value in the selected cell. Replace () searches for occurrence of “Microsoft Headquarters” in the URL and replaces it with “World Office.”  The selected cell is assigned the value of NewURL.

Programming using Excel VBA is interesting and gives you exposure to powerful functionality and features. Mastering it is important to efficiently and effectively use Excel.  Once you’ve tried these examples for yourself, do share your learning and experience with us. Once you’re ready to take the next step, hop over to this Ultimate VBA course, to check out some advanced VBA concepts.

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.

Содержание

  1. Range.Replace method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Example
  7. Support and feedback
  8. Метод Range.Replace (Excel)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Примечания
  13. Пример
  14. Поддержка и обратная связь
  15. VBA Excel. Метод Range.Replace (замена текста в ячейках)
  16. Определение метода Range.Replace
  17. Синтаксис и параметры метода
  18. Синтаксис
  19. Параметры
  20. VBA Excel. Изменение значений других ячеек из функции
  21. Функция с методом Range.Replace
  22. Метод Application.Volatile
  23. Безопасное использование функции

Range.Replace method (Excel)

Returns a Boolean indicating characters in cells within the specified range. Using this method doesn’t change either the selection or the active cell.

Syntax

expression.Replace (What, Replacement, LookAt, SearchOrder, MatchCase, MatchByte, SearchFormat, ReplaceFormat)

expression A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
What Required Variant The string that you want Microsoft Excel to search for.
Replacement Required Variant The replacement string.
LookAt Optional Variant Can be one of the following XlLookAt constants: xlWhole or xlPart.
SearchOrder Optional Variant Can be one of the following XlSearchOrder constants: xlByRows or xlByColumns.
MatchCase Optional Variant True to make the search case-sensitive.
MatchByte Optional Variant Use this argument only if you have selected or installed double-byte language support in Microsoft Excel. True to have double-byte characters match only double-byte characters. False to have double-byte characters match their single-byte equivalents.
SearchFormat Optional Variant The search format for the method.
ReplaceFormat Optional Variant The replace format for the method.

Return value

The settings for LookAt, SearchOrder, MatchCase, and MatchByte are saved each time you use this method. If you don’t specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, set these arguments explicitly each time that you use this method.

Example

This example replaces every occurrence of the trigonometric function SIN with the function COS. The replacement range is column A on Sheet1.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Range.Replace (Excel)

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

Синтаксис

expression. Replace (What, Replace, LookAt, SearchOrder, MatchCase, MatchByte, SearchFormat, ReplaceFormat)

выражение: переменная, представляющая объект Range.

Параметры

Имя Обязательный или необязательный Тип данных Описание
What Обязательный Variant Строка, которую требуется найти в Microsoft Excel.
Replacement Обязательный Variant Строка замены.
LookAt Необязательный Variant Может быть одной из следующих констант XlLookAt: xlWhole или xlPart.
SearchOrder Необязательный Variant Может быть одной из следующих констант XlSearchOrder: xlByRows или xlByColumns.
MatchCase Необязательный Variant Значение True, чтобы выполнять поиск с учетом регистра.
MatchByte Необязательный Variant Используйте этот аргумент, только если выбрана или установлена поддержка двухбайтового языка в Microsoft Excel. Значение True, чтобы двухбайтовые символы сопоставлялись только с двухбайтовым символами. Значение False, чтобы двухбайтовые символы сопоставлялись с однобайтовыми эквивалентами.
SearchFormat Необязательный Variant Формат поиска для метода .
ReplaceFormat Необязательный Variant Формат замены для метода .

Возвращаемое значение

Примечания

Параметры lookAt, SearchOrder, MatchCase и MatchByte сохраняются при каждом использовании этого метода. Если не указать значения этих аргументов при следующем вызове метода, будут использоваться сохраненные значения. Установка этих аргументов изменяет параметры в диалоговом окне Найти, а изменение параметров в диалоговом окне Найти приводит к изменению сохраненных значений, которые используются, если опустить аргументы. Чтобы избежать проблем, явно устанавливайте эти аргументы при каждом использовании этого метода.

Пример

В этом примере каждое вхождение тригонометрической функции SIN заменяется функцией COS. Диапазон замены — это столбец A на листе Sheet1.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Метод Range.Replace (замена текста в ячейках)

Замена подстроки, содержащейся в текстовых значениях ячеек указанного диапазона, другой подстрокой с помощью метода Range.Replace из кода VBA Excel.

Определение метода Range.Replace

Метод имеет некоторые особенности, которые заключаются в следующем:

  • при присвоении булева значения, возвращаемого методом Range.Replace, переменной, необходимо список параметров (аргументов) метода заключать в круглые скобки;
  • если метод используется без присвоения возвращаемого значения переменной, параметры должны быть указаны без заключения их в круглые скобки.

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

Синтаксис

Синтаксис при замене подстроки и присвоении переменной возвращаемого значения типа Boolean:

variable = expression.Replace(What, Replacement, [LookAt], [SearchOrder], [MatchCase], [MatchByte], [SearchFormat], [ReplaceFormat])

Синтаксис при замене подстроки без присвоения переменной возвращаемого значения:

expression.Replace What, Replacement, [LookAt], [SearchOrder], [MatchCase], [MatchByte], [SearchFormat], [ReplaceFormat]

  • variable – переменная (тип данных — Boolean);
  • expression – выражение, возвращающее объект Range.

Параметры

Параметр Описание
What Искомая подстрока или шаблон*, по которому ищется подстрока в диапазоне ячеек. Обязательный параметр.
Replacement Подстрока, заменяющая искомую подстроку. Обязательный параметр.
LookAt Указывает правило поиска по полному или частичному вхождению искомой подстроки в текст ячейки:
1 (xlWhole) – поиск полного вхождения искомого текста;
2 (xlPart) – поиск частичного вхождения искомого текста.
Необязательный параметр.
SearchOrder Задает построчный или постолбцовый поиск:
1 (xlByRows) – построчный поиск;
2 (xlByColumns) – постолбцовый поиск.
Необязательный параметр.
MatchCase Поиск с учетом или без учета регистра:
0 (False) – поиск без учета регистра;
1 (True) – поиск с учетом регистра.
Необязательный параметр.
MatchByte Способы сравнения двухбайтовых символов:
0 (False) – двухбайтовые символы сопоставляются с однобайтовыми эквивалентами;
1 (True) – двухбайтовые символы сопоставляются только с двухбайтовым символами.
Необязательный параметр.
SearchFormat Формат поиска. Необязательный параметр.
ReplaceFormat Формат замены. Необязательный параметр.

* Смотрите знаки подстановки для шаблонов, которые можно использовать в параметре What.

Источник

VBA Excel. Изменение значений других ячеек из функции

Изменение значений других ячеек из пользовательской функции VBA Excel с помощью методов Range.Replace и Application.Volatile. Примеры кода.

Функция с методом Range.Replace

Пользовательская функция не предназначена для изменения значений ячеек, кроме той, в которой она расположена. Попытка присвоить какое-либо значение из функции другой ячейке приводит к неработоспособности функции и отображению в ячейке, где она расположена, сообщения «#ЗНАЧ!».

Но, как ни странно, внутри процедуры Function работает метод Range.Replace, которым мы воспользуемся для изменения значений других ячеек из пользовательской функции.

Пример 1
Эта функция заменяет значение ячейки Cell1 на значение ячейки Cell2 увеличенное на 100. Сама функция размещается в третьей ячейке, чтобы не возникла циклическая ссылка.

В этом примере мы не присваиваем пользовательской функции значение, поэтому отображается значение по умолчанию – 0. Если объявить эту функцию как строковую: Function Primer1(Cell1 As Range, Cell2 As Range) as String , будет возвращена пустая строка.

Изменение значения ячейки C1 (Cell2) приведет к пересчету значения ячейки B1 (Cell1).

Попробуйте очистить или перезаписать ячейку B1 (Cell1), ничего не получится, так как функция Primer1 вновь перезапишет ее значением C1 (Cell2) + 100.

Метод Application.Volatile

Рассмотрим пересчет функции на следующем примере:

Пример 2

Эта функция будет пересчитываться только при изменении значений ячеек B1 и C1, присвоенных переменным Cell1 и Cell2. При изменении значения ячейки C2, значение ячейки B2 не изменится, так как не будет запущен пересчет функции Primer2.

Функция Primer2 начнет вести себя по-другому, если добавить в нее оператор Application.Volatile (переименуем ее в Primer3):

Пример 3

Теперь при смене значения в ячейке C2, значение ячейки B2 тоже изменится.

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

Безопасное использование функции

Если вам все-таки хочется в важном проекте VBA Excel с помощью одной пользовательской функции изменять значения нескольких ячеек, есть полностью безопасный вариант.

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

В простых случаях для выбора можно использовать функцию Choose или, в более сложных, оператор If…Then…Else и оператор Select Case.

Пример 4
Используем функцию Choose для выбора способа вычисления пользовательской функции в зависимости от значения дополнительного аргумента:

В функцию Primer4 добавлен дополнительный аргумент a, от которого зависит, какое действие будет произведено со значениями ячеек B1 и C1:

На следующем скриншоте представлены результаты вычисления функции в зависимости от значения аргумента a:

  1. В ячейке A1 вычисляется сумма значений ячеек B1 и C1 – аргумент a=1.
  2. В ячейке A2 вычисляется разность значений ячеек B2 и C2 – аргумент a=2.
  3. В ячейке A3 вычисляется произведение значений ячеек B3 и C3 – аргумент a=3.

Пример 5
Используем оператор If…Then…Else в сокращенном виде (If…Then…) для выбора способа вычисления функции в зависимости от значения дополнительного аргумента:

Источник

 

Wendflower

Пользователь

Сообщений: 21
Регистрация: 06.06.2018

Добрый день знатоки!
помогите, пожалуйста.

Нужно найти и заменить значения только в выделенном диапазоне (не по всему листу) по условию.
Например есть исходные данные плоского вида:

Товар Дата Примечание Количество
Капуста 18.07.2019 Спеццена 32
Морковь 18.07.2019 No 85
Яблоко 18.07.2019 Спеццена 16
Картошка 18.07.2019 No 94
Лук 18.07.2019 No 15
Капуста 19.07.2019 No 88
Морковь 19.07.2019 No 75
Яблоко 19.07.2019 No 46
Картошка 19.07.2019 No 0

Исходные данные, подтягиваются автоматом. Значение No-по умолчанию. За Предыдущие даты уже были (полуруками) проставлено примечание Спеццена и его трогать нельзя.
так же есть на соседнем листе список этих самых спец.цен с товарами, которое тянется из другого места.

Товар Примечание
Морковь Спеццена
Картошка Спеццена

нужно макросом обработать так, чтобы в выделенном мной диапазоне за 19 число Примечание No заменилось на Спеццена, если товар есть в списке на соседнем листе.

у меня получилось только тупо обрабатывать и заменять все имеющиеся данные в листе, а так нельзя.
заранее спасибо за ПОМОЩЬ!

 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#2

19.07.2019 13:59:15

Цитата
Wendflower написал:
у меня получилось только

если у Вас получилось на весь лист, то не понимаю, что останавливает сделать то же самое для отмеченного диапазона???
если получилось не у Вас, то так и пишите: нашел вот такой макрос помогите исправить его чтобы он работал для вот таких условий
и найдется кто-то, кто поможет
а пока сообщение читается так:
«я для листа сделал, но парится еще и с диапазоном — облом. сделайте кто-нибудь чтобы работало в отмеченном диапазоне, пожалуйста!»

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

casag

Пользователь

Сообщений: 175
Регистрация: 11.06.2018

#3

19.07.2019 14:38:49

Wendflower, можно так

Код
Sub csg()
Dim iCell As Range
Dim lr As Long, i As Long
Application.ScreenUpdating = False
With Selection
        If .Column <> 1 Then Exit Sub
        If .Columns.Count > 1 Then Exit Sub
End With
lr = Sheets(2).Cells(Rows.Count, "A").End(xlUp).Row
   For Each iCell In Selection
      For i = 2 To lr
         If iCell = Sheets(2).Cells(i, 1) Then
           iCell.Offset(0, 2) = Sheets(2).Cells(i, 2)
         End If
       Next
    Next
Application.ScreenUpdating = True
End Sub

Прикрепленные файлы

  • Пример для Planetaexcel.xlsm (21.64 КБ)

Изменено: casag20.07.2019 08:07:49

 

Wendflower

Пользователь

Сообщений: 21
Регистрация: 06.06.2018

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#5

19.07.2019 19:31:32

casag, For Each iCell In Selection — перебор всех ячеек выделенного диапазона. А это подразумевает намного больше вычислений в циклах:
к-во_столбцов_диапазона*к-во_значений_листа2

Немного изменил:

Код
Sub csg()
    Dim rRng As Range
    Dim lRw As Long, i As Long, k As Long
    
    With Selection
        If .Column <> 1 Then Exit Sub
        If .Columns.Count < 3 Then Exit Sub
    End With
    
    Set rRng = Selection
    lRw = Sheets(2).Cells(Rows.Count, "A").End(xlUp).Row
    Application.ScreenUpdating = False
 
    With Sheets(2)
        For k = 1 To rRng.Rows.Count
           For i = 2 To lRw
              If rRng(k, 1).Value = .Cells(i, 1).Value Then rRng(k, 3).Value = "Спеццена"
            Next i
         Next k
    End With
   
    Application.ScreenUpdating = True
    Set rRng = Nothing
End Sub

Если диапазон большой, лучше обработать в массиве.

 

casag

Пользователь

Сообщений: 175
Регистрация: 11.06.2018

#6

19.07.2019 21:24:39

vikttur, Спасибо за разъяснения, буду иметь в виду. Я только учусь, поэтому здоровая критика приветствуется. Всех благ.
Добавил в свой макрос ограничение.

Код
With Selection
        If .Column <> 1 Then Exit Sub
        If .Columns.Count > 1 Then Exit Sub
End With

Изменено: casag20.07.2019 08:06:14

Найти и заменить в открытых книгах или нескольких листах:

Kutools for ExcelАвтора Найти и заменить функция может помочь вам найти и заменить значения из открытых книг или конкретных рабочих листов, которые вам нужны.

док-множественный найти и заменить-6

arrow синий правый пузырь Найти И Заменить Сразу Несколько Значений Кодом VBA


Если вы устали от поиска и замены значений снова и снова, следующий код VBA может помочь вам сразу заменить несколько значений вашими необходимыми текстами.

2, Затем нажмите и удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений.

3. Щелчок Вставить > модуль, и вставьте следующий код в окно модуля.

Код VBA: поиск и замена сразу нескольких значений

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Sub MultiFindNReplace()

Dim Rng As Range

Dim InputRng As Range, ReplaceRng As Range

xTitleId = "KutoolsforExcel"

Set InputRng = Application.Selection

Set InputRng = Application.InputBox("Original Range ", xTitleId, InputRng.Address, Type:=8)

Set ReplaceRng = Application.InputBox("Replace Range :", xTitleId, Type:=8)

Application.ScreenUpdating = False

For Each Rng In ReplaceRng.Columns(1).Cells

    InputRng.Replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value

Next

Application.ScreenUpdating = True

End Sub

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

5. Щелчок OK, и появится другое окно подсказки, чтобы напомнить вам, выберите критерии, которые вы создали на шаге 1. Смотрите скриншот:

6, Затем нажмите OK, все конкретные значения были заменены новыми значениями по мере необходимости.

doc multiple find заменить 5


Статья: https://www.extendoffice.com/ru/documents/excel/1873-excel-find-and-replace-multiple-values-at-once.html

Понравилась статья? Поделить с друзьями:
  • Замена электронных таблиц excel
  • Замена шрифта в документе word
  • Замена шрифта microsoft word
  • Замена числа с точкой на число с запятой в excel
  • Замена шаблона стиля в word