Replace only last occurrence of match in a string in VBA

后端 未结 3 1659
不知归路
不知归路 2020-12-10 07:51

I have a string like this

\"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt\"

and have to replace Move_Help.txt

相关标签:
3条回答
  • 2020-12-10 08:29

    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.

    0 讨论(0)
  • 2020-12-10 08:30

    Would the technique in the code below meet your requirement?

    The intial value of Str is:

     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.

    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
    
    0 讨论(0)
  • 2020-12-10 08:31

    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

    Wscript.Echo Str

    0 讨论(0)
提交回复
热议问题