VBA Replace Function not working as expected

mamboq

Board Regular
Joined
Nov 15, 2008
Messages
67
In VBA help, the syntax for the replace function is: Replace(expression, find, replace, [start], [count], [compare])

I tried the following (in VBA): Msgbox Replace("Green apple", "e", "a", 7)

I was expecting "Green appla" to be the returned text, but only "appla" was returned. Is this correct? I thought the start argument was the position where the function starts looking for the 'find' substring, not the position at which the returned value begins.

My example was taken from the following page: http://www.webcheatsheet.com/SQL/access_functions/replace.php

That page is about Access, but I'm sure it's the same function in Excel - in any case, the 'unexpected' result ("appla") is identical in both access and excel.
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
Yes, I've come up against this myself.

The way I got round it was to write a separate function that took the 'position' argument and chopped the string up using left

Code:
Function midReplace(str, a, b, p)
    midReplace = Left(str, p - 1) & Replace(str, a, b, p)
End Function
 
Upvote 0
Alternatively, you can use the excel substitute function:

Code:
MsgBox Application.WorksheetFunction.Substitute("Green apple", "e", "a", 3)

Note the slight differences in the functions:

REPLACE(text, old_text, new_text [, start [, count[, compare]]]) where start is the position in the expression

Application.WorksheetFunction.SUBSTITUTE(text, old_text, new_text [, instance_num]) where instance_num is the occurrence in the expression

This is why the original value of 7 had to change to 3
 
Upvote 0

Forum statistics

Threads
1,214,613
Messages
6,120,515
Members
448,968
Latest member
Ajax40

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top