-
I am workiing on a project that replaces some parts nof a string with new parts. Istr work great for replacement of the first appearence of the string to be replaced, but I need something that well find a second occerance in a line. I uswe line input to read one line at a time and Instr to find the string to replace, but it only finds the first occerance.
any body got any ideas?
-
Could you replace the first string your program found with whatever you want to replace it with and then perform the instr again to get to the next one?
Works only if you want to change EVERY string that you find.
-JR-
-
why not use the REPLACE() function instead? That takes care of all occurences in the string
-
more on general question
Jr. sorry that won't work, need to be able to feed project a text file with old company name and have vb identify old name and replace it with new name then after whole file read, output new file to txt file. I can get it to work but Instr only finds the first occerence in each line, I need to replace more then one occerence in a line.
-
Can't win all the time... :)
-
did you see my suggestion? Look ^
-
more on general question
crptcblade,
sounds like replace is the answer, I'll try it Thank You!
-
You need to loop throught the string:
Code:
Dim lPos as Long
Dim bFinished as Boolean
bFinished = False
While not bFinished
lPos = Instr(lPos, TheString, StringToFind)
If lPos > 0 then
'Replace the string here using Mid or whatever
Else
'Exit case
bFinished = True
End If
Wend
That will replace all instances of whatever is in the StringToFind variable that are in the TheString variable. You can modify the exit case to get out of the loop at any point (eg: after three insertions or something)
cheers
- gaffa
-
If you don't have VB6, here is the VB5 eqv.
Code:
Public Function Replace(sIn As String, sFind As String, _
sReplace As String, Optional nStart As Long = 1, _
Optional nCount As Long = -1, Optional bCompare As _
VbCompareMethod = vbBinaryCompare) As String
Dim nC As Long, nPos As Integer, sOut As String
sOut = sIn
nPos = InStr(nStart, sOut, sFind, bCompare)
If nPos = 0 Then GoTo EndFn:
Do
nC = nC + 1
sOut = Left(sOut, nPos - 1) & sReplace & _
Mid(sOut, nPos + Len(sFind))
If nCount <> -1 And nC >= nCount Then Exit Do
nPos = InStr(nStart, sOut, sFind, bCompare)
Loop While nPos > 0
EndFn:
Replace = sOut
End Function