By request, this is a explanation and sample project for utilizing the built-in Replace function for VB6.
Finding and replacing text within a string is relatively speaking one of the more common functions you’ll perform when working with text. Fortunately, VB6 has included some functions for easing the burden of working with text.
One of these built-in functions is Replace. Replace does just what you would think; it searches a string of text for another string of text (or substring), and replaces it with a specified bit of text. Don’t worry, it’s not as complicated as it sounds.
Syntax
The command has a pretty straightforward syntax, and is actually pretty easy to work with. Here is the basic syntax for using it:
strTargetString = Replace(strStringToBeSearched, strStringToFind, strStringToReplace)
Pretty easy, no?
Explanation
I’ve made the variables in the example pretty self-explanatory, but here is brief expansion on that.
- strTargetString – where the modified string of text will end up. You can replace text in one string, storing the results in another string.
- strStringToBeSearched – the string to be searched for the substring.
- strStringToFind – this is the string that we want to find in the string to be searched.
- strStringToReplace – when the substring is found, it will be replaced with this string.
QuickHint
It’s generally good practice, at least in my opinion, to store the values of controls in variables, work with the data in the variables, then write the modified values back to the controls.
Working with the variables gives you some flexibility if your data requires multiple modifications, and you’re only writing data to the controls (like a textbox) once, instead of multiple times.
In the case of a textbox, the data in the textbox is updated as it is written. If you have an especially long block of text in the textbox, this can introduce a delay or slowdown in your program. Make sense?
Summary
The Replace function makes it quick and easy to replace text inside another text string, with a third string. It sounds complicated, but it’s not really, and you’ll get the hang of it very quickly.
I’ve included a demonstration project with this post, so that you may see the function in action.
Attachments
File | Uploaded | Size |
---|---|---|
389-20180624-063630-SearchReplaceSample.zip | 6/24/2018 6:36:30 AM | 42738 |