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.
By clicking Options, you can see advanced search options:
You can easily access these methods using VBA.
Find VBA Example
To demonstrate the Find functionality, we created the following data set in Sheet1.
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!
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.
Содержание
- VBA Replace Function to Replace Characters in a String
- The VBA Tutorials Blog
- Introduction — VBA Replace
- Example — VBA Replace
- Tutorial — VBA Replace
- Replace first 2 instances in a string
- Replace last occurrence of substring in a string
- Replace starting at the 10th character
- Replace starting at the 10th character and keep whole string
- Application Ideas — VBA Replace
- Find and Replace Cells with VBA
- The VBA Tutorials Blog
- Our Dataset
- The Inefficient Approach
- The .Replace Method
- Expanding the Range
- The Other .Replace Parameters
- LookAt Optional Argument
- MatchCase Optional Argument
- Other Parameters
- Функция Replace
- Синтаксис
- Параметры
- Возвращаемые значения
- Замечания
- См. также
- Поддержка и обратная связь
VBA Replace Function to Replace Characters in a String
The VBA Tutorials Blog
Introduction — VBA Replace
Use the VBA Replace function to replace a substring of characters in a string with a new string. VBA Replace is similar to the Excel SUBSTITUTE function; both can be used to replace a portion of a string with another.
Example — VBA Replace
Make powerful macros with our free VBA Developer Kit
This is actually pretty neat. If you have trouble understanding or remembering it, our free VBA Developer Kit can help. It’s loaded with VBA shortcuts to help you make your own macros like this one — we’ll send a copy, along with our Big Book of Excel VBA Macros, to your email address below.
Tutorial — VBA Replace
This is a very basic macro. I defined my string, then instantly changed it. You likely won’t be using your Replace function in this manner. In practice, you’ll probably be passing a cell, like Range(«a1») . Yep, you can pass cells to the Replace function, too!
Anyway, when the macro finishes, the string str1 will be changed from:
All instances of fish were replaced with the string cat . This is the same way the Excel SUBSTITUTE() function replaces portions of a string.
You can see how a macro like this could be useful for replacing a “.csv” with a “.xlsx” extension in a list of file names, for example.
Okay, time to talk more about the VBA Replace function. The VBA Replace function requires 3 arguments, but it can accept as many as 6 arguments. I’ll give you a nice description of each of these arguments, then I’ll show you a few examples:
VBA Replace Function Arguments
Argument | Optional | Description |
---|---|---|
Expression | The original string you want to replace characters in. | |
Find | The substring you want to find within your Expression. This will be the string removed from your Expression. | |
Replace | What you want to replace the string you found with. This will be the string added to your Expression. | |
Start | Optional | Where in your Expression you want to begin finding and replacing. The default is 1, so it begins at the first character. |
Count | Optional | The number of replacements you want to make. If there are multiple instances of the substring Find, it will only replace however many you define in this argument. The default is to replace all instances. |
Compare | Optional | Specifies the comparison method to be used. The options are vbBinaryCompare (default), vbDatabaseCompare, and vbTextCompare. You’ll rarely use this option so there’s no need to get too caught up on each of these options. The default is usually fine. |
We know how to do a basic find and replace in a string using the Replace VBA function. Let’s look at a few examples of how the optional Replace arguments can change your results.
Replace first 2 instances in a string
Result: One cat, two cat, red fish, blue fish
Once the VBA Replace function finds the first 2 instances of the word cat , it stops replacing them and the macro ends.
Replace last occurrence of substring in a string
Result: One fish, two fish, red fish, blue cat
This is kind of an interesting one. I use the VBA function strReverse to write the string backward, and then I search for the first instance of the backward string inside the main string. The Replace function is really replacing the first instance of your string, but I’ve reversed the string so the first instance is really the last instance. It sounds confusing, but it’s a neat little trick!
Replace starting at the 10th character
Result: two cat, red cat, blue cat
That’s right. When you specify a starting position, Replace truncates the characters from the 1st character to the Nth character you specify. The first 9 characters are missing! Here’s how you can fix that if you still want all the characters:
Replace starting at the 10th character and keep whole string
Result: One fish, two cat, red cat, blue cat
The first fish remains and the rest are replaced. I retained the first 9 characters by using the VBA Mid function.
Reader’s Note: I’ve created a really awesome user-defined function to help you replace the Nth occurrence of a substring in a string if that’s what you’re searching for!
Application Ideas — VBA Replace
The Replace function of VBA is great for manipulating strings. One great use is to replace date/time stamps, file extensions or personalized greetings for the person logged into a computer. I’m sure you have other great uses for it and I’d love to hear about them!
For more VBA tips, techniques, and tactics, join our VBA Insiders email series using the form below. After you do that, share this article on Twitter and Facebook.
Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.
Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.
Источник
Find and Replace Cells with VBA
The VBA Tutorials Blog
Some spreadsheets contain only a single sheet of data in a few columns and rows. Other spreadsheets contain tens or even hundreds of thousands of datapoints. The latter type often act as miniature databases for smaller businesses or teams within companies where building a full database is unnecessary. Often the datapoints are automatically populated, and they are not always checked for integrity before loading. Sometimes things just change and we need to globally update the information in a spreadsheet.
Whatever the reason, Find and Replace is an invaluable tool for anyone working with spreadsheets. The Excel GUI provides an easy-to-use dialogue to find and replace content throughout a spreadsheet, for both the data and the formulas. But what if, somewhere in the pipeline between origination of the data and its final residence in the spreadsheet, a flaw in the data is algorithmically introduced? No one wants to do exactly the same Find and Replace operation every time data is loaded or entered.
This is a programming blog, and around here we like to automate tasks, no matter how simple. It helps cut down on unnecessary, tedious work, but it also ensures our data is manipulated reliably. So, today let’s look at how to programmatically apply Find and Replace with VBA.
Our Dataset
Throughout this tutorial we’ll manipulate the data in this screenshot. You can download the CSV file here, if you’d like. It isn’t necessary to have all the data locally in your own workbook, but it serves as a good visual aid:
A screenshot of the dataset
The Inefficient Approach
I want to start off with an inefficient approach, which is really just brute-force string manipulation. This is certainly not the most efficient, but by using looped string manipulations and if statements you could check every cell explicitly.
For example, let’s say you import customer information daily, and the currency label resides in Column F . For some reason, the supplied information used Australian dollars (AUD) instead of Canadian dollars (CAD) for your Canadian orders. Most orders are in US dollars (USD), but you do have some Canadian customers. You do not ship to Australia, so you don’t accept AUD.
In this case, to ensure data consistency, you want to replace every instead of AUD with CAD . This is a very straightforward task, and you can write and apply this three-liner in about five seconds:
However, as your dataset grows, this method can become time consuming. It also makes it harder to expand to multiple columns and rows. Fortunately, there is a simpler and more elegant solution.
Make powerful macros with our free VBA Developer Kit
Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.
The .Replace Method
One of the methods attached to the Range object is the .Replace method, which does exactly what you would expect. Be wary that this function is the GUI equivalent of “replace all” within the range, not just “replace the first instance”. In our currency example, we want to replace all instances anyway, so this is fine.
Instead of using a loop, you can set the entire range first and Excel will use its optimized internal code to most efficiently find and replace the errant AUD s. The code is a simple one-liner:
And in the simplest terms, this searches the sixth column between rows 2 and 5000, replacing any instance of “AUD” with the letters “CAD”.
In letter-reference notation, you could use:
It’s important to recognize the Range.Replace method is different from the VBA Replace function, which is used to replace substrings within a string.
Expanding the Range
Of course, if you don’t know where in the spreadsheet certain information occurs, you can expand the range to anything you want. Perhaps your friend called you and said they accidentally entered “AUD” instead of “CAD” for every Canadian purchase. They need your help to fix the mistake! Moreover, they can’t show you the spreadsheet because it’s proprietary.
Well, you could tell them to write this line of code, which covers a gigantic area, captures every instance of AUD , and turns it into a CAD :
Note: if your friend’s spreadsheet is bigger than this, they need to switch to a real database…
But alas! This has also changed “Audio” into “CADio”! What a disaster.
The Other .Replace Parameters
One pitfall of the .Replace method is that it is non-case-sensitive and replaces any matching string, regardless of whether that string fully matches. Thus, Audio is converted to CADio by mistake, because the three letters A-U-D are matched non-case-sensitively.
You can use the other parameters in the .Replace method to avoid issues like this, even when searching large areas. In this section, I’ll use the named parameter method (:=) of setting them, since there are so many parameters and multiple empty commas is unsightly and a bit confusing.
LookAt Optional Argument
The first optional argument is LookAt , which accepts two options: xlWhole or xlPart . The function defaults to the latter, so when we searched for AUD , it rewrote any string that contained those three letters in sequential order.
One way to avoid the debacle for our friend is to ensure this parameter is set to xlWhole :
Now the full word must match for a replacement. Since “Audio” is not exactly the same 3 letters as “AUD”, we don’t end up with “CADio”. If we had an option Audio Audi , xlPart will match both “aud” strings in both words, giving us CADio CADi . Luckily, you can easily avoid this now with LookAt:=xlWhole .
MatchCase Optional Argument
Another approach in this situation could be to match cases. Since we are searching for all uppercase currency codes, and we know the Item Type column is proper case, we could force the case to precisely match to get the same outcome:
A quick quiz for you: if we truly did not know the stylization of the data, would it be better to use LookAt or MatchCase ?
Answer: LookAt , which forces the entire string to match. There is less chance that non-currency entries will be exactly the three letters A-U-D in that particular sequence, while it is very possible “AUD” might appear in multiple words, whether they’re capitalized or not. Had the Item Types used capital letters — as in AUDIO , PERIPHERAL , etc. — using only the MatchCase parameter would still have left us with CADIO .
Other Parameters
For finding and replacing strings in ranges, the other parameters are not important. Whether you choose to search by columns or by rows in SearchOrder is irrelevant for .Replace , because it will replace whatever it finds in all columns and all rows, regardless. Moreover, formatting is related to a completely different function and is not necessary for finding and replacing strings as we’ve explored here.
Replacing all instances of a string of text can be quite useful, particularly to fix mistakes or to update spreadsheets. However, it is important to think through how optional parameters might affect your output, because there is no simple undo button when using VBA. You certainly don’t want to make a mistake that affects 200,000 cells and cannot easily be undone.
If that worries you, I recommend saving your workbook before using .Replace . Or at least test it on a smaller range. You can remind your user to save, too, by running some code to programmatically initiate a Save As Dialog, if you want.
To learn more VBA tips like this one, subscribe using the form below.
Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.
Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.
This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Visit him on LinkedIn and his personal page.
Источник
Функция Replace
Возвращает строку, которая является подстрокой строкового выражения, начинающегося с начальной позиции (по умолчанию — 1), в которой указанная подстрока была заменена другой подстрокой указанное количество раз.
Синтаксис
Replace(expression, find, replace, [ start, [ count, [ compare ]]])
Синтаксис функции Replace содержит следующие именованные аргументы:
Part | Описание |
---|---|
выражение | Обязательно. Строковое выражение, содержащее заменяемую подстроку. |
Найти | Обязательно. Искомая подстрока. |
Заменить | Обязательно. Подстрока замены. |
start | Необязательно. Начальная позиция для поиска и возврата подстроки выражения . Если элемент опущен, предполагается, что он равен 1. |
count | Необязательный параметр. Число выполняемых замен подстроки. Если этот параметр опущен, значение по умолчанию — -1, то есть выполните все возможные подстановки. |
compare | Необязательно. Числовое значение, указывающее тип сравнения, который будет использоваться при оценке подстрок. Значения см. в разделе «Параметры». |
Параметры
Аргумент compare может принимать следующие значения:
Константа | Значение | Описание |
---|---|---|
vbUseCompareOption | –1 | Выполняет сравнение, используя параметр оператора Option Compare. |
vbBinaryCompare | 0 | Выполняется двоичное сравнение. |
vbTextCompare | 1 | Выполняется текстовое сравнение. |
vbDatabaseCompare | 2 | Только Microsoft Access. Выполняется сравнение на основе сведений из базы данных. |
Возвращаемые значения
Функция Replace возвращает следующие значения:
Если | Функция «Replace» возвращает |
---|---|
Элемент expression имеет нулевую длину | Пустая строка («») |
Элемент expression равен Null | Ошибка. |
Элемент find имеет нулевую длину | Копия expression. |
Элемент replace имеет нулевую длину | Копия выражения с удаленными вхождениями поиска . |
Начать>Len(выражение) | Строка нулевой длины. Замена строк начинается с позиции, указанной в начале. |
Элемент count равен 0 | Копия expression. |
Замечания
Возвращаемое значение функции Replace — это строка с подстановками, которая начинается с позиции, указанной start , и завершается в конце строки выражения . Это не копия исходной строки от начала до конца.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
In this VBA Tutorial, you learn how to replace or substitute substrings or characters within strings.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn about commonly-used VBA terms here.
- Learn about the Excel Object Model here.
- Learn about working with variables here.
- Learn about data types here.
- Learn about working with arrays here.
- Practical VBA applications and macro examples:
- Learn about referring to cell ranges here.
- Learn about working with worksheet functions within VBA here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Replace String in Cell
VBA Code to Replace String in Cell
To replace a string in a cell with VBA, use a statement with the following structure:
Cell.Value = Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString, Count:=NumberOfReplacements)
Process Followed by VBA Code to Replace String in Cell
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
- Item: Replace(…).
- VBA Construct: Replace function.
- Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString) a specific number of times (NumberOfReplacements).
- Item: Expression:=Cell.Value.
- VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
- Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
- Item: Find:=StringToReplace.
- VBA Construct: Find parameter of the Replace function.
- Description: The Find parameter of the Replace function specifies the substring you search for and replace.
If you explicitly declare a variable to represent StringToReplace, use the String data type.
- Item: Replace:=ReplacementString.
- VBA Construct: Replace parameter of the Replace function.
- Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.
If you explicitly declare a variable to represent ReplacementString, use the String data type.
- Item: Count:=NumberOfReplacements.
- VBA Construct: Count parameter of the Replace function.
- Description: The Count parameter of the Replace function specifies the number of substitutions you want to carry out. In other words, the number of times you want to replace StringToReplace with ReplacementString.
If you want VBA to replace all occurrences of StringToReplace with ReplacementString, omit the Count parameter. In such case, Count defaults to -1 and VBA carries out all possible substitutions. Please refer to the appropriate section (Replace All Occurrences of String in Cell) below for further information about this scenario.
Macro Example to Replace String in Cell
The following macro replaces the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) one time (myNumberOfReplacements) within the string in cell A5 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceStringInCell() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for string replacement (string to replace, replacement string, and number of replacements) Dim myStringToReplace As String Dim myReplacementString As String Dim myNumberOfReplacements As Long 'identify cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A5") 'specify parameters for string replacement (string to replace, replacement string, and number of replacements) myStringToReplace = "replace" myReplacementString = "substitute" myNumberOfReplacements = 1 'replace string in cell you work with, and assign resulting string to Range.Value property of cell you work with myCell.Value = Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString, Count:=myNumberOfReplacements) End Sub
Effects of Executing Macro Example to Replace String in Cell
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “replace” with the string “substitute” one time within the string in cell A5.
#2: Replace String in Cell Specifying a Starting Position for Search
VBA Code to Replace String in Cell Specifying a Starting Position for Search
To replace a string in a cell and specify the starting position to search for the string with VBA, use a statement with the following structure:
Cell.Value = Left(String:=Cell.Value, Length:=StartPosition - 1) & Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString, Start:=StartPosition, Count:=NumberOfReplacements)
Process Followed by VBA Code to Replace String in Cell Specifying a Starting Position for Search
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
- Item: Left(…).
- VBA Construct: Left function.
- Description: The Left function returns a string containing the number of characters specified by the Length parameter (StartPosition – 1) from the left side of the string specified by the String parameter (Cell.Value).
Within this macro structure, you use the Left function to return the substring containing the first characters of the string within the cell you work with. This substring goes from the first character of the string to the character immediately before the position within the string where you start searching for the substring you want to replace (StringToReplace).
You need to do this because the Replace function doesn’t return a copy of the string (with substitutions) from start to finish. The string that Replace returns starts at the position within the string where you start searching for the substring you want to replace (StartPosition). Therefore, VBA truncates the string and the characters to the left of StartPosition aren’t part of the string returned by Replace.
- Item: String:=Cell.Value.
- VBA Construct: String parameter of the Left function, Range object and Range.Value property.
- Description: The String parameter of the Left function specifies the string expression containing the substring you want to replace (StringToReplace).
Within this macro structure, String is the value (string) within Cell, as returned by the Range.Value property. The value of the String parameter of the Left function is the same as the value of the Expression parameter of the Replace function.
- Item: Length:=StartPosition – 1.
- VBA Construct: Length parameter of the Left function.
- Description: The Length parameter of the Left function specifies the number of characters the Left function returns from the string you work with. StartPosition is the position within the string where you start searching for the substring you want to replace (StringToReplace). (StartPosition – 1) is the position of the character immediately before StartPosition. Therefore, the Left function returns the substring containing the first characters of the string within the cell you work with, up until the character located in position (StartPosition – 1).
If you explicitly declare a variable to represent StartPosition, use the Long data type. The value of StartPosition within the Length parameter of the Left function is the same as the value of the Start parameter of the Replace function.
- Item: &.
- VBA Construct: Concatenation operator.
- Description: The & operator concatenates the strings returned by the Left and Replace functions.
- Item: Replace(…).
- VBA Construct: Replace function.
- Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString) a specific number of times (NumberOfReplacements).
- Item: Expression:=Cell.Value.
- VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
- Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
- Item: Find:=StringToReplace.
- VBA Construct: Find parameter of the Replace function.
- Description: The Find parameter of the Replace function specifies the substring you search for and replace.
If you explicitly declare a variable to represent StringToReplace, use the String data type.
- Item: Replace:=ReplacementString.
- VBA Construct: Replace parameter of the Replace function.
- Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.
If you explicitly declare a variable to represent ReplacementString, use the String data type.
- Item: Start:=StartPosition.
- VBA Construct: Start parameter of the Replace function.
- Description: The Start parameter of the Replace function specifies the position within the string you work with where you start searching for StringToReplace.
The default value of the Start parameter is 1. In such case, the Replace function doesn’t truncate the string. Therefore, you generally don’t have to work with the Left function and concatenation operator. Please refer to the appropriate section (Replace String in Cell) above for further information about this scenario.
- Item: Count:=NumberOfReplacements.
- VBA Construct: Count parameter of the Replace function.
- Description: The Count parameter of the Replace function specifies the number of substitutions you want to carry out. In other words, the number of times you want to replace StringToReplace with ReplacementString.
If you want VBA to replace all occurrences of StringToReplace after StartPosition with ReplacementString, omit the Count parameter. In such case, Count defaults to -1 and VBA carries out all possible substitutions. Please refer to the appropriate section (Replace All Occurrences of String in Cell) below for further information about this scenario.
Macro Example to Replace String in Cell Specifying a Starting Position for Search
The following macro replaces the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) one time (myNumberOfReplacements) within the string in cell A6 of the worksheet named “Excel VBA Replace” (myCell). The search for myStringToReplace begins in position 14 (myStartPosition) of the string in myCell.
Sub replaceStringInCellWithStartPosition() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for string replacement (string to replace, replacement string, start position for search of string to replace, and number of replacements) Dim myStringToReplace As String Dim myReplacementString As String Dim myStartPosition As Long Dim myNumberOfReplacements As Long 'identify cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A6") 'specify parameters for string replacement (string to replace, replacement string, start position for search of string to replace, and number of replacements) myStringToReplace = "replace" myReplacementString = "substitute" myStartPosition = 14 myNumberOfReplacements = 1 'return and concatenate the following strings, and assign the resulting (concatenated) string to Range.Value property of cell you work with '(i) string containing the first characters within the cell you work with (from first position up to the character before the start position for search of string to replace) '(ii) string resulting from working with the Replace function and the parameter for string replacement you specify myCell.Value = Left(String:=myCell.Value, Length:=myStartPosition - 1) & Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString, Start:=myStartPosition, Count:=myNumberOfReplacements) End Sub
Effects of Executing Macro Example to Replace String in Cell Specifying a Starting Position for Search
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “replace” with the string “substitute” one time within the string in cell A6. The search for myStringToReplace begins in position 14 of the string in cell A6. This matches with the second occurrence of the “replace” string.
#3: Replace All Occurrences of String in Cell
VBA Code to Replace All Occurrences of String in Cell
To replace all occurrences of a string in a cell with VBA, use a statement with the following structure:
Cell.Value = Replace(Expression:=Cell.Value, Find:=StringToReplace, Replace:=ReplacementString)
Process Followed by VBA Code to Replace All Occurrences of String in Cell
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
- Item: Replace(…).
- VBA Construct: Replace function.
- Description: The Replace function returns a string where a specific substring (StringToReplace) is replaced by another substring (ReplacementString). Within this macro structure, Replace carries out all possible substitutions.
- Item: Expression:=Cell.Value.
- VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
- Description: The Expression parameter of the Replace function specifies the string expression containing the substring you want to replace (StringToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
- Item: Find:=StringToReplace.
- VBA Construct: Find parameter of the Replace function.
- Description: The Find parameter of the Replace function specifies the substring you search for and replace.
If you explicitly declare a variable to represent StringToReplace, use the String data type.
- Item: Replace:=ReplacementString.
- VBA Construct: Replace parameter of the Replace function.
- Description: The Replace parameter of the Replace function specifies the substring you want to use as replacement for StringToReplace.
If you explicitly declare a variable to represent ReplacementString, use the String data type.
Macro Example to Replace All Occurrences of String in Cell
The following macro replaces all occurrences of the string “replace” (myStringToReplace) with the string “substitute” (myReplacementString) within the string in cell A7 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceAll() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for string replacement (string to replace and replacement string) Dim myStringToReplace As String Dim myReplacementString As String 'identify cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A7") 'specify parameters for string replacement (string to replace and replacement string) myStringToReplace = "replace" myReplacementString = "substitute" 'replace all occurrences within string in cell you work with, and assign resulting string to Range.Value property of cell you work with myCell.Value = Replace(Expression:=myCell.Value, Find:=myStringToReplace, Replace:=myReplacementString) End Sub
Effects of Executing Macro Example to Replace All Occurrences of String in Cell
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all (2) occurrences of the string “replace” with the string “substitute” within the string in cell A7.
#4: Replace Character in String
VBA Code to Replace Character in String
To replace a character in a string within a cell with VBA, use a statement with the following structure:
Cell.Value = Replace(Expression:=Cell.Value, Find:=CharacterToReplace, Replace:=ReplacementCharacter)
Process Followed by VBA Code to Replace Character in String
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
- Item: Replace(…).
- VBA Construct: Replace function.
- Description: The Replace function returns a string where a specific character (CharacterToReplace) is replaced by another character (ReplacementCharacter). Within this macro structure, Replace carries out all possible substitutions.
- Item: Expression:=Cell.Value.
- VBA Construct: Expression parameter of the Replace function, Range object and Range.Value property.
- Description: The Expression parameter of the Replace function specifies the string expression containing the character you want to replace (CharacterToReplace). Within this macro structure, Expression is the value (string) within Cell, as returned by the Range.Value property.
- Item: Find:=CharacterToReplace.
- VBA Construct: Find parameter of the Replace function.
- Description: The Find parameter of the Replace function specifies the character you search for and replace.
If you explicitly declare a variable to represent CharacterToReplace, use the String data type.
- Item: Replace:=ReplacementCharacter.
- VBA Construct: Replace parameter of the Replace function.
- Description: The Replace parameter of the Replace function specifies the character you want to use as replacement for CharacterToReplace.
If you explicitly declare a variable to represent ReplacementCharacter, use the String data type.
Macro Example to Replace Character in String
The following macro replaces all occurrences of the character “a” (myCharacterToReplace) with the character “e” (myReplacementCharacter) within the string in cell A8 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceCharacterInString() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for character replacement (character to replace and replacement character) Dim myCharacterToReplace As String Dim myReplacementCharacter As String 'identify cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A8") 'specify parameters for string replacement (character to replace and replacement character) myCharacterToReplace = "a" myReplacementCharacter = "e" 'replace all occurrences of character within string in cell you work with, and assign resulting string to Range.Value property of cell you work with myCell.Value = Replace(Expression:=myCell.Value, Find:=myCharacterToReplace, Replace:=myReplacementCharacter) End Sub
Effects of Executing Macro Example to Replace Character in String
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all occurrences of the character “a” with the character “e” within the string in cell A8.
#5: Replace Multiple Characters in String
VBA Code to Replace Multiple Characters in String
To replace multiple characters in a string with VBA, use a macro with the following statement structure:
Dim StringReplace As String StringReplace = Cell.Value For Each Character In Array(CharactersList) StringReplace = Replace(Expression:=StringReplace, Find:=Character, Replace:=ReplacementCharacter) Next Character Cell.Value = StringReplace
Process Followed by VBA Code to Replace Multiple Characters in String
VBA Statement Explanation
Line #1: Dim StringReplace As String
- Item: Dim StringReplace As String.
- VBA Construct: Dim statement.
- Description: The Dim statement declares the StringReplace variable as of the String data type.
StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
Line #2: StringReplace = Cell.Value
- Item: StringReplace.
- VBA Construct: Variable of the string data type.
- Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Range.Value property to the StringReplace variable.
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property returns the value (in this case string) within Cell.
Lines #3 and #5: For Each Character In Array(CharactersList) | Next Character
- Item: For Each… In… Next.
- VBA Construct: For Each… Next statement.
- Description: The For Each… Next statement repeats the statement within the loop (line #4) for each element (Character) in the array returned by the Array function (Array(CharactersList)).
- Item: Character.
- VBA Construct: Element of For Each… Next statement and variable of the Variant data type.
- Description: The Element of the For Each… Next statement is a variable used to iterate through the elements of the array returned by the Array function (Array(CharactersList)).
If you explicitly declare a variable to represent Character, use the Variant data type.
- Item: Array(CharactersList).
- VBA Construct: Array function.
- Description: The Array function returns a Variant containing an array. CharactersList is the comma-delimited list of characters (passed as strings) that you assign to each of the array elements
Line #4: StringReplace = Replace(Expression:=StringReplace, Find:=Character, Replace:=ReplacementCharacter)
- Item: StringReplace.
- VBA Construct: Variable of the String data type.
- Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to StringReplace.
- Item: Replace(…).
- VBA Construct: Replace function.
- Description: The Replace function returns a string (starting with StringReplace) where a specific character (Character) is replaced by another character (ReplacementCharacter). Within this macro structure, Replace carries out all possible substitutions.
- Item: Expression:=StringReplace.
- VBA Construct: Expression parameter of the Replace function and variable of the String data type.
- Description: The Expression parameter of the Replace function specifies the string expression (StringReplace) containing the characters you want to replace (CharactersList).
- Item: Find:=Character.
- VBA Construct: Find parameter of the Replace function and variable of the Variant data type.
- Description: The Find parameter of the Replace function specifies the character you search for and replace.
Within this macro structure, Character is also the Element of the For Each… Next statement. This is the variable used to iterate through the elements of the array returned by the Array function (Array(CharactersList)).
If you explicitly declare a variable to represent Character, use the Variant data type.
- Item: Replace:=ReplacementCharacter.
- VBA Construct: Replace parameter of the Replace function.
- Description: The Replace parameter of the Replace function specifies the character you want to use as replacement for the characters you want to replace (CharactersList).
If you explicitly declare a variable to represent ReplacementCharacter, use the String data type.
Line #6: Cell.Value = StringReplace
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string represented by the StringReplace variable to the Range.Value property of Cell.
- Item: StringReplace.
- VBA Construct: Variable of the String data type.
- Description: StringReplace represents the string you work with. StringReplace is both (i) the string where you replace multiple characters (prior to working with the Replace function and the For Each… Next statement) and (ii) the new string after multiple characters have been replaced (after working with the Replace function and the For Each… Next statement).
Macro Example to Replace Multiple Characters in String
The following macro replaces all occurrences of the characters “a”, “e” and “i” (myCharactersArray) with the character “o” (myReplacementCharacter) within the string in cell A9 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceMultipleCharactersInString() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold string you work with and replacement character Dim myString As String Dim myReplacementCharacter As String 'declare variable to hold Variant containing array whose elements are characters to replace, and variable used to iterate through the elements of the array Dim myCharactersArray() As Variant Dim iCharacter As Variant 'identify the cell you work with and the string within that cell Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A9") myString = myCell.Value 'specify elements of array (characters to replace) and replacement character myCharactersArray = Array("a", "e", "i") myReplacementCharacter = "o" 'loop through each element (iCharacter) of the array (myCharacterArray) For Each iCharacter In myCharactersArray 'replace all occurrences of element (iCharacter) within current version of string you work with (myString), and assign resulting string to myString variable myString = Replace(Expression:=myString, Find:=iCharacter, Replace:=myReplacementCharacter) Next iCharacter 'assign string represented by myString variable to Range.Value property of cell you work with myCell.Value = myString End Sub
Effects of Executing Macro Example to Replace Multiple Characters in String
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces all occurrences of the characters “a”, “e” and “i” with the character “o” within the string in cell A9.
#6: Replace Wildcard
VBA Code to Replace Wildcard
To replace characters in a string within a cell using a wildcard with VBA, use a statement with the following structure:
Cell.Replace What:=StringToReplace, Replacement:=ReplacementString, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Process Followed by VBA Code to Replace Wildcard
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Replace.
- VBA Construct: Range.Replace method.
- Description: The Range.Replace method replaces a specific substring (StringToReplace) by another substring (ReplacementString) within Cell.
- Item: What:=StringToReplace.
- VBA Construct: What parameter of the Range.Replace method.
- Description: The What parameter of the Range.Replace method specifies the string you want to replace (StringToReplace).
When specifying StringToReplace, use the following wildcards as required:
- Question mark (?): The question mark represents any single character. For example, “w?ldcard” represents a string (i) starting with a “w”, (ii) followed by any single character (including “i”), and (iii) ending with “lcard”.
- Asterisk (*): The asterisk represents any group of characters. For example, “w*card” represents a string (i) starting with a “w”, (ii) followed by any group of characters (including “ild”), and (iii) ending with “card”.
If you explicitly declare a variable to represent StringToReplace, use the String data type.
- Item: Replacement:=ReplacementString.
- VBA Construct: Replacement parameter of the Range.Replace method.
- Description: The Replacement parameter of the Range.Replace method specifies the substring you want to use as replacement for StringToReplace.
- Item: LookAt:=xlPart.
- VBA Construct: LookAt parameter of the Range.Replace method.
- Description: The LookAt parameter of the Range.Replace method specifies that Range.Replace looks at (and matches) a part (xlPart) of the search data.
- Item: SearchOrder:=xlByRows.
- VBA Construct: SearchOrder parameter of the Range.Replace method.
- Description: The SearchOrder parameter of the Range.Replace method specifies that Range.Replace searches by rows (xlByRows).
- Item: MatchCase:=False.
- VBA Construct: MatchCase parameter of the Range.Replace method.
- Description: The MatchCase parameter of the Range.Replace method specifies that the search isn’t case sensitive (False).
- Item: SearchFormat:=False.
- VBA Construct: SearchFormat parameter of the Range.Replace method.
- Description: The SearchFormat parameter of the Range.Replace method specifies that the search doesn’t consider formatting (False).
- Item: ReplaceFormat:=False.
- VBA Construct: ReplaceFormat parameter of the Range.Replace method.
- Description: The ReplaceFormat parameter of the Range.Replace method specifies that no replace format is set (False).
Macro Example to Replace Wildcard
The following macro replaces the string (i) starting with a “w”, (ii) followed by any group of characters (including “ild”), and (iii) ending with “card” (myStringToReplace), with the string “question mark” (myReplacementString) within the string in cell A10 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceWildcard() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for string replacement (string to replace and replacement string) Dim myStringToReplace As String Dim myReplacementString As String 'identify the cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A10") 'specify parameters for string replacement (string to replace and replacement string). Use wildcards (? or *) to specify string to replace myStringToReplace = "w*card" myReplacementString = "question mark" 'replace all occurrences within string in cell you work with, and assign resulting string to Range.Value property of cell you work with myCell.Replace What:=myStringToReplace, Replacement:=myReplacementString, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub
Effects of Executing Macro Example to Replace Wildcard
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string “wildcard” which (i) starts with a “w”, (ii) followed by a group of characters (“ild”), and (iii) ends with “card”, with the string “question mark” within the string in cell A10.
#7: Replace Character in String by Position
VBA Code to Replace Character in String by Position
To replace a character in a string within a cell according to its position with VBA, use a statement with the following structure:
Cell.Value = WorksheetFunction.Replace(Cell.Value, CharacterPosition, CharactersToReplace, ReplacementString)
Process Followed by VBA Code to Replace Character in String by Position
VBA Statement Explanation
- Item: Cell.
- VBA Construct: Range object.
- Description: Range object representing the cell you work with.
You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with the Range.Item) or Range.Offset properties.
- Item: Value.
- VBA Construct: Range.Value property.
- Description: The Range.Value property specifies the value (in this case string) within Cell.
- Item: =.
- VBA Construct: Assignment operator.
- Description: The = operator assigns the string returned by the Replace function to the Range.Value property of Cell.
- Item: WorksheetFunction.Replace(…).
- VBA Construct: WorksheetFunction.Replace method.
- Description: The WorksheetFunction.Replace method replaces a substring with a different string (ReplacementString). The replaced substring is determined based on its position within the string you work with (CharacterPosition) and the number of characters to replace (CharactersToReplace).
- Item: Cell.Value.
- VBA Construct: Arg1 parameter of the WorksheetFunction.Replace method, Range object and Range.Value property.
- Description: The Arg1 parameter of the WorksheetFunction.Replace method specifies the string containing the substring you want to replace. Within this macro structure, Arg1 is the value (string) within Cell, as returned by the Range.Value property.
If you explicitly declare a variable to represent Arg1, use the String data type.
- Item: CharacterPosition.
- VBA Construct: Arg2 parameter of the WorksheetFunction.Replace method.
- Description: The Arg2 parameter of the WorksheetFunction.Replace method specifies the starting position within Arg1 (Cell.Value) of the substring you want to replace with Arg4 (ReplacementString).
If you explicitly declare a variable to represent Arg2 (CharacterPosition), use the Double data type.
- Item: CharactersToReplace.
- VBA Construct: Arg3 parameter of the WorksheetFunction.Replace method.
- Description: The Arg3 parameter of the WorksheetFunction.Replace method specifies the number of characters within Arg1 (Cell.Value) you want to replace with Arg4 (ReplacementString).
If you explicitly declare a variable to represent Arg3 (CharactersToReplace), use the Double data type.
- Item: ReplacementString.
- VBA Construct: Arg4 parameter of the WorksheetFunction.Replace method.
- Description: The Arg4 parameter of the WorksheetFunction.Replace method specifies the substring you want to use as replacement.
If you explicitly declare a variable to represent Arg4 (ReplacementString), use the String data type.
Macro Example to Replace Character in String by Position
The following macro replaces the string starting in position 10 (myCharacterPosition) with a length of 1 character (myCharactersToReplace) with the string “+” (myReplacementString) within the string in cell A11 of the worksheet named “Excel VBA Replace” (myCell).
Sub replaceCharacterByPosition() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-replace-substitute/ 'declare object variable to hold reference to cell you work with Dim myCell As Range 'declare variables to hold parameters for string replacement (starting position of string to replace, number of characters to replace, and replacement string) Dim myCharacterPosition As Double Dim myCharactersToReplace As Double Dim myReplacementString As String 'identify the cell you work with Set myCell = ThisWorkbook.Worksheets("Excel VBA Replace").Range("A11") 'specify parameters for string replacement (starting position of string to replace, number of characters to replace, and replacement string) myCharacterPosition = 10 myCharactersToReplace = 1 myReplacementString = "+" 'replace string in cell you work with, and assign resulting string to Range.Value property of cell you work with myCell.Value = WorksheetFunction.Replace(myCell.Value, myCharacterPosition, myCharactersToReplace, myReplacementString) End Sub
Effects of Executing Macro Example to Replace Character in String by Position
The following GIF illustrates the results of executing this macro example. As expected, the macro replaces the string starting in position 10 with a length of 1 character with the string “+” within the string in cell A11.
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage in the Microsoft Developer Network:
- Identify the workbook and worksheet you work with:
- Workbook object.
- Application.ThisWorkbook property.
- Worksheet object.
- Workbook.Worksheets property.
- Identify the cell you work with:
- Range object.
- Worksheet.Range property.
- Worksheet.Cells property.
- Range.Item property.
- Range.Offset property.
- Obtain or set the string within the cell you work with:
- Range.Value property.
- Assign a new string to the cell you work with or to the variable representing the string you work with:
- = operator.
- Replace characters or strings:
- Replace function.
- Range.Replace method.
- WorksheetFunction.Replace method.
- Complete and concatenate truncated strings:
- Left function.
- & operator.
- Create an array containing characters and loop through its elements:
- For Each… Next statement.
- Array function.
- Work with variables and data types:
- Dim statement.
- Set statement.
- Data types:
- Double data type.
- Long data type.
- String data type.
- Variant data type.
Find & Replace Function in VBA
If your Excel job involves routine tasks finding and replacing something with something, then you need this article at any cost. Because after reading this article, you would probably save 80% of your time by learning this VBA coding technique. Find and Replace in ExcelFind and Replace is an Excel feature that allows you to search for any text, numerical symbol, or special character not just in the current sheet but in the entire workbook. Ctrl+F is the shortcut for find, and Ctrl+H is the shortcut for find and replace.read more is an often used tool. We can implement the same with VBA as well. Our earlier article, “VBA Find,” shows you how to use the FIND method in VBA. This article will show you how to use the VBA “Find & Replace” method.
Table of contents
- Find & Replace Function in VBA
- VBA Find and Replace Syntax
- Examples of VBA Find and Replace in Excel
- Example #1 – VBA Find and Replace the Word
- Example #2 – Case Sensitive Replacement
- Recommended Articles
Follow the article to learn this technique.
VBA Find and Replace Syntax
We must follow the steps below to use the Find and Replace method in VBA. First, we have selected the range of cells, so mention the range of cells using RANGE object in VBARange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.
Now put a dot (.) to see the IntelliSense list.
Select the Replace method from the list.
We can see the huge parameter list of the Replace method. Now, we will see each parameter explanation below.
- What: This is nothing but what we need to find to replace the value.
- Replacement: With the found value, what should be the new value to be replaced with?
- Look At: This is to mention whether we want to look at the full content or just the part of the content. We can supply two parameters here “xlWhole” & “xlPart.”
- Search Order: This mentions the search order, either rows or columns. We can supply two parameters here “xlByRows” & “xlByColumns.”
- Match Case: The content we are searching for is case-sensitive. Suppose the case-sensitive argument is TRUE or else FALSE.
- Search Format: We can also search the content by formatting the value we are looking for.
- Replace Format: We can replace one format with another format as well.
Examples of VBA Find and Replace in Excel
Below are some examples of the Excel VBA Find and Replace method.
You can download this VBA Find and Replace Excel Template here – VBA Find and Replace Excel Template
Example #1 – VBA Find and Replace the Word
Let us look at the following example to understand the VBA Find and Replace method. First, take a look at the following data.
Step 1: First, mention the Range of cells we are replacing. In this example, the range is from A1 to B15 so the code will be Range (“A1: B15”).
Code:
Sub Replace_Example1() Range ("A1:B15") End Sub
Step 2: Now, put a dot to see the IntelliSense list.
Step 3: Select the Replace method from the IntelliSense list.
Step 4: Mention what parameter as “September.”
Code:
Range("A1:B15").Replace What:="September"
Step 5: Next, Replace with parameter should be the new value we are replacing with, i.e., “December.”
Code:
Range("A1:D4").Replace What:="September", Replacement:="December"
As of now, ignore all the other parameters. Now, run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more to see the replacement method with VBA.
So, it has replaced all of September with the word “December.”
Example #2 – Case Sensitive Replacement
The more advanced example of the VBA Find & Replace method will be using case sensitive replacement methods. We have created this sample data for this example, as shown in the image below.
We have two cell data in capital letters, “HELLO.” Wherever we have a capital “HELLO,” it should be replaced by the new word “Hiii.”
As usual, write the code, and mention what to find and replace first.
Code:
Sub Replace_Example2() Range("A1:D4").Replace What:="HELLO", Replacement:="Hiii" End Sub
For the next argument, “Match Case,” write the condition as TRUE.
Code:
Range("A1:D4").Replace What:="HELLO", Replacement:="Hiii", MatchCase:=True
Now, run the code. It will replace only the capital “HELLO” with “Hiii.”
Imagine you have not applied the Match Case argument in VBAIn VBA, the match function is used as a lookup function and is accessed by the application. worksheet method. The arguments for the Match function are similar to the worksheet function.read more, then it will replace all the “Hello” with “Hiii.”
Note: I have removed the Match Case argument here. By default, the MATCH CASE argument value is FALSE.
As we can see in the above image, it has replaced all the “hello” words with “hiii.”
So, whenever we want to use MATCH CASE criteria, we should apply the argument as “TRUE.” By default, this argument value is “FALSE.” Like this, we can use the “FIND & REPLACE” method to find something and replace the found value with something else.
Recommended Articles
This article has been a guide to the VBA Find and Replace Method. Here we will learn how to find and replace the word in VBA Excel with examples and downloadable Excel sheets. You may also have a look at other articles related to Excel VBA: –
- VBA Charts
- What does StrConv do in Excel VBA?
- End Property in VBA
- ROUND Function in VBA
Quick Guide to String Functions
String operations | Function(s) |
---|---|
Append two or more strings | Format or «&» |
Build a string from an array | Join |
Compare — normal | StrComp or «=» |
Compare — pattern | Like |
Convert to a string | CStr, Str |
Convert string to date | Simple: CDate Advanced: Format |
Convert string to number | Simple: CLng, CInt, CDbl, Val Advanced: Format |
Convert to unicode, wide, narrow | StrConv |
Convert to upper/lower case | StrConv, UCase, LCase |
Extract part of a string | Left, Right, Mid |
Format a string | Format |
Find characters in a string | InStr, InStrRev |
Generate a string | String |
Get length of a string | Len |
Remove blanks | LTrim, RTrim, Trim |
Replace part of a string | Replace |
Reverse a string | StrReverse |
Parse string to array | Split |
The Webinar
If you are a member of the website, click on the image below to view the webinar for this post.
(Note: Website members have access to the full webinar archive.)
Introduction
Using strings is a very important part of VBA. There are many types of manipulation you may wish to do with strings. These include tasks such as
- extracting part of a string
- comparing strings
- converting numbers to a string
- formatting a date to include weekday
- finding a character in a string
- removing blanks
- parsing to an array
- and so on
The good news is that VBA contains plenty of functions to help you perform these tasks with ease.
This post provides an in-depth guide to using string in VBA. It explains strings in simple terms with clear code examples. I have laid it out so the post can be easily used as a quick reference guide.
If you are going to use strings a lot then I recommend you read the first section as it applies to a lot of the functions. Otherwise you can read in order or just go to the section you require.
Read This First!
The following two points are very important when dealing with VBA string functions.
The Original String is not Changed
An important point to remember is that the VBA string functions do not change the original string. They return a new string with the changes the function made. If you want to change the original string you simply assign the result to the original string. See the section Extracting Part of a String for examples of this.
How To Use Compare
Some of the string functions such as StrComp() and Instr() etc. have an optional Compare parameter. This works as follows:
vbTextCompare: Upper and lower case are considered the same
vbBinaryCompare: Upper and lower case are considered different
The following code uses the string comparison function StrComp() to demonstrate the Compare parameter
' https://excelmacromastery.com/ Sub Comp1() ' Prints 0 : Strings match Debug.Print StrComp("ABC", "abc", vbTextCompare) ' Prints -1 : Strings do not match Debug.Print StrComp("ABC", "abc", vbBinaryCompare) End Sub
You can use the Option Compare setting instead of having to use this parameter each time. Option Compare is set at the top of a Module. Any function that uses the Compare parameter will take this setting as the default. The two ways to use Option Compare are:
1. Option Compare Text: makes vbTextCompare the default Compare argument
' https://excelmacromastery.com/ Option Compare Text Sub Comp2() ' Strings match - uses vbCompareText as Compare argument Debug.Print StrComp("ABC", "abc") Debug.Print StrComp("DEF", "def") End Sub
2. Option Compare Binary: Makes vbBinaryCompare the default Compare argument
' https://excelmacromastery.com/ Option Compare Binary Sub Comp2() ' Strings do not match - uses vbCompareBinary as Compare argument Debug.Print StrComp("ABC", "abc") Debug.Print StrComp("DEF", "def") End Sub
If Option Compare is not used then the default is Option Compare Binary.
Now that you understand these two important points about string we can go ahead and look at the string functions individually.
Go back to menu
Appending Strings
ABC Cube Pile © Aleksandr Atkishkin | Dreamstime.com
You can append strings using the & operator. The following code shows some examples of using it
' https://excelmacromastery.com/ Sub Append() Debug.Print "ABC" & "DEF" Debug.Print "Jane" & " " & "Smith" Debug.Print "Long " & 22 Debug.Print "Double " & 14.99 Debug.Print "Date " & #12/12/2015# End Sub
You can see in the example that different types such as dates and number are automatically converted to strings. You may see the + operator being used to append strings. The difference is that this operator will only work with string types. If you try to use it with other type you will get an error.
' This will give the error message: "Type Mismatch" Debug.Print "Long " + 22
If you want to do more complex appending of strings then you may wish to use the Format function described below.
Go back to menu
Extracting Part of a String
The functions discussed in this section are useful when dealing with basic extracting from a string. For anything more complicated you might want to check out my post on How to Easily Extract From Any String Without Using VBA InStr.
Function | Parameters | Description | Example |
---|---|---|---|
Left | string, length | Return chars from left side | Left(«John Smith»,4) |
Right | string, length | Return chars from right side | Right(«John Smith»,5) |
Mid | string, start, length | Return chars from middle | Mid(«John Smith»,3,2) |
The Left, Right, and Mid functions are used to extract parts of a string. They are very simple functions to use. Left reads characters from the left, Right from the right and Mid from a starting point that you specify.
' https://excelmacromastery.com/ Sub UseLeftRightMid() Dim sCustomer As String sCustomer = "John Thomas Smith" Debug.Print Left(sCustomer, 4) ' Prints: John Debug.Print Right(sCustomer, 5) ' Prints: Smith Debug.Print Left(sCustomer, 11) ' Prints: John Thomas Debug.Print Right(sCustomer, 12) ' Prints: Thomas Smith Debug.Print Mid(sCustomer, 1, 4) ' Prints: John Debug.Print Mid(sCustomer, 6, 6) ' Prints: Thomas Debug.Print Mid(sCustomer, 13, 5) ' Prints: Smith End Sub
As mentioned in the previous section, VBA string functions do not change the original string. Instead, they return the result as a new string.
In the next example you can see that the string Fullname was not changed after using the Left function
' https://excelmacromastery.com/ Sub UsingLeftExample() Dim Fullname As String Fullname = "John Smith" Debug.Print "Firstname is: "; Left(Fullname, 4) ' Original string has not changed Debug.Print "Fullname is: "; Fullname End Sub
If you want to change the original string you simply assign it to the return value of the function
' https://excelmacromastery.com/ Sub ChangingString() Dim name As String name = "John Smith" ' Assign return string to the name variable name = Left(name, 4) Debug.Print "Name is: "; name End Sub
Go back to menu
Searching Within a String
Function | Params | Description | Example |
---|---|---|---|
InStr | String1, String2 | Finds position of string | InStr(«John Smith»,»h») |
InStrRev | StringCheck, StringMatch | Finds position of string from end | InStrRev(«John Smith»,»h») |
InStr and InStrRev are VBA functions used to search through strings for a substring. If the search string is found then the position(from the start of the check string) of the search string is returned. If the search string is not found then zero is returned. If either string is null then null is returned.
InStr Description of Parameters
InStr() Start[Optional], String1, String2, Compare[Optional]
- Start As Long[Optional – Default is 1]: This is a number that specifies the starting search position from the left
- String1 As String: The string to search
- String2 As String: The string to search for
- Compare As vbCompareMethod : See the section on Compare above for more details
InStr Use and Examples
InStr returns the first position in a string where a given substring is found. The following shows some examples of using it
' https://excelmacromastery.com/ Sub FindSubString() Dim name As String name = "John Smith" ' Returns 3 - position of first h Debug.Print InStr(name, "h") ' Returns 10 - position of first h starting from position 4 Debug.Print InStr(4, name, "h") ' Returns 8 Debug.Print InStr(name, "it") ' Returns 6 Debug.Print InStr(name, "Smith") ' Returns 0 - string "SSS" not found Debug.Print InStr(name, "SSS") End Sub
InStrRev Description of Parameters
InStrRev() StringCheck, StringMatch, Start[Optional], Compare[Optional]
- StringCheck As String: The string to search
- StringMatch: The string to search for
- Start As Long[Optional – Default is -1]: This is a number that specifies the starting search position from the right
- Compare As vbCompareMethod: See the section on Compare above for more details
InStrRev Use and Examples
The InStrRev function is the same as InStr except that it searches from the end of the string. It’s important to note that the position returned is the position from the start. Therefore if there is only one instance of the search item then both InStr() and InStrRev() will return the same value.
The following code show some examples of using InStrRev
' https://excelmacromastery.com/ Sub UsingInstrRev() Dim name As String name = "John Smith" ' Both Return 1 - position of the only J Debug.Print InStr(name, "J") Debug.Print InStrRev(name, "J") ' Returns 10 - second h Debug.Print InStrRev(name, "h") ' Returns 3 - first h as searches from position 9 Debug.Print InStrRev(name, "h", 9) ' Returns 1 Debug.Print InStrRev(name, "John") End Sub
The InStr and InStrRev functions are useful when dealing with basic string searches. However, if you are going to use them for extracting text from a string they can make things complicated. I have written about a much better way to do this in my post How to Easily Extract From Any String Without Using VBA InStr.
Go back to menu
Removing Blanks
Function | Params | Description | Example |
---|---|---|---|
LTrim | string | Removes spaces from left | LTrim(» John «) |
RTrim | string | Removes spaces from right | RTrim(» John «) |
Trim | string | Removes Spaces from left and right | Trim(» John «) |
The Trim functions are simple functions that remove spaces from either the start or end of a string.
Trim Functions Use and Examples
- LTrim removes spaces from the left of a string
- RTrim removes spaces from the right of a string
- Trim removes spaces from the left and right of a string
' https://excelmacromastery.com/ Sub TrimStr() Dim name As String name = " John Smith " ' Prints "John Smith " Debug.Print LTrim(name) ' Prints " John Smith" Debug.Print RTrim(name) ' Prints "John Smith" Debug.Print Trim(name) End Sub
Go back to menu
Length of a String
Function | Params | Description | Example |
---|---|---|---|
Len | string | Returns length of string | Len («John Smith») |
Len is a simple function when used with a string. It simply returns the number of characters the string contains. If used with a numeric type such as long it will return the number of bytes.
' https://excelmacromastery.com/ Sub GetLen() Dim name As String name = "John Smith" ' Prints 10 Debug.Print Len("John Smith") ' Prints 3 Debug.Print Len("ABC") ' Prints 4 as Long is 4 bytes in size Dim total As Long Debug.Print Len(total) End Sub
Go back to menu
Reversing a String
Function | Params | Description | Example |
---|---|---|---|
StrReverse | string | Reverses a string | StrReverse («John Smith») |
StrReverse is another easy-to-use function. It simply returns the given string with the characters reversed.
' https://excelmacromastery.com/ Sub RevStr() Dim s As String s = "Jane Smith" ' Prints: htimS enaJ Debug.Print StrReverse(s) End Sub
Go back to menu
Comparing Strings
Function | Params | Description | Example |
---|---|---|---|
StrComp | string1, string2 | Compares 2 strings | StrComp («John», «John») |
The function StrComp is used to compare two strings. The following subsections describe how it is used.
Description of Parameters
StrComp() String1, String2, Compare[Optional]
- String1 As String: The first string to compare
- String2 As String: The second string to compare
- Compare As vbCompareMethod : See the section on Compare above for more details
StrComp Return Values
Return Value | Description |
---|---|
0 | Strings match |
-1 | string1 less than string2 |
1 | string1 greater than string2 |
Null | if either string is null |
Use and Examples
The following are some examples of using the StrComp function
' https://excelmacromastery.com/ Sub UsingStrComp() ' Returns 0 Debug.Print StrComp("ABC", "ABC", vbTextCompare) ' Returns 1 Debug.Print StrComp("ABCD", "ABC", vbTextCompare) ' Returns -1 Debug.Print StrComp("ABC", "ABCD", vbTextCompare) ' Returns Null Debug.Print StrComp(Null, "ABCD", vbTextCompare) End Sub
Compare Strings using Operators
You can also use the equals sign to compare strings. The difference between the equals comparison and the StrComp function are:
- The equals sign returns only true or false.
- You cannot specify a Compare parameter using the equal sign – it uses the “Option Compare” setting.
The following shows some examples of using equals to compare strings
' https://excelmacromastery.com/ Option Compare Text Sub CompareUsingEquals() ' Returns true Debug.Print "ABC" = "ABC" ' Returns true because "Compare Text" is set above Debug.Print "ABC" = "abc" ' Returns false Debug.Print "ABCD" = "ABC" ' Returns false Debug.Print "ABC" = "ABCD" ' Returns null Debug.Print Null = "ABCD" End Sub
The Operator “<>” means “does not equal”. It is essentially the opposite of using the equals sign as the following code shows
' https://excelmacromastery.com/ Option Compare Text Sub CompareWithNotEqual() ' Returns false Debug.Print "ABC" <> "ABC" ' Returns false because "Compare Text" is set above Debug.Print "ABC" <> "abc" ' Returns true Debug.Print "ABCD" <> "ABC" ' Returns true Debug.Print "ABC" <> "ABCD" ' Returns null Debug.Print Null <> "ABCD" End Sub
Go back to menu
Comparing Strings using Pattern Matching
Operator | Params | Description | Example |
---|---|---|---|
Like | string, string pattern | checks if string has the given pattern | «abX» Like «??X» «54abc5» Like «*abc#» |
Token | Meaning |
---|---|
? | Any single char |
# | Any single digit(0-9) |
* | zero or more characters |
[charlist] | Any char in the list |
[!charlist] | Any char not in the char list |
Pattern matching is used to determine if a string has a particular pattern of characters. For example, you may want to check that a customer number has 3 digits followed by 3 alphabetic characters or a string has the letters XX followed by any number of characters.
If the string matches the pattern then the return value is true, otherwise it is false.
Pattern matching is similar to the VBA Format function in that there are almost infinite ways to use it. In this section I am going to give some examples that will explain how it works. This should cover the most common uses. If you need more information about pattern matching you can refer to the MSDN Page for the Like operator.
Lets have a look at a basic example using the tokens. Take the following pattern string
[abc][!def]?#X*
Let’s look at how this string works
[abc] a character that is either a,b or c
[!def] a character that is not d,e or f
? any character
# any digit
X the character X
* followed by zero or more characters
Therefore the following string is valid
apY6X
a is one of abc
p is not one of the characters d, e or f
Y is any character
6 is a digit
X is the letter X
The following code examples show the results of various strings with this pattern
' https://excelmacromastery.com/ Sub Patterns() ' True Debug.Print 1; "apY6X" Like "[abc][!def]?#X*" ' True - any combination of chars after x is valid Debug.Print 2; "apY6Xsf34FAD" Like "[abc][!def]?#X*" ' False - char d not in [abc] Debug.Print 3; "dpY6X" Like "[abc][!def]?#X*" ' False - 2nd char e is in [def] Debug.Print 4; "aeY6X" Like "[abc][!def]?#X*" ' False - A at position 4 is not a digit Debug.Print 5; "apYAX" Like "[abc][!def]?#X*" ' False - char at position 5 must be X Debug.Print 6; "apY6Z" Like "[abc][!def]?#X*" End Sub
Real-World Example of Pattern Matching
To see a real-world example of using pattern matching check out Example 3: Check if a filename is valid.
Important Note on VBA Pattern Matching
The Like operator uses either Binary or Text comparison based on the Option Compare setting. Please see the section on Compare above for more details.
Go back to menu
Replace Part of a String
Function | Params | Description | Example |
---|---|---|---|
Replace | string, find, replace, start, count, compare |
Replaces a substring with a substring | Replace («Jon»,»n»,»hn») |
Replace is used to replace a substring in a string by another substring. It replaces all instances of the substring that are found by default.
Replace Description of Parameters
Replace() Expression, Find, Replace, Start[Optional], Count[Optional], Compare[Optional]
- Expression As String: The string to replace chars in
- Find As String: The substring to replace in the Expression string
- Replace As String: The string to replace the Find substring with
- Start As Long[Optional – Default is 1]: The start position in the string
- Count As Long[Optional – Default is -1]: The number of substitutions to make. The default -1 means all.
- Compare As vbCompareMethod : See the section on Compare above for more details
Use and Examples
The following code shows some examples of using the Replace function
' https://excelmacromastery.com/ Sub ReplaceExamples() ' Replaces all the question marks with(?) with semi colons(;) Debug.Print Replace("A?B?C?D?E", "?", ";") ' Replace Smith with Jones Debug.Print Replace("Peter Smith,Ann Smith", "Smith", "Jones") ' Replace AX with AB Debug.Print Replace("ACD AXC BAX", "AX", "AB") End Sub
Output
A;B;C;D;E
Peter Jones,Sophia Jones
ACD ABC BAB
In the following examples we use the Count optional parameter. Count determines the number of substitutions to make. So for example, setting Count equal to one means that only the first occurrence will be replaced.
' https://excelmacromastery.com/ Sub ReplaceCount() ' Replaces first question mark only Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=1) ' Replaces first three question marks Debug.Print Replace("A?B?C?D?E", "?", ";", Count:=3) End Sub
Output
A;B?C?D?E
A;B;C;D?E
The Start optional parameter allow you to return part of a string. The position you specify using Start is where it starts returning the string from. It will not return any part of the string before this position whether a replace was made or not.
' https://excelmacromastery.com/ Sub ReplacePartial() ' Use original string from position 4 Debug.Print Replace("A?B?C?D?E", "?", ";", Start:=4) ' Use original string from position 8 Debug.Print Replace("AA?B?C?D?E", "?", ";", Start:=8) ' No item replaced but still only returns last 2 characters Debug.Print Replace("ABCD", "X", "Y", Start:=3) End Sub
Output
;C;D;E
;E
CD
Sometimes you may only want to replace only upper or lower case letters. You can use the Compare parameter to do this. This is used in a lot of string functions. For more information on this check out the Compare section above.
' https://excelmacromastery.com/ Sub ReplaceCase() ' Replace capital A's only Debug.Print Replace("AaAa", "A", "X", Compare:=vbBinaryCompare) ' Replace All A's Debug.Print Replace("AaAa", "A", "X", Compare:=vbTextCompare) End Sub
Output
XaXa
XXXX
Multiple Replaces
If you want to replace multiple values in a string you can nest the calls. In the following code we want to replace X and Y with A and B respectively.
' https://excelmacromastery.com/ Sub ReplaceMulti() Dim newString As String ' Replace A with X newString = Replace("ABCD ABDN", "A", "X") ' Now replace B with Y in new string newString = Replace(newString, "B", "Y") Debug.Print newString End Sub
In the next example we will change the above code to perform the same task. We will use the return value of the first replace as the argument for the second replace.
' https://excelmacromastery.com/ Sub ReplaceMultiNested() Dim newString As String ' Replace A with X and B with Y newString = Replace(Replace("ABCD ABDN", "A", "X"), "B", "Y") Debug.Print newString End Sub
The result of both of these Subs is
XYCD XYDN
Go back to menu
Convert Types to String(Basic)
This section is about converting numbers to a string. A very important point here is that most the time VBA will automatically convert to a string for you. Let’s look at some examples
' https://excelmacromastery.com/ Sub AutoConverts() Dim s As String ' Automatically converts number to string s = 12.99 Debug.Print s ' Automatically converts multiple numbers to string s = "ABC" & 6 & 12.99 Debug.Print s ' Automatically converts double variable to string Dim d As Double, l As Long d = 19.99 l = 55 s = "Values are " & d & " " & l Debug.Print s End Sub
When you run the above code you can see that the number were automatically converted to strings. So when you assign a value to a string VBA will look after the conversion for you most of the time. There are conversion functions in VBA and in the following sub sections we will look at the reasons for using them.
Explicit Conversion
Function | Params | Description | Example |
---|---|---|---|
CStr | expression | Converts a number variable to a string | CStr («45.78») |
Str | number | Converts a number variable to a string | Str («45.78») |
In certain cases you may want to convert an item to a string without have to place it in a string variable first. In this case you can use the Str or CStr functions. Both take an expression as a function and this can be any type such as long, double, data or boolean.
Let’s look at a simple example. Imagine you are reading a list of values from different types of cells to a collection. You can use the Str/CStr functions to ensure they are all stored as strings. The following code shows an example of this
' https://excelmacromastery.com/ Sub UseStr() Dim coll As New Collection Dim c As Range ' Read cell values to collection For Each c In Range("A1:A10") ' Use Str to convert cell value to a string coll.Add Str(c) Next ' Print out the collection values and type Dim i As Variant For Each i In coll Debug.Print i, TypeName(i) Next End Sub
In the above example we use Str to convert the value of the cell to a string. The alternative to this would be to assign the value to a string and then assigning the string to the collection. So you can see that using Str here is much more efficient.
Multi Region
The difference between the Str and CStr functions is that CStr converts based on the region. If your macros will be used in multiple regions then you will need to use CStr for your string conversions.
It is good to practise to use CStr when reading values from cells. If your code ends up being used in another region then you will not have to make any changes to make it work correctly.
Go back to menu
Convert String to Number- CLng, CDbl, Val etc.
Function | Returns | Example |
---|---|---|
CBool | Boolean | CBool(«True»), CBool(«0») |
CCur | Currency | CCur(«245.567») |
CDate | Date | CDate(«1/1/2017») |
CDbl | Double | CCur(«245.567») |
CDec | Decimal | CDec(«245.567») |
CInt | Integer | CInt(«45») |
CLng | Long Integer | CLng(«45.78») |
CVar | Variant | CVar(«») |
The above functions are used to convert strings to various types. If you are assigning to a variable of this type then VBA will do the conversion automatically.
' https://excelmacromastery.com/ Sub StrToNumeric() Dim l As Long, d As Double, c As Currency Dim s As String s = "45.923239" l = s d = s c = s Debug.Print "Long is "; l Debug.Print "Double is "; d Debug.Print "Currency is "; c End Sub
Using the conversion types gives more flexibility. It means you can determine the type at runtime. In the following code we set the type based on the sType argument passed to the PrintValue function. As this type can be read from an external source such as a cell, we can set the type at runtime. If we declare a variable as Long then it will always be long when the code runs.
' https://excelmacromastery.com/ Sub Test() ' Prints 46 PrintValue "45.56", "Long" ' Print 45.56 PrintValue "45.56", "" End Sub Sub PrintValue(ByVal s As String, ByVal sType As String) Dim value ' Set the data type based on a type string If sType = "Long" Then value = CLng(s) Else value = CDbl(s) End If Debug.Print "Type is "; TypeName(value); value End Sub
If a string is not a valid number(i.e. contains symbols other numeric) then you get a “Type Mismatch” error.
' https://excelmacromastery.com/ Sub InvalidNumber() Dim l As Long ' Will give type mismatch error l = CLng("45A") End Sub
The Val Function
The value function convert numeric parts of a string to the correct number type.
The Val function converts the first numbers it meets. Once it meets letters in a string it stops. If there are only letters then it returns zero as the value. The following code shows some examples of using Val
' https://excelmacromastery.com/ Sub UseVal() ' Prints 45 Debug.Print Val("45 New Street") ' Prints 45 Debug.Print Val(" 45 New Street") ' Prints 0 Debug.Print Val("New Street 45") ' Prints 12 Debug.Print Val("12 f 34") End Sub
The Val function has two disadvantages
1. Not Multi-Region – Val does not recognise international versions of numbers such as using commas instead of decimals. Therefore you should use the above conversion functions when you application will be used in multiple regions.
2. Converts invalid strings to zero – This may be okay in some instances but in most cases it is better if an invalid string raises an error. The application is then aware there is a problem and can act accordingly. The conversion functions such as CLng will raise an error if the string contains non-numeric characters.
Go back to menu
Generate a String of items – String Function
Function | Params | Description | Example |
---|---|---|---|
String | number, character | Converts a number variable to a string | String (5,»*») |
The String function is used to generate a string of repeated characters. The first argument is the number of times to repeat it, the second argument is the character.
' https://excelmacromastery.com/ Sub GenString() ' Prints: AAAAA Debug.Print String(5, "A") ' Prints: >>>>> Debug.Print String(5, 62) ' Prints: (((ABC))) Debug.Print String(3, "(") & "ABC" & String(3, ")") End Sub
Go back to menu
Convert Case/Unicode – StrConv, UCase, LCase
Function | Params | Description | Example |
---|---|---|---|
StrConv | string, conversion, LCID | Converts a String | StrConv(«abc»,vbUpperCase) |
If you want to convert the case of a string to upper or lower you can use the UCase and LCase functions for upper and lower respectively. You can also use the StrConv function with the vbUpperCase or vbLowerCase argument. The following code shows example of using these three functions
' https://excelmacromastery.com/ Sub ConvCase() Dim s As String s = "Mary had a little lamb" ' Upper Debug.Print UCase(s) Debug.Print StrConv(s, vbUpperCase) ' Lower Debug.Print LCase(s) Debug.Print StrConv(s, vbLowerCase) ' Sets the first letter of each word to upper case Debug.Print StrConv(s, vbProperCase) End Sub
Output
MARY HAD A LITTLE LAMB
MARY HAD A LITTLE LAMB
mary had a little lamb
mary had a little lamb
Mary Had A Little Lamb
Other Conversions
As well as case the StrConv can perform other conversions based on the Conversion parameter. The following table shows a list of the different parameter values and what they do. For more information on StrConv check out the MSDN Page.
Constant | Value | Converts |
---|---|---|
vbUpperCase | 1 | to upper case |
vbLowerCase | 2 | to lower case |
vbProperCase | 3 | first letter of each word to uppercase |
vbWide* | 4 | from Narrow to Wide |
vbNarrow* | 8 | from Wide to Narrow |
vbKatakana** | 16 | from Hiragana to Katakana |
vbHiragana | 32 | from Katakana to Hiragana |
vbUnicode | 64 | to unicode |
vbFromUnicode | 128 | from unicode |
Go back to menu
Using Strings With Arrays
Function | Params | Description | Example |
---|---|---|---|
Split | expression, delimiter, limit, compare |
Parses a delimited string to an array | arr = Split(«A;B;C»,»;») |
Join | source array, delimiter | Converts a one dimensional array to a string | s = Join(Arr, «;») |
String to Array using Split
You can easily parse a delimited string into an array. You simply use the Split function with the delimiter as parameter. The following code shows an example of using the Split function.
' https://excelmacromastery.com/ Sub StrToArr() Dim arr() As String ' Parse string to array arr = Split("John,Jane,Paul,Sophie", ",") Dim name As Variant For Each name In arr Debug.Print name Next End Sub
Output
John
Jane
Paul
Sophie
You can find a complete guide to the split function here.
Array to String using Join
If you want to build a string from an array you can do so easily using the Join function. This is essentially a reverse of the Split function. The following code provides an example of using Join
' https://excelmacromastery.com/ Sub ArrToStr() Dim Arr(0 To 3) As String Arr(0) = "John" Arr(1) = "Jane" Arr(2) = "Paul" Arr(3) = "Sophie" ' Build string from array Dim sNames As String sNames = Join(Arr, ",") Debug.Print sNames End Sub
Output
John,Jane,Paul,Sophie
Go back to menu
Formatting a String
Function | Params | Description | Example |
---|---|---|---|
Format | expression, format, firstdayofweek, firstweekofyear |
Formats a string | Format(0.5, «0.00%») |
The Format function is used to format a string based on given instructions. It is mostly used to place a date or number in certain format. The examples below show the most common ways you would format a date.
' https://excelmacromastery.com/ Sub FormatDate() Dim s As String s = "31/12/2015 10:15:45" ' Prints: 31 12 15 Debug.Print Format(s, "DD MM YY") ' Prints: Thu 31 Dec 2015 Debug.Print Format(s, "DDD DD MMM YYYY") ' Prints: Thursday 31 December 2015 Debug.Print Format(s, "DDDD DD MMMM YYYY") ' Prints: 10:15 Debug.Print Format(s, "HH:MM") ' Prints: 10:15:45 AM Debug.Print Format(s, "HH:MM:SS AM/PM") End Sub
The following examples are some common ways of formatting numbers
' https://excelmacromastery.com/ Sub FormatNumbers() ' Prints: 50.00% Debug.Print Format(0.5, "0.00%") ' Prints: 023.45 Debug.Print Format(23.45, "00#.00") ' Prints: 23,000 Debug.Print Format(23000, "##,000") ' Prints: 023,000 Debug.Print Format(23000, "0##,000") ' Prints: $23.99 Debug.Print Format(23.99, "$#0.00") End Sub
The Format function is quite a large topic and could use up a full post on it’s own. If you want more information then the MSDN Format Page provides a lot of information.
Helpful Tip for Using Format
A quick way to figure out the formatting to use is by using the cell formatting on an Excel worksheet. For example add a number to a cell. Then right click and format the cell the way you require. When you are happy with the format select Custom from the category listbox on the left. When you select this you can see the format string in the type textbox(see image below). This is the string format you can use in VBA.
Format Cells Dialog
Go back to menu
Conclusion
In almost any type of programming, you will spend a great deal of time manipulating strings. This post covers the many different ways you use strings in VBA.
To get the most from use the table at the top to find the type of function you wish to use. Clicking on the left column of this function will bring you to that section.
If you are new to strings in VBA, then I suggest you check out the Read this First section before using any of the functions.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)