5

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

[email protected]

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

master_of_desaster

Everything after the "word" (@) should be removed, including the "word" itself.

I found a similar topic here, but he asks the opposite.

3
  • 2
    find the @ using Instr function. Then, just use Left of the original string up to the result of Instr Commented Sep 20, 2016 at 11:37
  • 1
    Possible duplicate of VBA, excel cut a part from a string Commented Sep 20, 2016 at 12:19
  • If you are doing this on cells, a simple Find/Replace may well be fastest. Commented Sep 20, 2016 at 12:38

5 Answers 5

5
email = "[email protected]"

ret = Left(email, InStr(1, email, "@") - 1)

Result: master_of_desaster

Thanks to Shai Rado

Sign up to request clarification or add additional context in comments.

Comments

4

=split("[email protected]","@")(0)

1 Comment

If you add comments to it, then i will accept it as the solution. (I understand it, but will others do?)
2

Just for fun - a regex approach.

Public Sub reg()

    Dim re_pattern As String
    Dim re As RegExp
    Dim email As String
    Dim match As Object

    Set re = New RegExp

    email = "[email protected]"
    re_pattern = "(.*)@.*"

    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = re_pattern
    End With

    Set match = re.Execute(email)

    Debug.Print match.Item(0).SubMatches(0)

End Sub

Comments

2

A bit hacky but fast ( most Windows API accept zero terminated strings )

ret = Replace("[email protected]", "@", vbNullChar, , 1) ' Chr(0)

I usually use the Split method but with Limit:

ret = Split("[email protected]", "@", 2)(0)

Comments

1
ret = evaluate("left(" & string & ", search(""@"", " & string & ") - 1)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.