Text replace from excel

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 Excel Starter 2010 More…Less

This article describes the formula syntax and usage of the REPLACE and REPLACEB
 function in Microsoft Excel.

Description

REPLACE replaces part of a text string, based on the number of characters you specify, with a different text string.

REPLACEB replaces part of a text string, based on the number of bytes you specify, with a different text string.

Important: 

  • These functions may not be available in all languages.

  • REPLACE is intended for use with languages that use the single-byte character set (SBCS), whereas REPLACEB is intended for use with languages that use the double-byte character set (DBCS). The default language setting on your computer affects the return value in the following way:

  • REPLACE always counts each character, whether single-byte or double-byte, as 1, no matter what the default language setting is.

  • REPLACEB counts each double-byte character as 2 when you have enabled the editing of a language that supports DBCS and then set it as the default language. Otherwise, REPLACEB counts each character as 1.

The languages that support DBCS include Japanese, Chinese (Simplified), Chinese (Traditional), and Korean.

Syntax

REPLACE(old_text, start_num, num_chars, new_text)

REPLACEB(old_text, start_num, num_bytes, new_text)

The REPLACE and REPLACEB function syntax has the following arguments:

  • Old_text    Required. Text in which you want to replace some characters.

  • Start_num    Required. The position of the character in old_text that you want to replace with new_text.

  • Num_chars    Required. The number of characters in old_text that you want REPLACE to replace with new_text.

  • Num_bytes    Required. The number of bytes in old_text that you want REPLACEB to replace with new_text.

  • New_text    Required. The text that will replace characters in old_text.

Example

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter. If you need to, you can adjust the column widths to see all the data.

Data

abcdefghijk

2009

123456

Formula

Description (Result)

Result

=REPLACE(A2,6,5,»*»)

Replaces five characters in abcdefghijk with a single * character, starting with the sixth character (f).

abcde*k

=REPLACE(A3,3,2,»10″)

Replaces the last two digits (09) of 2009 with 10.

2010

=REPLACE(A4,1,3,»@»)

Replaces the first three characters of 123456 with a single @ character.

@456

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Skip to content

How to Replace Text in Excel with the REPLACE function (2023)

How to Replace Text in Excel with the REPLACE function (2023)

Need to replace text in multiple cells?

Excel’s REPLACE and SUBSTITUTE functions make the process much easier.

Let’s take a look at how the two functions work, how they differ, and how you put them to use in a real spreadsheet🔍

If you want to follow along with what I show you, download my workbook here.

Replacing characters in text with the REPLACE function

The REPLACE function substitutes a text string with another text string.

Let’s say your boss tells you that the product IDs for a product line must be changed.

But only a part of the product ID should be changed – not all of it.

Here, the “29FA” part of all the product IDs needs to be changed to “39LU”.

To do that with the REPLACE function, we’ll walk through the syntax of the REPLACE function, which goes like this:

=REPLACE(old_text, start_num, num_chars, new_text)

Don’t worry, it’s not as daunting as it looks. It’s actually pretty straightforward👍

Step 1: Old text

The old text argument is a reference to the cell where you want to replace some text. Write:

=REPLACE(A2

Excel replace function - reference to old text argument of syntax

And put a comma to wrap up the first argument, and let’s move on to the next.

Step 2: Start num

The start_num argument determines where the REPLACE function should start replacing characters from.

In our case, the “29FA” part starts on the 3rd character in the text.

Excel replace function to replace text from a specified position

So, write:

=REPLACE(A2, 3,

Now, we’ve established where the REPLACE function should start to replace text.

Still with me? Then let’s dive into the next argument of the REPLACE syntax🤿

Step 3: Num chars

Also called the “number of characters” argument, this determines how many characters should be replaced with the new text.

Typically, this should be the length of the text you want to replace the old text with.

So, it ties together with the next argument.

If you want to replace “29FA” with “39LU”, then you’re replacing the next 4 characters.

Write:

=REPLACE(A2, 3, 4

Excel replace function - number of characters to replace

And wrap it up with a comma🎁

There are situations where this num_chars argument should be a different length than the new_text argument. I’ll tell you more about that later.

Kasper Langmann, Microsoft Office Specialist

Step 4: New text

The new_text argument is the replacement text for the old text.

So, simply write the new characters that should replace the old 4 characters:

=REPLACE(A2, 3, 4, “39LU”

Excel replace function - new text argument

Remember the double quotes when the replacement text is letters or a combination of numbers and letters.

Wrap up the formula with an end parenthesis and press Enter.

Now, the “29FA” part of the old product ID is replaced with “39LU”.

Excel replace function - visual example

PRO TIP: Length of num_chars vs new_text

If you need the replacement text to be shorter or longer than the text it’s replacing, you can have a different length in the 3rd and 4th argument of REPLACE. Let me give you a few formula examples of that:

If you wanted to replace the “29FA” with “39L” instead, you’d write:

=REPLACE(A2, 3, 4, “39L”)

But the length of the 4th argument would be shorter than the 4 characters defined in the 3rd argument.

On the other hand, if you wanted to replace “FA” with “LLUU”, you’d write this:

=REPLACE(A2, 5, 2, “LLUU”)

Formula example Different length in number of characters and new text

Replacing text strings with the SUBSTITUTE function

If the string you want to replace doesn’t always appear in the same place, you’re better off using the SUBSTITUTE function.

The syntax of SUBSTITUTE goes like this:

=SUBSTITUTE(text, old_text, new_text, [instance_num])

This is a little different from the last syntax of the REPLACE function, so be careful not to get them mixed up⚠️

Step 1: Text

The text argument is just a cell reference to the cell where you want to replace text.

Write:

=SUBSTITUTE(A2

Excel substitute function to replace text - text argument

And of course, put a comma to go to the next argument.

Step 2: Old text

The SUBSTITUTE function doesn’t replace characters from a fixed position in a cell.

Instead, it cleverly searches for a text string and begins replacing characters from there🔍

So, if you want to replace the “FA” part of the product ID with “LU”, write:

=SUBSTITUTE(A2, “FU”

Excel substitute function - old text argument

Step 3: New text

The new_text argument is what the old text should be replaced with.

For this example, that’s “LU”.

=SUBSTITUTE(A2, “FA”, “LU”

Excel replace text - old text and new text

The new text doesn’t have to be the same length as the old text.

Kasper Langmann, Microsoft Office Specialist

Step 4: Instance num

The optional instance num argument decides how many times the text should be replaced.

This is relevant if there is more than one instance of the old text.

The instance_num argument is optional. If you leave it blank, every instance of the old text is replaced by the new text😊

In the following formula example, the first 2 product IDs each have 2 instances of the “FA”. So, the instance num argument determines whether only the first instance of “FA” is replaced with “LU” or both instances of “FA” is replaced with “LU”.

As you can see from the picture below, write 1 if you want only the first instance of “FA” to be replaced.

=SUBSTITUTE(A2, “FA”, “LU”, 1)

Or don’t use the instance num argument if every instance of “FA” should be replaced:

=SUBSTITUTE(A2, “FA”, “LU”)

Excel substitute formula examples with instance number argument for multiple replacements

And that’s how to replace text dynamically based on the location of the text you want to replace.

The difference between REPLACE and SUBSTITUTE

There are a few subtle differences between these two “replace functions”.

Both of them replace one or more characters in a text string with another text string.

The difference lies in how the first string is identified.

REPLACE selects the first string based on the position. So you might replace four characters, starting with the sixth character in the string.

SUBSTITUTE selects based on whether the string matches a predefined search. You might tell Excel to replace any instance of “FA” with “LU” for example.

Other than that, the two functions are identical👬🏻

Replace text using Find and Replace

Another way to replace text is with the ‘Find and Replace’ feature of Excel.

It’s a way to substitute characters in the original cell instead of having to add additional columns with formulas.

1. Select all the cells that contain the text to replace.

2. From the ‘Home’ tab, click ‘ Find and Select’.

Find and Select Excel feature

3. From the Find and Replace dialog box (in the replace tab) write the text you want to replace, in the ‘Find what:’ field.

4. Still within the ‘Find and Replace’ dialog box, write the new text to replace the old text with in the ‘Replace with:’ field.

Replace text by using the find what and replace with fields from Find and Replace dialog box

5. When you click the ‘Replace all’ button, Excel replaces all instances of the old text with the new text, in the selected cells.

If you instead want to replace all instances of the text within the entire workbook, just select a single cell before opening the ‘Find and Replace’ dialog box.

(Instead of selecting multiple cells).

Kasper Langmann, Microsoft Office Specialist

That’s it – Now what?

With the REPLACE and SUBSTITUTE functions, you can replace very specific strings with other strings. You can use letters, numbers, or other characters.

In short, you can replace text with extreme accuracy. And that saves you a great deal of time when you need to make a lot of edits.

Additionally, you can use the Find and Replace tool, which is the most underrated feature of Excel.

But no one got a job offer just based on their skills to replace characters in a text in Microsoft Excel.

Luckily, there are other areas of Excel that are magnets for job offers🧲

Click here to learn IF, SUMIF, VLOOKUP, and pivot tables (yup, that’s the magnets) for FREE in my 30-minute online Excel course.

Other resources

Replacing text is often used to clean up data so it’s ready for analysis, formulas, pivot tables, etc.

Other ways of cleaning up data are with other important Excel functions like LEFT, RIGHT, MID, and LEN.

Or with one of the two ways of deleting blank rows (one better than the other). Read all about it here.

Kasper Langmann2023-01-19T12:24:59+00:00

Page load link

REPLACE function is included in the text functions of MS Excel and is intended to replace a specific area of the text string containing the source text on the specified text line (new text).



How does the REPLACE function in Excel work?

Example 1. In order to study in detail the operation of this function, we consider one of the simplest examples. Suppose we have several words in different columns, we need to get new words using the original ones. For this example, in addition to our main function REPLACE, we also use the RIGHT function — this function serves to return a certain number of characters from the end of a line of text. That is, for example, we have two words: milk and a skating rink, as a result we must get the word hammer.

REPLACE function in Excel and examples of its use

  1. Create a table with words on the sheet of the Excel spreadsheet workbook, as shown in the figure:
  2. Example 1.

  3. Next, on the sheet of the workbook, we will prepare an area for placing our result — the resulting word “hammer”, as shown below. Place the cursor in cell A6 and call the function REPLACE:
  4. FORMULAS.

  5. Fill the function with the arguments shown in the figure:
  6. REPLACE.

Let us explain the choice of these parameters as follows: cell A2 was chosen as the beginning of the text, the number 5 was set as beginning_, since it is from the fifth position of the word “Milk” we don’t take characters for our final word, the number_ of signs was set equal to 2, since this number It is not taken into account in the new word, as the new text, the set option RIGHT with the parameters of the cell A3 and taking the last two characters «ok».

Next, click on the «OK» button and get the result:

examples of its use.

How to REPLACE a piece of text in Excel cell?

Example 2. Consider another small example. Suppose we have columns of words in the cells of the Excel spreadsheet. It is necessary to replace their letters in certain places so as to convert them.

  1. Let’s create a tablet with words on the sheet of an Excel workbook, as shown in the figure:
  2. Example 2.

  3. Further, on the same sheet of the working book we will prepare an area for placing our result — modified words. Fill the cells with two types of formulas as shown in the picture:
  4. piece of text in cell.

Download examples text function REPLACE in Excel

Note! In the second formula, we use the operator “&” to add the character «s» to the male surname to convert it to the female. To solve this problem, one could use the function =CONCATENATE(B3,»s») instead of the formula =B3&»s» — the result is identical. But today it is strongly recommended to abandon this formula as it has its limitations and is more demanding on resources in comparison with a simple and convenient ampersand operator.

Purpose 

Replace text based on content

Usage notes 

The Excel SUBSTITUTE function can replace text by matching. Use the SUBSTITUTE function when you want to replace text based on matching, not position. Optionally, you can specify the instance of found text to replace (i.e. first instance, second instance, etc.).

SUBSTITUTE is case-sensitive. To replace one or more characters with nothing, enter an empty string («»).

Examples

Below are the formulas used in the example shown above:

=SUBSTITUTE(B5,"t","b") // replace all t's with b's
=SUBSTITUTE(B6,"t","b",1) // replace first t with b
=SUBSTITUTE(B7,"cat","dog") // replace cat with dog
=SUBSTITUTE(B8,"&","") // replace # with nothing
=SUBSTITUTE(B9,"-",", ") // replace hyphen with comma

The SUBSTITUTE function cannot replace more than one string at a time. However, SUBSTITUTE can be nested inside of itself to accomplish the same thing. For example, with the text «a (dog)» in cell A1, the formula below will strip parentheses () from text:

=SUBSTITUTE(SUBSTITUTE(A1,"(",""),")","") // returns "a dog"

This same approach can be used in a more complex formula to normalize telephone numbers.

Related functions

Use the REPLACE function to replace text at a known location in a text string. Use the SUBSTITUTE function to replace text by searching when the location is not known. Use FIND or SEARCH to determine the location of specific text.

Notes

  • SUBSTITUTE finds and replaces old_text with new_text in a text string.
  • Instance limits SUBSTITUTE replacement a particular instance of old_text.
  • When instance is omitted, all instances of old_text are replaced with new_text.
  • SUBSTITUTE is case-sensitive and does not support wildcards.

What Is REPLACE function In Excel?

The Excel REPLACE function replaces an old text from a string with a new string. The input required by this function is the old text, new text, and the starting and ending numbers of the characters, which must be replaced.

The REPLACE function in Excel is an inbuilt text function, similar to a SUBSTITUTE function, so we can insert the formula from the “Function Library” or enter it directly in the worksheet.

For example, in an Excel spreadsheet with numbers and text, we will replace the number “517” with the other number “987”, and retain the text “ABC”.

Using the Excel REPLACE function, we can apply the formula =REPLACE(“ABC517″,4,3,”987”). And the output will then be “ABC987”.

Table of contents
  • What Is REPLACE function In Excel?
    • Syntax of Excel REPLACE function
    • How To Use REPLACE function In Excel?
    • Important Things To Note
    • REPLACE Excel Function Video
    • Recommended Articles
  • The Excel REPLACE function is a Text function thathelps users replace an old text character or an entire string with a new set of characters or strings.
  • As a worksheet function, it can be written as a part of a formula in a worksheet cell. It can be used in macro code as a VBA function, entered through the Microsoft Visual Basic Editor integrated with MS Excel.
  • The second parameter, start_num, and the third parameter, num_chars, cannot have a non-numeric or a negative value.

Syntax of Excel REPLACE function

The syntax of the Excel REPLACE formula is,

Replace Formula in Excel

Where,

  • old_text: This is a required parameter. It is the original string to be replaced.
  • start_numIt is the starting position in the original string from where the replacement should begin.
  • num_charsIt is a numeric value and indicates the number of characters to be replaced.
  • new_text: It is another required parameter and indicates the new string/set of characters to be replaced the old_text with.

REPLACE-Function-in-Excel

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: Excel REPLACE Function (wallstreetmojo.com)

How To Use REPLACE function In Excel?

The REPLACE function is used in 2 ways, namely,

  1. Access from the Excel ribbon.
  2. Enter in the worksheet manually.

Method #1: Access from the Excel ribbon

First, choose an empty cell – select the “Formulas” tab – go to the “Function Library” group – click the “Text” option drop-down – select the “REPLACE” function, as shown below.

Excel Replace Function - Formulas - Replace

The “Function Arguments” window opens. Enter the arguments in the “Old_text, Start_num, Num_chars, New_text” fields, and click “OK”, as shown below.

Excel Replace Function - Formulas - Arguments

Method #2: Enter in the worksheet manually

  1. Choose an empty cell for the output.
  2. Type =REPLACE( in the cell. [Alternatively, type =R or =RE, and select the REPLACE function from the suggestions given by Excel]
  3. Enter the arguments as cell values or cell references.
  4. Close the brackets, and press the “Enter” key to execute the formula.

Examples

We will consider some specific scenarios and their corresponding examples, such as,

  • Replace a string
  • Replace a Substring
  • Replace a Single Character
  • Replace numbers
  • Remove a string
  • Common Problem with REPLACE function

You can download this REPLACE Function Excel Template here – REPLACE Function Excel Template

Example #1 – Replace a string

In this example, cell C4 has a REPLACE formula associated with it. So, C4 is a result cell.

REPLACE Function Example 1

The steps to apply the REPLACE formula are as follows:

  1. The first argument of the REPLACE function is B4, which contains the original string to be replaced.
  2. The second argument is 1, which indicates the starting letter of the original string.
  3. The third argument is 4, which is the number of characters to be replaced.
  4. The fourth and last parameter is “Stephen”, a new string to be replaced with.

The old string is “John”, and the new string is “Stephen”.

Example #2 – Replace a Substring

REPLACE Function Example 2

In this example, cell C6 has a formula associated with it. So, C6 is a result cell.

  • The first argument of the REPLACE function is B6, which contains the original string to be replaced.
  • The second argument is 5, which indicates the starting letter of the original string.
  • The third argument is 5, which is the number of characters to be replaced.
  • The fourth and last parameter is yahoo, a new string to be replaced with.

The old string is “gmail”, and the new string is “yahoo”. As a result, C6 is updated with “[email protected].”

Example #3 – Replace a Single Character

Example 3

In this example, cell C8 has a REPLACE formula associated with it. So, C8 is a result cell.

  • The first argument of the REPLACE function is B8, which contains the original string to be replaced.
  • The second argument is 1, which indicates the starting letter of the original string.
  • The third argument is 1, which is the number of characters to be replaced.
  • The fourth and last parameter is “s,” which is a new character to be replaced with.

Here, the old character is n, and the new character is s. As a result, C8 is updated with “set.”

Example #4 – Replace numbers

Example 4

In this example, cell C10 has a REPLACE formula associated with it. So, C10 is a result cell.

  • The first argument of the REPLACE function is B10, which contains the original string to be replaced.
  • The second argument is 7, which indicates the starting letter of the original string.
  • The third argument is 4, which is the number of characters to be replaced.
  • The fourth and last parameter is “2000,” a new string to be returned with.

The old string is “1989.” The new string is “2000.” As a result, C8 is updated with “23-12-2000.”

Example #5 – Remove a string

Example 5

In this example, cell C12 has a REPLACE formula associated with it. So, C12 is a result cell.

  • The first argument of the REPLACE function is B12, which contains the original string to be replaced.
  • The second argument is 1, which indicates the starting letter of the original string.
  • The third argument is 11, which is the number of characters to be replaced.
  • The fourth and last parameter is “” which is a new string (an empty string) to be replaced with.

Here, the old string is “Remove this,” and the new string is “”. As a result, C12 is updated to a blank cell as all the characters are replaced with blanks.

Example #6 – Common Problem with REPLACE Function

example 6

In this example, cell C14 has a REPLACE formula associated with it. So, C14 is a result cell.

  • The first argument of the REPLACE function is B14, which contains the original string to be replaced.
  • The second argument is 0.

However, any string in an Excel worksheet cell starts with 1, index 1. So, the result in cell C14 is an error which is #VALUE! indicating that there is an error in the value.

Important Things To Note

  • We get the #VALUE! error, when either of the second, third, or fourth argument value is not provided.
  • If the proper cell value or cell reference is not selected, we get the “#NAME?” error.

REPLACE Excel Function Video

Frequently Asked Questions (FAQs)

1. How to insert REPLACE function in Excel?

We can insert the REPLACE function in Excel as follows:
1. Choose an empty cell for the output.
2. Type =REPLACE( in the cell. [Alternatively, type =R or =RE, and select the REPLACE function from the suggestions given by Excel]
3. Enter the arguments as cell values or cell references.
4. Close the brackets, and press the “Enter” key to execute the formula.

2. Where is the REPLACE function in Excel?

The REPLACE function is found as follows:
First, choose an empty cell – select the “Formulas” tab – go to the “Function Library” group – click the “Text” option drop-down – select the “REPLACE” function, as shown below.

Excel Replace Function - Formulas - Replace

3. Why is the REPLACE function in Excel not working?

The REPLACE function may not work for the following reasons,
We have not selected a proper cell value or cell reference.
We have not entered the start_num, and num_chars, argument values.

Download Template

This article must help understand Excel REPLACE function with its formulas and examples. You can download the template here to use it instantly.

Recommended Articles

This article has been a guide to Excel REPLACE Function. Here we replace/substitute existing string/text with another string, examples & downloadable excel template. You may also look at these useful functions in Excel: –

  • Excel VBA Find and Replace
  • VBA Replace String
  • Substring Function in VBA
  • Left Function in VBA | Examples
  • Excel MAXIFS

На чтение 1 мин

Функция ЗАМЕНИТЬ (REPLACE) в Excel используется для замены части текста одной строки, другим текстом.

Содержание

  1. Что возвращает функция
  2. Синтаксис
  3. Аргументы функции
  4. Дополнительная информация
  5. Примеры использования функции ЗАМЕНИТЬ в Excel

Что возвращает функция

Возвращает текстовую строку, в которой часть текста заменена на другой текст.

Синтаксис

=REPLACE(old_text, start_num, num_chars, new_text) — английская версия

=ЗАМЕНИТЬ(стар_текст;начальная_позиция;число_знаков;нов_текст) — русская версия

Аргументы функции

  • old_text (стар_текст) — который вы хотите заменить;
  • start_num (начальная_позиция) — стартовая позиция (порядковый номер символа), с которой вы хотите осуществить замену текста;
  • num_chars (число_знаков) — количество символов, которое вы хотите заменить;
  • new_text (нов_текст) — новый текст, которым вы замените текст из аргумента old_text (стар_текст).

Дополнительная информация

Аргументы стартовой позиции и количество символов для замены текста не могут быть отрицательными.

Telegram Logo Больше лайфхаков в нашем Telegram Подписаться

Примеры использования функции ЗАМЕНИТЬ в Excel

Функция ЗАМЕНИТЬ в Excel

In this tutorial, I will show you how to use the REPLACE function in Excel (with examples).

Excel REPLACE Function

Replace is a text function that allows you to quickly replace a string or a part of the string with some other text string.

This can be really useful when you’re working with a large dataset and you want to replace or remove a part of the string. But the real power of the replace function can be unleashed when you use it with other formulas in Excel (as we will in the examples covered later in this tutorial).

Before I show you the examples of using the function, let me quickly cover the syntax of the REPLACE function.

Syntax of the REPLACE Function

=REPLACE(old_text, start_num, num_chars, new_text)

Input Arguments

  • old_text – the text that you want to replace.
  • start_num – the starting position from where the search should begin.
  • num_chars – the number of characters to replace.
  • new_text – the new text that should replace the old_text.

Note that the Start Number and Number of Characters argument cannot be negative.

Now let’s have a look at some examples to see how the REPLACE function can be used in Excel.

Example 1 – Replace Text with Blank

Suppose you have the following data set and you want to replace the text “ID-” and only want to keep the numeric part.

Replace ID from the text - Dataset

You can do this by using the following formula:

=REPLACE(A2,1,3,"")

The above formula replaces the first three characters of the text in each cell with a blank.

Replace formula to replace text with a blank

Note: The same result can also be achieved by other techniques such as using the Find and Replace or by extracting the text to the right of the dash by using the combination of RIGHT and FIND functions.

Example 2: Extract the User Name from the Domain name

Suppose you have a dataset as shown below and you want to remove the domain part (the one that follows the @ sign).

Email Dataset for Replace Function Example

To do this, you can use the below formula:

=REPLACE(A2,FIND("@",A2),LEN(A2)-FIND("@",A2)+1,"")

Formula to get the username from an email

The above function uses a combination of REPLACE, LEN and FIND function.

It first uses the FIND function to get the position of the @. This value is used as the Start Number argument and I want to remove the entire text string starting from the @ sign.

Another thing I need to remove this string is the total number of characters after the @ so that I can specify these many characters to be replaced with a blank. This is where I have used the formula combination of LEN and FIND.

Pro Tip: In the above formula, since I want to remove all the characters after the @ sign, I don’t really need the number of characters. I can specify any large number (which is greater than the number of characters after the @ sign), and I will get the same result. So I can even use the following formula: =REPLACE(A2,FIND(“@”,A2),LEN(A2),””)

Example 3: Replace One Text String with Another

In the above two examples, I showed you how to extract a part of the string by replacing the remaining with blank.

Here is an example where you change one text string with another.

Suppose you have the below dataset and you want to change the domain from example.net to example.com.

replace domain name TLDs

You can do this using the below formula:

=REPLACE(A2,FIND("net",A2),3,"com")

Replace domain TLD using the formula

Difference between Replace and Substitute functions

There is a major difference in the usage of the REPLACE function and the SUBSTITUTE function (although the result expected from these may be similar).

The REPLACE function requires the position from which it needs to start replacing the text. It then also requires the number of characters you need to replace with the new text. This makes REPLACE function suitable where you have a clear pattern in the data and want to replace text.

A good example of this could be when working with email ids or address or ids – where the construct of the text is consistent.

SUBSTITUTE function, on the other hand, is a little more versatile. You can use it to replace all the instances of an occurrence of a string with some other string.

For example, I can use it to replace all the occurrence of character Z with J in a text string. And at the same time, it also gives you the flexibility to only change a specific instance of the occurrence (for example, only substitute the first occurrence of the matching string or only the second occurrence).

Note: In many cases, you can do away with using the REPLACE function and instead use the FIND and REPLACE functionality. It will allow you to change the data set without using the formula and getting the result in another column/row. REPLACE function is more suited when you want to keep the original dataset and also want the resulting data to be dynamic (such that updates in case you change the original data).

Excel REPLACE Function – Video Tutorial

Related Excel Functions:

  • Excel FIND Function.
  • Excel LOWER Function.
  • Excel UPPER Function.
  • Excel PROPER Function.
  • Excel SEARCH Function.

You may also like the following Excel Tutorials:

  • How to Remove the First Character from a String in Excel

Skip to content

Формула ЗАМЕНИТЬ и ПОДСТАВИТЬ для текста и чисел

В статье объясняется на примерах как работают функции Excel ЗАМЕНИТЬ (REPLACE в английской версии) и ПОДСТАВИТЬ (SUBSTITUTE по-английски). Мы покажем, как использовать функцию ЗАМЕНИТЬ с текстом, числами и датами, а также как вложить несколько функций ЗАМЕНИТЬ или ПОДСТАВИТЬ в одну формулу.

Функции Excel ЗАМЕНИТЬ и ПОДСТАВИТЬ используются для замены одной буквы или части текста в ячейке. Но делают они это немного по-разному. Об этом и поговорим далее.

Как работает функция ЗАМЕНИТЬ  

Функция ЗАМЕНИТЬ  позволяет заместить слово, один или несколько символов в текстовой строке другим словом или символом.

ЗАМЕНИТЬ(старый_текст; начальная_позиция; число_знаков, новый_текст)

Как видите, функция ЗАМЕНИТЬ имеет 4 аргумента, и все они обязательны для заполнения.

  • Старый_текст — исходный текст (или ссылка на ячейку с исходным текстом), в котором вы хотите поменять некоторые символы.
  • Начальная_позиция — позиция первого символа в старый_текст, начиная с которого вы хотите сделать замену.
  • Число_знаков — количество символов, которые вы хотите заместить новыми.
  • Новый_текст – текст замены.

Например, чтобы исправить слово «кит» на «кот», следует поменять вторую букву в слове. Вы можете использовать следующую формулу:

=ЗАМЕНИТЬ(«кит»;2;1;»о»)

И если вы поместите исходное слово в какую-нибудь ячейку, скажем, A2, вы можете указать соответствующую ссылку на ячейку в аргументе старый_текст:

=ЗАМЕНИТЬ(А2;2;1;»о»)

Примечание. Если аргументы начальная_позиция или число_знаков отрицательные или не являются числом, формула замены возвращает ошибку #ЗНАЧ!.

Использование функции ЗАМЕНИТЬ с числами

Функция ЗАМЕНИТЬ предназначена для работы с текстом. Но безусловно, вы можете использовать ее для замены не только букв, но и цифр, являющихся частью текстовой строки, например:

=ЗАМЕНИТЬ(A1; 9; 4; «2023»)

как заменить значения в ячейке Эксель

Обратите внимание, что мы заключаем «2023» в двойные кавычки, как вы обычно делаете с текстовыми значениями.

Аналогичным образом вы можете заменить одну или несколько цифр в числе. Например формула:

=ЗАМЕНИТЬ(A1;3;2;»23″)

И снова вы должны заключить значение замены в двойные кавычки («23»).

Примечание. Формула ЗАМЕНИТЬ всегда возвращает текстовую строку, а не число. На скриншоте выше обратите внимание на выравнивание по левому краю возвращаемого текстового значения в ячейке B1 и сравните его с исходным числом, выровненным по правому краю в A1. А поскольку это текст, вы не сможете использовать его в других вычислениях, пока не преобразуете его обратно в число, например, умножив на 1 или используя любой другой метод, описанный в статье Как преобразовать текст в число.

Как заменить часть даты

Как вы только что видели, функция ЗАМЕНИТЬ отлично работает с числами, за исключением того, что она возвращает текстовую строку :) Помните, что во внутренней системе Excel даты хранятся в виде чисел. Поэтому нельзя пытаться заменить часть даты, работая с ней как с текстом.

Например, у вас есть дата в A3, скажем, 15 июля 1992г., и вы хотите изменить «июль» на «май». Итак, вы пишете формулу ЗАМЕНИТЬ(A3; 4; 3; «Май»), которая предписывает Excel поменять 3 символа в ячейке A3, начиная с четвертого. Мы получили следующий результат:

Почему так? Потому что «15-июл-92» — это только визуальное представление базового серийного номера (33800), представляющего дату. Итак, наша формула замены заменяет цифры начиная с четвертой (а это два нуля) в указанном выше числе на текст «Май» и возвращает в результате текстовую строку «338Май».

Чтобы заставить функцию ЗАМЕНИТЬ правильно работать с датами, вы должны сначала преобразовать даты в текстовые строки, используя функцию ТЕКСТ. Кроме того, вы можете встроить функцию ТЕКСТ непосредственно в аргумент старый_текст функции ЗАМЕНИТЬ:

=ЗАМЕНИТЬ(ТЕКСТ(A3; «дд-ммм-гг»); 4; 3; «Май»)

Помните, что результатом приведенной выше формулы является текстовая строка, и поэтому это решение работает только в том случае, если вы не планируете использовать измененные даты в своих дальнейших расчетах. Если вам нужны даты, а не текстовые строки, используйте функцию ДАТАЗНАЧ , чтобы преобразовать значения, возвращаемые функцией Excel ЗАМЕНИТЬ, обратно в даты:

=ДАТАЗНАЧ(ЗАМЕНИТЬ(ТЕКСТ(A3; «дд-ммм-гг»); 4; 3; «Май»))

Как заменить сразу несколько букв или слов

Довольно часто может потребоваться выполнить более одной замены в одной и той же ячейке Excel. Конечно, можно было сделать одну замену, вывести промежуточный результат в дополнительный столбец, а затем снова использовать функцию ЗАМЕНИТЬ. Однако лучший и более профессиональный способ — использовать вложенные функции ЗАМЕНИТЬ, которые позволяют выполнить сразу несколько замен с помощью одной формулы. В этом смысле «вложение» означает размещение одной функции внутри другой.

Рассмотрим следующий пример. Предположим, у вас есть список телефонных номеров в столбце A, отформатированный как «123456789», и вы хотите сделать их более похожими на привычные нам  телефонные номера, добавив дефисы. Другими словами, ваша цель — превратить «123456789» в «123-456-789».

Вставить первый дефис легко. Вы пишете обычную формулу замены Excel, которая заменяет ноль символов дефисом, т.е. просто добавляет дефис на четвёртой позиции в ячейке:

=ЗАМЕНИТЬ(A3;4;0;»-«)

Результат приведенной выше формулы замены выглядит следующим образом:

А теперь нам нужно вставить еще один дефис в восьмую позицию. Для этого вы помещаете приведенную выше формулу в еще одну функцию Excel ЗАМЕНИТЬ. Точнее, вы встраиваете её в аргумент старый_текст другой функции, чтобы вторая функция ЗАМЕНИТЬ обрабатывала значение, возвращаемое первой формулой, а не первоначальное значение из ячейки А3:

=ЗАМЕНИТЬ(ЗАМЕНИТЬ(A3;4;0;»-«);8;0;»-«)

В результате вы получаете номера телефонов в нужном формате:

Аналогичным образом вы можете использовать вложенные функции ЗАМЕНИТЬ, чтобы текстовые строки выглядели как даты, добавляя косую черту (/) там, где это необходимо:

=ЗАМЕНИТЬ(ЗАМЕНИТЬ(A3;3;0;»/»);6;0;»/»)

Кроме того, вы можете преобразовать текстовые строки в реальные даты, обернув приведенную выше формулу ЗАМЕНИТЬ функцией ДАТАЗНАЧ:

=ДАТАЗНАЧ(ЗАМЕНИТЬ(ЗАМЕНИТЬ(A3;3;0;»/»);6;0;»/»))

И, естественно, вы не ограничены в количестве функций, которые вы можете последовательно, как матрёшки, вложить друг в друга в одной формуле (современные версии Excel позволяют использовать до 8192 символов и до 64 вложенных функций в одной формуле).

Например, вы можете попробовать 3 вложенные функции ЗАМЕНИТЬ, чтобы число отображалось как дата и время:

=ЗАМЕНИТЬ(ЗАМЕНИТЬ(ЗАМЕНИТЬ(ЗАМЕНИТЬ(A3;3;0;»/»);6;0;»/»);9;0;» «);12;0;»:»)

Как заменить текст в разных местах

До сих пор во всех примерах мы имели дело с простыми задачами и производили замены в одной и той же позиции в каждой ячейке. Но реальные задачи часто бывают сложнее. В ваших рабочих листах заменяемые символы могут не обязательно появляться в одном и том же месте в каждой ячейке, и поэтому вам придется найти позицию первого символа, начиная с которого нужно заменить часть текста. Следующий пример продемонстрирует то, о чем я говорю.

Предположим, у вас есть список адресов электронной почты в столбце A. И название одной компании изменилось с «ABC» на, скажем, «BCA». Изменилось и название их почтового домена. Таким образом, вы должны соответствующим образом обновить адреса электронной почты всех клиентов и заменить три буквы в адресах электронной почты, где это необходимо.

Но проблема в том, что имена почтовых ящиков имеют разную длину, и поэтому нельзя указать, с какой именно позиции начинается название домена. Другими словами, вы не знаете, какое значение указать в аргументе начальная_позиция функции Excel ЗАМЕНИТЬ. Чтобы узнать это, используйте функцию Excel НАЙТИ, чтобы определить позицию, с которой начинается доменное имя в адресе электронной почты:

=НАЙТИ(«@abc»; A3)

Затем вставьте указанную выше функцию НАЙТИ в аргумент начальная_позиция формулы ЗАМЕНИТЬ:

=ЗАМЕНИТЬ(A3; НАЙТИ(«@abc»;A3); 4; «@bca»)

ПримечаниеМы включаем символ «@» в нашу формулу поиска и замены Excel, чтобы избежать случайных ошибочных замен в именах почтовых ящиков электронной почты. Конечно, вероятность того, что такие совпадения произойдут, очень мала, и все же вы можете перестраховаться.

Как вы видите на скриншоте ниже, у формулы нет проблем, чтобы поменять символы в разных позициях. Однако если заменяемая текстовая строка не найдена и менять в ней ничего не нужно, формула возвращает ошибку #ЗНАЧ!:

 Excel как заменить буквы в адресе

И мы хотим, чтобы формула вместо ошибки возвращала исходный адрес электронной почты без изменения.  Для этого заключим нашу формулу НАЙТИ И ЗАМЕНИТЬ в функцию ЕСЛИОШИБКА:

=ЕСЛИОШИБКА(ЗАМЕНИТЬ(A3; НАЙТИ(«@abc»;A3); 4; «@bca»);A3)

И эта доработанная формула прекрасно работает, не так ли?

Заменить заглавные буквы на строчные и наоборот

Еще один полезный пример – заменить первую строчную букву в ячейке на прописную (заглавную). Всякий раз, когда вы имеете дело со списком имен, товаров и т.п., вы можете использовать приведенную ниже формулу, чтобы изменить первую букву на ЗАГЛАВНУЮ. Ведь названия товаров могут быть записаны по-разному, а в списках важно единообразие.

Таким образом, нам нужно заменить первый символ в тексте на заглавную букву. Используем формулу

=ЗАМЕНИТЬ(СТРОЧН(A3);1;1;ПРОПИСН(ЛЕВСИМВ(A3;1)))

excel заменить первые буквы на заглавные

Как видите, эта формула сначала заменяет все буквы в тексте на строчные при помощи функции СТРОЧН, а затем первую строчную букву меняет на заглавную (прописную).

Быть может, это будет полезно.

Описание функции ПОДСТАВИТЬ

Функция ПОДСТАВИТЬ в Excel заменяет один или несколько экземпляров заданного символа или текстовой строки указанными символами.

Синтаксис формулы ПОДСТАВИТЬ в Excel следующий:

ПОДСТАВИТЬ(текст, старый_текст, новый_текст, [номер_вхождения])

Первые три аргумента являются обязательными, а последний – нет.

  • Текст – исходный текст, в котором вы хотите заменить слова либо отдельные символы. Может быть тестовой строой, ссылкой на ячейку или же результатом вычисления другой формулы.
  • Старый_текст – что именно вы хотите заменить.
  • Новый_текст – новый символ или слово для замены старого_текста.
  • Номер_вхождения — какой по счёту экземпляр старый_текст вы хотите заменить. Если этот параметр опущен, все вхождения старого текста будут заменены новым текстом.

Например, все приведенные ниже формулы подставляют вместо «1» – цифру «2» в ячейке A2, но возвращают разные результаты в зависимости от того, какое число указано в последнем аргументе:

=ПОДСТАВИТЬ(A3;»1″;»2″;1) — Заменяет первое вхождение «1» на «2».

=ПОДСТАВИТЬ(A3;»1″;»2″;2) — Заменяет второе вхождение «1» на «2».

=ПОДСТАВИТЬ(A3;»1″;»2″) — Заменяет все вхождения «1» на «2».

На практике формула ПОДСТАВИТЬ также используется для удаления ненужных символов из текста. Вы просто меняете их на пустую строку “”.

Например, чтобы удалить пробелы из текста, замените их на пустоту.

=ПОДСТАВИТЬ(A3;» «;»»)

Примечание. Функция ПОДСТАВИТЬ в Excel чувствительна к регистру . Например, следующая формула меняет все вхождения буквы «X» в верхнем регистре на «Y» в ячейке A2, но не заменяет ни одной буквы «x» в нижнем регистре.

=ПОДСТАВИТЬ(A3;»Х»;»Y»)

Замена нескольких значений одной формулой

Как и в случае с функцией ЗАМЕНИТЬ, вы можете вложить несколько функций ПОДСТАВИТЬ в одну формулу, чтобы сделать несколько подстановок одновременно, т.е. заменить несколько символов или подстрок при помощи одной формулы.

Предположим, у вас есть текстовая строка типа « пр1, эт1, з1 » в ячейке A3, где «пр» означает «Проект», «эт» означает «этап», а «з» означает «задача». Вы хотите заместить три этих кода их полными эквивалентами. Для этого вы можете написать 3 разные формулы подстановки:

=ПОДСТАВИТЬ(A3;»пр»;»Проект «)

=ПОДСТАВИТЬ(A3;»эт»;»Этап «)

=ПОДСТАВИТЬ(A3;»з»;»Задача «)

А затем вложить их друг в друга:

=ПОДСТАВИТЬ(ПОДСТАВИТЬ(ПОДСТАВИТЬ(A3;»пр»;»Проект «); «эт»;»Этап «);»з»;»Задача «)

Обратите внимание, что мы добавили пробел в конце каждого аргумента новый_текст для лучшей читабельности.

Другие полезные применения функции ПОДСТАВИТЬ:

  • Замена неразрывных пробелов в ячейке Excel обычными
  • Убрать пробелы в числах
  • Удалить перенос строки в ячейке
  • Подсчитать определенные символы в ячейке

Что лучше использовать – ЗАМЕНИТЬ или ПОДСТАВИТЬ?

Функции Excel ЗАМЕНИТЬ и ПОДСТАВИТЬ очень похожи друг на друга в том смысле, что обе они предназначены для подмены отдельных символов или текстовых строк. Различия между двумя функциями заключаются в следующем:

  • ПОДСТАВИТЬ замещает один или несколько экземпляров данного символа или текстовой строки. Итак, если вы знаете тот текст, который нужно поменять, используйте функцию Excel ПОДСТАВИТЬ.
  • ЗАМЕНИТЬ замещает символы в указанной позиции текстовой строки. Итак, если вы знаете положение заменяемых символов, используйте функцию Excel ЗАМЕНИТЬ.
  • Функция ПОДСТАВИТЬ в Excel позволяет добавить необязательный параметр (номер_вхождения), указывающий, какой по счету экземпляр старого_текста следует заместить на новый_текст.

Вот как вы можете заменить текст в ячейке и использовать функции ПОДСТАВИТЬ и ЗАМЕНИТЬ в Excel. Надеюсь, эти примеры окажутся полезными при решении ваших задач. 

Понравилась статья? Поделить с друзьями:
  • Text prompts in word
  • Text prompt in word
  • Texts with word process
  • Text positioning in word
  • Texts from my excel