PDA

View Full Version : Solved: String Division by Index



tmptplayer
05-18-2011, 02:09 AM
Greetings All,

I have a question that should be simple but I can't recall the proper functions that will make this work for me. Specifically, I am wondering how to divide a string in two based on an index of length within the string (such as one that would be returned by 'instr').

The big picture is that I'm trying to replace a string of characters within a string expression, however I only want to replace the string once, and I want it to be after the previous string insert. Using the replace function, it is easy to find and replace the necessary string using a steadily incremented starting location in the search string. Here is my initial code:


Do
x = y
countString = CStr(counter) + ". "
replString = "*^*^" + CStr(counter) + "~"
startLoc = InStr(startLoc, y, countString, CompareVal)
y = Replace(y, countString, replString, startLoc, 1, CompareVal)
counter = counter + 1
Loop While (y <> x)


The problem with this logic is that the Replace function only returns the string from the starting location onwards. So what I want to do is to initially divide the string at the index of where I want to do the string replacement, and then concatenate the first half with the result of the Replace function. Is there a function that will do this string splitting for me (I'm aware of Split, but I don't have a delimiter)? Also note that the variable being searched for will not necessarily be unique; there will be multiple instances throughout the document, and I only want this specific instance to be replaced.

GTO
05-18-2011, 02:38 AM
Hi there,

I'm not exactly following, but does this help?
Sub test()
Dim strInitial As String, strTemp As String, strMatch As String

strMatch = "tiny"

strInitial = "Mary had a tiny tiny lamb"

strTemp = Left(strInitial, InStr(1, strInitial, strMatch) - 1)
strInitial = Mid(strInitial, InStr(1, strInitial, strMatch))
End Sub

tmptplayer
05-18-2011, 03:48 AM
Hey,

Thanks a lot. My modified code is below. The Left function was exactly what I was looking for. Sorry- rookie mistake.


Do
x = y
countString = CStr(counter) + ". "
replString = "*^*^" + CStr(counter) + "~"
startLoc = InStr(startLoc, y, countString, CompareVal)
If (startLoc <> 0) Then
y = Left(y, startLoc - 1) + Replace(y, countString, replString, startLoc, 1, CompareVal)
counter = counter + 1
End If
Loop While (y <> x)