VBA Code to Modify String by Changing the last word between the second to the last backslash and then last one

OilEconomist

Active Member
Joined
Dec 26, 2016
Messages
441
Office Version
  1. 2019
Platform
  1. Windows
Thanks in advance for any help given!

What is the VBA Code to take an existing string and modify the last word. I would like to change e-mails to attachments.

For example, I have the directory stored:
C:\Files\Section A\e-mails\

and I would like to modify it to:
C:\Files\Section A\Attachments\

VBA Code:
Option Explicit

Sub Modify_String()

Dim String_Org As String, String_New As String


String_Org = "C:\Files\Section A\e-mails\"

'Code to change String_Org to "C:\Files\Section A\Attachments\" and store it as String_Mod
    
    'String_Mod = ?

End Sub
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
The phrasing of your question confuses me, but to change the last "word" of a string requires either length or delimiter. It looks like, in your case, the string will be a file location so "\" will be the delimiter. Here is a generic code block to change the last "word" of a string. Modify it to suit your needs.
VBA Code:
Option Explicit

Sub ChangeLastWord()

Dim base_string As String, change_last As String, new_string As String

base_string = "C:\Users\User1\Documents"

change_last = "Pictures"

new_string = Left(base_string, Len(base_string) - InStr(1, base_string, "User1\")) & "\" & change_last

End Sub
 
Upvote 0

Forum statistics

Threads
1,225,669
Messages
6,186,346
Members
453,349
Latest member
neam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top