仅替换 VBA 中字符串中最后出现的匹配项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24394833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace only last occurrence of match in a string in VBA
提问by Isaac G Sivaa
I have a string like this
我有一个这样的字符串
"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
and have to replace Move_Help.txt
with Move_Job.txt
并且必须替换Move_Help.txt
为Move_Job.txt
I am using the below code in VBA EXCEL
我在 VBA EXCEL 中使用以下代码
str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
rlpStr = Replace(str, 'Help', 'Job')
I am getting
我正进入(状态
"C://Documents/TestUser/WWW/Job/Files/Move_Job.txt"
Expected
预期的
"C://Documents/TestUser/WWW/Help/Files/Move_Job.txt"
Can you please help on this.
你能帮忙解决这个问题吗?
FYI : I can't match Move_Help to Move_Job (Move_ is not constant. It can be any string)
仅供参考:我无法将 Move_Help 与 Move_Job 匹配(Move_ 不是常量。它可以是任何字符串)
回答by Engineer Toast
There's a one-line solution for this:
有一个单行解决方案:
rlpStr = StrReverse(Replace(StrReverse(str), StrReverse("Help"), StrReverse("Job"), , 1))
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.
从技术上讲,它的效率略低于组合InStr
,Replace
但如果需要,它可以在另一个表达式中使用。此外,我喜欢单行解决方案,只要它们不是不可理解的。
回答by Tony Dallimore
Would the technique in the code below meet your requirement?
下面代码中的技术是否符合您的要求?
The intial value of Str is:
Str 的初始值为:
C://Documents/TestUser/WWW/Help/Files/Move_Help.txt
The final value is:
最终值为:
C://Documents/TestUser/WWW/Help/Files/Move_Job.txt
The code uses InStrRev
to locate the last occurrence of ValueCrnt
, if any, If ValueCrnt
is present, it replaces that final occurrence with ValueNew
.
该代码用于InStrRev
定位 的最后一次出现(ValueCrnt
如果有),如果ValueCrnt
存在,则将最后一次出现的 替换为ValueNew
。
Option Explicit
Sub Demo()
Dim Pos As Long
Dim Str As String
Dim ValueCrnt As String
Dim ValueNew As String
Str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
ValueCrnt = "Help"
ValueNew = "Job"
Pos = InStrRev(Str, ValueCrnt)
If Pos > 0 Then
Str = Mid(Str, 1, Pos - 1) & Replace(Str, ValueCrnt, ValueNew, Pos)
End If
Debug.Print Str
End Sub