Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - delete string content up to *word*

Tags:

string

excel

vba

I'm trying to delete string content up to a certain word contained within the string. For example

"Emily has wild flowers. They are red and blue."

I'd like to use VBA in order to replace that with

"They are red and blue."

i.e. remove all the content up to the word "They". I don't know the string content and the number of characters contained in it.

I'm not sure how to do this and I'd really appreciate your help!

like image 568
jcv Avatar asked Aug 23 '13 12:08

jcv


People also ask

How do I remove a word from a string in Excel VBA?

The basic VBA skill to remove characters from a string is with the Replace method. What is this? Example 1 is the most typical approach where the Replace method is used to remove all occurrences of specific character(s) from the input string.


2 Answers

Here you go:

Dim s As String
s = "Emily has wild flowers. They are red and blue."

Dim indexOfThey As Integer

indexOfThey = InStr(1, s, "They")


Dim finalString As String
finalString = Right(s, Len(s) - indexOfThey + 1)
like image 78
S Nash Avatar answered Oct 11 '22 11:10

S Nash


Simple example of dropping all text before value in string.

Sub Foo()
    Dim strOrig As String
    Dim strReplace As String
    strOrig = "The Quick brown fox jumped over the lazy dogs"
    strReplace = "jumped"

    MsgBox (DropTextBefore(strOrig, strReplace))

End Sub

Public Function DropTextBefore(strOrigin As String, strFind As String)
    Dim strOut As String
    Dim intFindPosition As Integer
    'case insensitive search
    'could made it so that case sensitivity is a parameter but this gets the idea across.
    If strOrigin <> "" And strFind <> "" Then
        intFindPosition = InStr(UCase(strOrigin), UCase(strFind))
        strOut = Right(strOrigin, Len(strOrigin) - (intFindPosition + Len(strFind) - 1))
    Else
      strOut = "Error Empty Parameter in function call was encountered."
    End If
    DropTextBefore = strOut
End Function
like image 35
xQbert Avatar answered Oct 11 '22 10:10

xQbert