VBA – Replace String
The Replace
function in VBA is used to replace all occurrences of a specified substring within a given string with another string.
Syntax:
Replace(string, find, replacewith[, start[, count]])
Parameter:
find
.string
to start the search. If omitted, the search begins at the first character.
Return Value:
Example
Dim str1 As String
Dim newStr As String
str1 = "Hello, World! Hello again!"
newStr = Replace(str1, "Hello", "Hi")
' newStr will be "Hi, World! Hi again!"
newStr = Replace(str1, "Hello", "Hi", 1)
' newStr will be "Hi, World! Hello again!" (Only the first occurrence is replaced)
Use Cases:
Key Considerations:
Replace
function is case-sensitive by default.StrConv
function to convert the strings to uppercase or lowercase before using Replace
.Example: (Case-Insensitive)
Dim str1 As String
Dim newStr As String
str1 = "Hello, World! Hello again!"
newStr = Replace(StrConv(str1, vbUpperCase), "HELLO", "Hi")
' newStr will be "Hi, World! Hi again!"