Web Development
2 replies
by shanghai sam
Public Function Sreplace(str As String) As String
Dim Pos As Integer
Dim Found As Integer
Dim vSearchline As String
Pos = 0
vSearchline = str
Do While InStr(Pos + 1, vSearchline, " ", vbDatabaseCompare) <> 0
Found = InStr(Pos + 1,vSearchline, " ", vbDatabaseCompare)
Pos = InStr(Pos + 1, vSearchline, "", vbDatabaseCompare)
vSearchline = Left(vSearchline, Found - 1) + "+" + Right(vSearchline, Len(vSearchline) - (Found + 1))
Loop
End Function
by bob sellman
While the answer posted above has the right basic idea, there are some problems with it, such as not handling the beginning and end of the starting text correctly and only working for one replacement.
Here's a function that will do the job and allow you to enter any character to find and any character to replace it with. I did not include some error checking that you might want to add, either within the function or externally. See my comments after the function for ideas on these.
Public Function SReplace(strText As String, strFind As String, strReplace As String)
Dim intLength As Long
Dim intX As Long
Dim strNewText As String
intLength = Len(strText)
For intX = 1 To intLength
If InStr(MID$(strText, intX, 1), strFind) > 0Then
If intX = 1 Then
strText = strReplace & MID$(strText, 2, intLength - 1)
Else
If intX < intLength Then
strText = Left$(strText, intX - 1) & strReplace & MID$(strText, intX + 1, intLength - intX) Else
strText = Left$(strText, intLength - 1) & strReplace
End If
End If
End If
Next intX
SReplace = strText
End Function
A few notes:
1. Be sure the character to look for (strFind) passed to the function is one character long. In the case of a space, be sure it is one space (" ") and not a null.
2. If the text (strText) being "fixed" could be one character long, you need to add another if statement within the function that checks for that condition and if it is true, replaces the entire strText with strReplace.
This function can be used in your VBA code as well as your query. In the VBA code it provides more flexilibity because you can prompt the user to supply the character to find and the replacement character.
This discussion is closed to new replies.
Trending Web Development posts
Sort by Trending