Since this question is about string manipulation and doesn't have anything to do with shapes for convenience I will assume the input string to be in a variable called str
and the result to be output to the console. Adjust as necessary.
There are basically two approaches. The first uses the built-in functions InStr
to search in a string and Left
and Mid
to retrieve parts of a string:
Dim firstWordLocation As Long
Dim secondWordLocation As Long
firstWordLocation = InStr(str, firstWord)
secondWordLocation = InStr(str, secondWord)
If firstWordLocation > 0 And secondWordLocation > 0 Then
Debug.Print Left(str, firstWordLocation + Len(firstWord) - 1) & Mid(str, secondWordLocation)
End If
Another way to approach this is to use regular expressions. They are much more powerful and can perform complex string manipulations in a very compact way.
The library Microsoft VBScript Regular Expressions 5.5 provides a RegExp
class that can be used as follows, (also see https://stackoverflow.com/a/22542835 for more details):
Dim regex As New VBScript_RegExp_55.RegExp
regex.Pattern = "(.*?" & firstWord & ").*?(" & secondWord & ".*)"
Debug.Print regex.Replace(str, "$1$2")
This replaces the input string with the content of the first and second parenthesis in Pattern
, therefore omitting everything in between.
Be aware that the reserved characters .*+?()[]{}^$\
must be escaped with a backslash \
if they should occur in firstWord
or secondWord
.
If you have line breaks in your input string, you should have a look at https://superuser.com/q/399381.
If you want to place this string back in a shape and format certain parts of it using VBA, you have to use the Character
property of the TextRange
which represents each single text character in the shape. Now you can assign the desired format using those character objects.
See https://msdn.microsoft.com/de-de/library/office/ff743845.aspx for more (although that documentation is for PowerPoint, I think it will also apply to Word).