How to Create a Macro Code to Achieve Find and Replace Text in Excel


Excel macros are useful tools that you may use to automate repetitive tasks and save time. We'll demonstrate how to construct a macro code in this article so you may find certain text in your Excel worksheets and replace it with new data. The search and replace feature is incredibly useful when you need to update several instances of a particular term or phrase within a sizable dataset. By writing your own macro code, you can expedite this process and do find and replace operations with only a few clicks.

We will presume that you are familiar with Excel's user interface and that you have a basic comprehension of the program throughout this tutorial. So let's get started and learn how to write a macro code that will allow you to automate the find and replace procedure in Excel if you're prepared to save time and increase your productivity in this way.

Create a Macro Code to Achieve Find and Replace Text

Here, we will first create a VBA module and then run it to complete the task. So let us see a simple process to learn how you can create a macro code to find and replace text in Excel.

Step 1

Consider an Excel sheet where you have a list of strings.

First, right-click on the sheet name and select View Code to open the VBA application.

Step 2

Then click on Insert and select Module, then copy the below code into the text box.

Insert > Module > Copy.

Example

Sub FindandReplaceText()
    Dim xFind As String
    Dim xRep As String
    Dim xRg As Range
    On Error Resume Next
    Set xRg =Cells
    xFind = Application.InputBox("word to search:", "Create Macro Code", , , , , 2)
    xRep = Application.InputBox("word to replace:", "Create Macro Code", , , , , 2)
    If xFind = "False" Or xRep = "False" Then Exit Sub
    xRg.Replace xFind, xRep, xlPart, xlByRows, False, False, False, False
End Sub

Step 3

Then click F5 to run the module. Then enter the text to find the box and click OK.

F5 > Text > Ok.

Step 4

Finally, enter the text to replace and click OK.

Text > Ok.

Conclusion

In this tutorial, we have used a simple example to demonstrate how you can create a macro code to find and replace text in Excel to highlight a particular set of data.

Updated on: 12-Jul-2023

552 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements