Excel VBA - 删除* word *后的字符串内容

时间:2016-09-20 11:35:30

标签: vba excel-vba excel

我试图在字符串中包含的某个单词之前删除字符串内容。例如

master_of_desaster@live.de

我想使用VBA来替换

master_of_desaster

"之后的所有内容" (@)应删除,包括"字"本身。

我发现了一个类似的主题here,但他提出了相反的观点。

5 个答案:

答案 0 :(得分:3)

email = "master_of_desaster@live.de"

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

结果:master_of_desaster

感谢Shai Rado

答案 1 :(得分:2)

=split("master_of_desaster@live.de","@")(0)

答案 2 :(得分:2)

有点hacky但很快(大多数Windows API接受零终止字符串)

ret = Replace("master_of_disaster@live.de", "@", vbNullChar, , 1) ' Chr(0)

我通常使用Split方法,但使用Limit:

ret = Split("master_of_disaster@live.de", "@", 2)(0)

答案 3 :(得分:2)

只是为了好玩 - 一种正则表达式方法。

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 = "master_of_desaster@live.de"
    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

答案 4 :(得分:1)

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