仅替换VBA中字符串中匹配的最后一次 [英] Replace only last occurrence of match in a string in VBA

查看:683
本文介绍了仅替换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"

你可以帮忙吗

FYI:我不能将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 替换稍微有效,但如果您使用需要。此外,我喜欢单行解决方案,只要它们不能理解。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆