Link to home
Start Free TrialLog in
Avatar of BuggyLogic
BuggyLogic

asked on

replace space with underscore

How do I replace space with underscore as such....

"Replacing this string with underscore"  into "Replacing_this_string_with_underscore" in VBA
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here is a Function that works in Excel VBA for your purpose:

Function FindAndReplace(strSource As String, strFind As String, strReplace As String)
Dim i As Long, temp As String
temp = strSource
Do
i = InStr(1, temp, strFind)
If i = 0 Then Exit Do
    temp = Left(temp, i - 1) & strReplace & Right(temp, Len(temp) - i - Len(strFind) + 1)
Loop
FindAndReplace = temp
End Function
Avatar of gafoorgk
gafoorgk

there is a built-in function in vba

Function Replace(Expression As String, Find As String, Replace As String, [Start As Long = 1], [Count As Long = -1], [Compare As VbCompareMethod = vbBinaryCompare]) As String
    Member of VBA.Strings
    Find and replace a substring within a string

eg:-
    Replace("Replacing this string with underscore", " ", "_")
Right you are gafoorgk--and it's a much better solution than my function
Below is a basic search and replace program

Replacing this string with underscore"  into "Replacing_this_string_with_underscore
Below is a basic search and replace program

Private Sub cmdrepl_Click()
    Dim strTemp As String
    Dim strSrch As String
    Dim strRepl As String

    strTemp = "Replacing this string with underscore"
    strSrch = " "
    strRepl = "_"

   'replace all occurrences of 'strSrch' in 'strTemp' with 'strRepl'
    strTemp = Replace(strTemp, strSrch, strRepl)
End Sub


In this code it is incoporated into a button click routine with hardcoded values in the function
Private Sub cmdrepl_Click()
        txtnewstr.Text = Replace(txtOrigStr, " ", "_")
        txtnewstr.Refresh
End Sub