VBA loop to replace all characters in a string and writing the result to a single cell (Excel)
What I'm trying to do is take开发者_开发知识库 user-inserted text from a cell and convert it to morse code, then write the result to a different cell. I can't figure out how to write the result, as my current code only saves the last character in the morse code array as changed in the output string (if it exists in the input string).
m is the number of characters in both arrays.
For i = 1 To m
output = Replace(input, A$(i), B$(i))
Next i
Range("output") = output
If I understand your question correctly I think the problem is that you're overwriting the output
in each iteration of the loop. Try changing your code to:
For i = 1 To m
output = output & Replace(input, A$(i), B$(i))
Next i
Range("output") = input
Note the added output &
which tells it to append the new value to the output rather than overwriting it.
It's cause you need to feed the output after your first iteration to Replace, not the unaltered input again and again.
Untested, just to give you a clue:
Dim strPuffer As String
strPuffer = Replace(input, A$(1), B$(1))
For i = 2 To m
strPuffer = Replace(strPuffer, A$(i), B$(i))
Next i
Range("output") = strPuffer
精彩评论