仅替换 VBA 中字符串中最后出现的匹配项 [英] Replace only last occurrence of match in a string in VBA
问题描述
我有一个这样的字符串
"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
并且必须将 Move_Help.txt
替换为 Move_Job.txt
and have to replace Move_Help.txt
with Move_Job.txt
我在 VBA EXCEL 中使用以下代码
I am using the below code in VBA EXCEL
str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
rlpStr = Replace(str, 'Help', 'Job')
我得到了
"C://Documents/TestUser/WWW/Job/Files/Move_Job.txt"
预期
"C://Documents/TestUser/WWW/Help/Files/Move_Job.txt"
你能帮忙解决这个问题吗?
Can you please help on this.
仅供参考:我无法将 Move_Help 与 Move_Job 匹配(Move_ 不是常量.它可以是任何字符串)
FYI : I can't match Move_Help to Move_Job (Move_ is not constant. It can be any string)
推荐答案
有一个单行解决方案:
rlpStr = StrReverse(Replace(StrReverse(str), StrReverse("Help"), StrReverse("Job"), , 1))
从技术上讲,它比组合 InStr
和 Replace
效率稍低,但如果需要,它可以在另一个表达式中使用.另外,我喜欢单行解决方案,只要它们不是难以理解的.
Technically, it's slightly less efficient than combining InStr
and Replace
but it can be used inside another expression if you need to. Also, I like the one-line solutions so long as they're not incomprehensible.
这篇关于仅替换 VBA 中字符串中最后出现的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!